com.google.bitcoin.core.Peer Maven / Gradle / Ivy
/**
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.BlockStoreException;
import com.google.bitcoin.utils.ListenerRegistration;
import com.google.bitcoin.utils.Threading;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import net.jcip.annotations.GuardedBy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* A Peer handles the high level communication with a Bitcoin node, extending a {@link PeerSocketHandler} which
* handles low-level message (de)serialization.
*
* Note that timeouts are handled by the extended
* {@link com.google.bitcoin.net.AbstractTimeoutHandler} and timeout is automatically disabled (using
* {@link com.google.bitcoin.net.AbstractTimeoutHandler#setTimeoutEnabled(boolean)}) once the version
* handshake completes.
*/
public class Peer extends PeerSocketHandler {
private static final Logger log = LoggerFactory.getLogger(Peer.class);
protected final ReentrantLock lock = Threading.lock("peer");
private final NetworkParameters params;
private final AbstractBlockChain blockChain;
// onPeerDisconnected should not be called directly by Peers when a PeerGroup is involved (we don't know the total
// number of connected peers), thus we use a wrapper that PeerGroup can use to register listeners that wont get
// onPeerDisconnected calls
static class PeerListenerRegistration extends ListenerRegistration {
boolean callOnDisconnect = true;
public PeerListenerRegistration(PeerEventListener listener, Executor executor) {
super(listener, executor);
}
public PeerListenerRegistration(PeerEventListener listener, Executor executor, boolean callOnDisconnect) {
this(listener, executor);
this.callOnDisconnect = callOnDisconnect;
}
}
private final CopyOnWriteArrayList eventListeners;
// Whether to try and download blocks and transactions from this peer. Set to false by PeerGroup if not the
// primary peer. This is to avoid redundant work and concurrency problems with downloading the same chain
// in parallel.
private volatile boolean vDownloadData;
// The version data to announce to the other side of the connections we make: useful for setting our "user agent"
// equivalent and other things.
private final VersionMessage versionMessage;
// How many block messages the peer has announced to us. Peers only announce blocks that attach to their best chain
// so we can use this to calculate the height of the peers chain, by adding it to the initial height in the version
// message. This method can go wrong if the peer re-orgs onto a shorter (but harder) chain, however, this is rare.
private final AtomicInteger blocksAnnounced = new AtomicInteger();
// A class that tracks recent transactions that have been broadcast across the network, counts how many
// peers announced them and updates the transaction confidence data. It is passed to each Peer.
private final MemoryPool memoryPool;
// Each wallet added to the peer will be notified of downloaded transaction data.
private final CopyOnWriteArrayList wallets;
// A time before which we only download block headers, after that point we download block bodies.
@GuardedBy("lock") private long fastCatchupTimeSecs;
// Whether we are currently downloading headers only or block bodies. Starts at true. If the fast catchup time is
// set AND our best block is before that date, switch to false until block headers beyond that point have been
// received at which point it gets set to true again. This isn't relevant unless vDownloadData is true.
@GuardedBy("lock") private boolean downloadBlockBodies = true;
// Whether to request filtered blocks instead of full blocks if the protocol version allows for them.
@GuardedBy("lock") private boolean useFilteredBlocks = false;
// The current Bloom filter set on the connection, used to tell the remote peer what transactions to send us.
private volatile BloomFilter vBloomFilter;
// The last filtered block we received, we're waiting to fill it out with transactions.
private FilteredBlock currentFilteredBlock = null;
// How many filtered blocks have been received during the lifetime of this connection. Used to decide when to
// refresh the server-side side filter by sending a new one (it degrades over time as false positives are added
// on the remote side, see BIP 37 for a discussion of this).
private int filteredBlocksReceived;
// How frequently to refresh the filter. This should become dynamic in future and calculated depending on the
// actual false positive rate. For now a good value was determined empirically around January 2013.
private static final int RESEND_BLOOM_FILTER_BLOCK_COUNT = 25000;
// Keeps track of things we requested internally with getdata but didn't receive yet, so we can avoid re-requests.
// It's not quite the same as getDataFutures, as this is used only for getdatas done as part of downloading
// the chain and so is lighter weight (we just keep a bunch of hashes not futures).
//
// It is important to avoid a nasty edge case where we can end up with parallel chain downloads proceeding
// simultaneously if we were to receive a newly solved block whilst parts of the chain are streaming to us.
private final HashSet pendingBlockDownloads = new HashSet();
// The lowest version number we're willing to accept. Lower than this will result in an immediate disconnect.
private volatile int vMinProtocolVersion = Pong.MIN_PROTOCOL_VERSION;
// When an API user explicitly requests a block or transaction from a peer, the InventoryItem is put here
// whilst waiting for the response. Is not used for downloads Peer generates itself.
private static class GetDataRequest {
Sha256Hash hash;
SettableFuture future;
// If the peer does not support the notfound message, we'll use ping/pong messages to simulate it. This is
// a nasty hack that relies on the fact that bitcoin-qt is single threaded and processes messages in order.
// The nonce field records which pong should clear this request as "not found".
long nonce;
}
private final CopyOnWriteArrayList getDataFutures;
// Outstanding pings against this peer and how long the last one took to complete.
private final ReentrantLock lastPingTimesLock = new ReentrantLock();
@GuardedBy("lastPingTimesLock") private long[] lastPingTimes = null;
private final CopyOnWriteArrayList pendingPings;
private static final int PING_MOVING_AVERAGE_WINDOW = 20;
private volatile VersionMessage vPeerVersionMessage;
private boolean isAcked;
// A settable future which completes (with this) when the connection is open
private final SettableFuture connectionOpenFuture = SettableFuture.create();
/**
* Construct a peer that reads/writes from the given block chain.
*
* Note that this does NOT make a connection to the given remoteAddress, it only creates a handler for a
* connection. If you want to create a one-off connection, create a Peer and pass it to
* {@link com.google.bitcoin.net.NioClientManager#openConnection(java.net.SocketAddress, com.google.bitcoin.net.StreamParser)}
* or
* {@link com.google.bitcoin.net.NioClient#NioClient(java.net.SocketAddress, com.google.bitcoin.net.StreamParser, int)}.
*
* The remoteAddress provided should match the remote address of the peer which is being connected to, and is
* used to keep track of which peers relayed transactions and offer more descriptive logging.
*/
public Peer(NetworkParameters params, VersionMessage ver, @Nullable AbstractBlockChain chain, PeerAddress remoteAddress) {
this(params, ver, remoteAddress, chain, null);
}
/**
* Construct a peer that reads/writes from the given block chain and memory pool. Transactions stored in a memory
* pool will have their confidence levels updated when a peer announces it, to reflect the greater likelyhood that
* the transaction is valid.
*
* Note that this does NOT make a connection to the given remoteAddress, it only creates a handler for a
* connection. If you want to create a one-off connection, create a Peer and pass it to
* {@link com.google.bitcoin.net.NioClientManager#openConnection(java.net.SocketAddress, com.google.bitcoin.net.StreamParser)}
* or
* {@link com.google.bitcoin.net.NioClient#NioClient(java.net.SocketAddress, com.google.bitcoin.net.StreamParser, int)}.
*
* The remoteAddress provided should match the remote address of the peer which is being connected to, and is
* used to keep track of which peers relayed transactions and offer more descriptive logging.
*/
public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress,
@Nullable AbstractBlockChain chain, @Nullable MemoryPool mempool) {
super(params, remoteAddress);
this.params = Preconditions.checkNotNull(params);
this.versionMessage = Preconditions.checkNotNull(ver);
this.blockChain = chain; // Allowed to be null.
this.vDownloadData = chain != null;
this.getDataFutures = new CopyOnWriteArrayList();
this.eventListeners = new CopyOnWriteArrayList();
this.fastCatchupTimeSecs = params.getGenesisBlock().getTimeSeconds();
this.isAcked = false;
this.pendingPings = new CopyOnWriteArrayList();
this.wallets = new CopyOnWriteArrayList();
this.memoryPool = mempool;
}
/**
* Construct a peer that reads/writes from the given chain. Automatically creates a VersionMessage for you from
* the given software name/version strings, which should be something like "MySimpleTool", "1.0" and which will tell
* the remote node to relay transaction inv messages before it has received a filter.
*
* Note that this does NOT make a connection to the given remoteAddress, it only creates a handler for a
* connection. If you want to create a one-off connection, create a Peer and pass it to
* {@link com.google.bitcoin.net.NioClientManager#openConnection(java.net.SocketAddress, com.google.bitcoin.net.StreamParser)}
* or
* {@link com.google.bitcoin.net.NioClient#NioClient(java.net.SocketAddress, com.google.bitcoin.net.StreamParser, int)}.
*
* The remoteAddress provided should match the remote address of the peer which is being connected to, and is
* used to keep track of which peers relayed transactions and offer more descriptive logging.
*/
public Peer(NetworkParameters params, AbstractBlockChain blockChain, PeerAddress peerAddress, String thisSoftwareName, String thisSoftwareVersion) {
this(params, new VersionMessage(params, blockChain.getBestChainHeight(), true), blockChain, peerAddress);
this.versionMessage.appendToSubVer(thisSoftwareName, thisSoftwareVersion, null);
}
/**
* Registers the given object as an event listener that will be invoked on the user thread. Note that listeners
* added this way will not receive {@link PeerEventListener#getData(Peer, GetDataMessage)} or
* {@link PeerEventListener#onPreMessageReceived(Peer, Message)} calls because those require that the listener
* be added using {@link Threading#SAME_THREAD}, which requires the other addListener form.
*/
public void addEventListener(PeerEventListener listener) {
addEventListener(listener, Threading.USER_THREAD);
}
/**
* Registers the given object as an event listener that will be invoked by the given executor. Note that listeners
* added using any other executor than {@link Threading#SAME_THREAD} will not receive
* {@link PeerEventListener#getData(Peer, GetDataMessage)} or
* {@link PeerEventListener#onPreMessageReceived(Peer, Message)} calls because this class is not willing to cross
* threads in order to get the results of those hook methods.
*/
public void addEventListener(PeerEventListener listener, Executor executor) {
eventListeners.add(new PeerListenerRegistration(listener, executor));
}
// Package-local version for PeerGroup
void addEventListenerWithoutOnDisconnect(PeerEventListener listener, Executor executor) {
eventListeners.add(new PeerListenerRegistration(listener, executor, false));
}
public boolean removeEventListener(PeerEventListener listener) {
return ListenerRegistration.removeFromList(listener, eventListeners);
}
@Override
public String toString() {
PeerAddress addr = getAddress();
if (addr == null) {
// User-provided NetworkConnection object.
return "Peer()";
} else {
return addr.toString();
}
}
@Override
public void connectionClosed() {
for (final PeerListenerRegistration registration : eventListeners) {
if (registration.callOnDisconnect)
registration.executor.execute(new Runnable() {
@Override
public void run() {
registration.listener.onPeerDisconnected(Peer.this, 0);
}
});
}
}
@Override
public void connectionOpened() {
// Announce ourselves. This has to come first to connect to clients beyond v0.3.20.2 which wait to hear
// from us until they send their version message back.
PeerAddress address = getAddress();
log.info("Announcing to {} as: {}", address == null ? "Peer" : address.toSocketAddress(), versionMessage.subVer);
sendMessage(versionMessage);
connectionOpenFuture.set(this);
// When connecting, the remote peer sends us a version message with various bits of
// useful data in it. We need to know the peer protocol version before we can talk to it.
}
/**
* Provides a ListenableFuture that can be used to wait for the socket to connect. A socket connection does not
* mean that protocol handshake has occurred.
*/
public ListenableFuture getConnectionOpenFuture() {
return connectionOpenFuture;
}
protected void processMessage(Message m) throws Exception {
// Allow event listeners to filter the message stream. Listeners are allowed to drop messages by
// returning null.
for (ListenerRegistration registration : eventListeners) {
// Skip any listeners that are supposed to run in another thread as we don't want to block waiting
// for it, which might cause circular deadlock.
if (registration.executor == Threading.SAME_THREAD) {
m = registration.listener.onPreMessageReceived(this, m);
if (m == null) break;
}
}
if (m == null) return;
// If we are in the middle of receiving transactions as part of a filtered block push from the remote node,
// and we receive something that's not a transaction, then we're done.
if (currentFilteredBlock != null && !(m instanceof Transaction)) {
endFilteredBlock(currentFilteredBlock);
currentFilteredBlock = null;
}
if (m instanceof NotFoundMessage) {
// This is sent to us when we did a getdata on some transactions that aren't in the peers memory pool.
// Because NotFoundMessage is a subclass of InventoryMessage, the test for it must come before the next.
processNotFoundMessage((NotFoundMessage) m);
} else if (m instanceof InventoryMessage) {
processInv((InventoryMessage) m);
} else if (m instanceof Block) {
processBlock((Block) m);
} else if (m instanceof FilteredBlock) {
startFilteredBlock((FilteredBlock) m);
} else if (m instanceof Transaction) {
processTransaction((Transaction) m);
} else if (m instanceof GetDataMessage) {
processGetData((GetDataMessage) m);
} else if (m instanceof AddressMessage) {
// We don't care about addresses of the network right now. But in future,
// we should save them in the wallet so we don't put too much load on the seed nodes and can
// properly explore the network.
} else if (m instanceof HeadersMessage) {
processHeaders((HeadersMessage) m);
} else if (m instanceof AlertMessage) {
processAlert((AlertMessage) m);
} else if (m instanceof VersionMessage) {
processVersionMessage((VersionMessage) m);
} else if (m instanceof VersionAck) {
if (vPeerVersionMessage == null) {
throw new ProtocolException("got a version ack before version");
}
if (isAcked) {
throw new ProtocolException("got more than one version ack");
}
isAcked = true;
this.setTimeoutEnabled(false);
for (final ListenerRegistration registration : eventListeners) {
registration.executor.execute(new Runnable() {
@Override
public void run() {
registration.listener.onPeerConnected(Peer.this, 1);
}
});
}
// We check min version after onPeerConnected as channel.close() will
// call onPeerDisconnected, and we should probably call onPeerConnected first.
final int version = vMinProtocolVersion;
if (vPeerVersionMessage.clientVersion < version) {
log.warn("Connected to a peer speaking protocol version {} but need {}, closing",
vPeerVersionMessage.clientVersion, version);
close();
}
} else if (m instanceof Ping) {
if (((Ping) m).hasNonce())
sendMessage(new Pong(((Ping) m).getNonce()));
} else if (m instanceof Pong) {
processPong((Pong)m);
} else {
log.warn("Received unhandled message: {}", m);
}
}
private void processVersionMessage(VersionMessage m) throws ProtocolException {
if (vPeerVersionMessage != null)
throw new ProtocolException("Got two version messages from peer");
vPeerVersionMessage = m;
// Switch to the new protocol version.
int peerVersion = vPeerVersionMessage.clientVersion;
PeerAddress peerAddress = getAddress();
long peerTime = vPeerVersionMessage.time * 1000;
log.info("Connected to {}: version={}, subVer='{}', services=0x{}, time={}, blocks={}",
peerAddress == null ? "Peer" : peerAddress.getAddr().getHostAddress(),
peerVersion,
vPeerVersionMessage.subVer,
vPeerVersionMessage.localServices,
String.format("%tF %tT", peerTime, peerTime),
vPeerVersionMessage.bestHeight);
// Now it's our turn ...
// Send an ACK message stating we accept the peers protocol version.
sendMessage(new VersionAck());
// bitcoinj is a client mode implementation. That means there's not much point in us talking to other client
// mode nodes because we can't download the data from them we need to find/verify transactions. Some bogus
// implementations claim to have a block chain in their services field but then report a height of zero, filter
// them out here.
if (!vPeerVersionMessage.hasBlockChain() ||
(!params.allowEmptyPeerChain() && vPeerVersionMessage.bestHeight <= 0)) {
// Shut down the channel
throw new ProtocolException("Peer does not have a copy of the block chain.");
}
}
private void startFilteredBlock(FilteredBlock m) {
// Filtered blocks come before the data that they refer to, so stash it here and then fill it out as
// messages stream in. We'll call endFilteredBlock when a non-tx message arrives (eg, another
// FilteredBlock) or when a tx that isn't needed by that block is found. A ping message is sent after
// a getblocks, to force the non-tx message path.
currentFilteredBlock = m;
// Potentially refresh the server side filter. Because the remote node adds hits back into the filter
// to save round-tripping back through us, the filter degrades over time as false positives get added,
// triggering yet more false positives. We refresh it every so often to get the FP rate back down.
filteredBlocksReceived++;
if (filteredBlocksReceived % RESEND_BLOOM_FILTER_BLOCK_COUNT == RESEND_BLOOM_FILTER_BLOCK_COUNT - 1) {
sendMessage(vBloomFilter);
}
}
private void processNotFoundMessage(NotFoundMessage m) {
// This is received when we previously did a getdata but the peer couldn't find what we requested in it's
// memory pool. Typically, because we are downloading dependencies of a relevant transaction and reached
// the bottom of the dependency tree (where the unconfirmed transactions connect to transactions that are
// in the chain).
//
// We go through and cancel the pending getdata futures for the items we were told weren't found.
for (GetDataRequest req : getDataFutures) {
for (InventoryItem item : m.getItems()) {
if (item.hash.equals(req.hash)) {
log.info("{}: Bottomed out dep tree at {}", this, req.hash);
req.future.cancel(true);
getDataFutures.remove(req);
break;
}
}
}
}
private void processAlert(AlertMessage m) {
try {
if (m.isSignatureValid()) {
log.info("Received alert from peer {}: {}", toString(), m.getStatusBar());
} else {
log.warn("Received alert with invalid signature from peer {}: {}", toString(), m.getStatusBar());
}
} catch (Throwable t) {
// Signature checking can FAIL on Android platforms before Gingerbread apparently due to bugs in their
// BigInteger implementations! See issue 160 for discussion. As alerts are just optional and not that
// useful, we just swallow the error here.
log.error("Failed to check signature: bug in platform libraries?", t);
}
}
private void processHeaders(HeadersMessage m) throws ProtocolException {
// Runs in network loop thread for this peer.
//
// This method can run if a peer just randomly sends us a "headers" message (should never happen), or more
// likely when we've requested them as part of chain download using fast catchup. We need to add each block to
// the chain if it pre-dates the fast catchup time. If we go past it, we can stop processing the headers and
// request the full blocks from that point on instead.
boolean downloadBlockBodies;
long fastCatchupTimeSecs;
lock.lock();
try {
if (blockChain == null) {
// Can happen if we are receiving unrequested data, or due to programmer error.
log.warn("Received headers when Peer is not configured with a chain.");
return;
}
fastCatchupTimeSecs = this.fastCatchupTimeSecs;
downloadBlockBodies = this.downloadBlockBodies;
} finally {
lock.unlock();
}
try {
checkState(!downloadBlockBodies, toString());
for (int i = 0; i < m.getBlockHeaders().size(); i++) {
Block header = m.getBlockHeaders().get(i);
// Process headers until we pass the fast catchup time, or are about to catch up with the head
// of the chain - always process the last block as a full/filtered block to kick us out of the
// fast catchup mode (in which we ignore new blocks).
boolean passedTime = header.getTimeSeconds() >= fastCatchupTimeSecs;
boolean reachedTop = blockChain.getBestChainHeight() >= vPeerVersionMessage.bestHeight;
if (!passedTime && !reachedTop) {
if (!vDownloadData) {
// Not download peer anymore, some other peer probably became better.
log.info("Lost download peer status, throwing away downloaded headers.");
return;
}
if (blockChain.add(header)) {
// The block was successfully linked into the chain. Notify the user of our progress.
invokeOnBlocksDownloaded(header);
} else {
// This block is unconnected - we don't know how to get from it back to the genesis block yet.
// That must mean that the peer is buggy or malicious because we specifically requested for
// headers that are part of the best chain.
throw new ProtocolException("Got unconnected header from peer: " + header.getHashAsString());
}
} else {
lock.lock();
try {
log.info("Passed the fast catchup time, discarding {} headers and requesting full blocks",
m.getBlockHeaders().size() - i);
this.downloadBlockBodies = true;
// Prevent this request being seen as a duplicate.
this.lastGetBlocksBegin = Sha256Hash.ZERO_HASH;
blockChainDownloadLocked(Sha256Hash.ZERO_HASH);
} finally {
lock.unlock();
}
return;
}
}
// We added all headers in the message to the chain. Request some more if we got up to the limit, otherwise
// we are at the end of the chain.
if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS) {
lock.lock();
try {
blockChainDownloadLocked(Sha256Hash.ZERO_HASH);
} finally {
lock.unlock();
}
}
} catch (VerificationException e) {
log.warn("Block header verification failed", e);
} catch (PrunedException e) {
// Unreachable when in SPV mode.
throw new RuntimeException(e);
}
}
private void processGetData(GetDataMessage getdata) {
log.info("{}: Received getdata message: {}", getAddress(), getdata.toString());
ArrayList items = new ArrayList();
for (ListenerRegistration registration : eventListeners) {
if (registration.executor != Threading.SAME_THREAD) continue;
List listenerItems = registration.listener.getData(this, getdata);
if (listenerItems == null) continue;
items.addAll(listenerItems);
}
if (items.size() == 0) {
return;
}
log.info("{}: Sending {} items gathered from listeners to peer", getAddress(), items.size());
for (Message item : items) {
sendMessage(item);
}
}
private void processTransaction(Transaction tx) throws VerificationException {
// Check a few basic syntax issues to ensure the received TX isn't nonsense.
tx.verify();
final Transaction fTx;
lock.lock();
try {
log.debug("{}: Received tx {}", getAddress(), tx.getHashAsString());
if (memoryPool != null) {
// We may get back a different transaction object.
tx = memoryPool.seen(tx, getAddress());
}
fTx = tx;
// Label the transaction as coming in from the P2P network (as opposed to being created by us, direct import,
// etc). This helps the wallet decide how to risk analyze it later.
fTx.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
if (maybeHandleRequestedData(fTx)) {
return;
}
if (currentFilteredBlock != null) {
if (!currentFilteredBlock.provideTransaction(tx)) {
// Got a tx that didn't fit into the filtered block, so we must have received everything.
endFilteredBlock(currentFilteredBlock);
currentFilteredBlock = null;
}
// Don't tell wallets or listeners about this tx as they'll learn about it when the filtered block is
// fully downloaded instead.
return;
}
// It's a broadcast transaction. Tell all wallets about this tx so they can check if it's relevant or not.
for (final Wallet wallet : wallets) {
try {
if (wallet.isPendingTransactionRelevant(fTx)) {
// This transaction seems interesting to us, so let's download its dependencies. This has several
// purposes: we can check that the sender isn't attacking us by engaging in protocol abuse games,
// like depending on a time-locked transaction that will never confirm, or building huge chains
// of unconfirmed transactions (again - so they don't confirm and the money can be taken
// back with a Finney attack). Knowing the dependencies also lets us store them in a serialized
// wallet so we always have enough data to re-announce to the network and get the payment into
// the chain, in case the sender goes away and the network starts to forget.
// TODO: Not all the above things are implemented.
Futures.addCallback(downloadDependencies(fTx), new FutureCallback>() {
public void onSuccess(List dependencies) {
try {
log.info("{}: Dependency download complete!", getAddress());
wallet.receivePending(fTx, dependencies);
} catch (VerificationException e) {
log.error("{}: Wallet failed to process pending transaction {}",
getAddress(), fTx.getHashAsString());
log.error("Error was: ", e);
// Not much more we can do at this point.
}
}
public void onFailure(Throwable throwable) {
log.error("Could not download dependencies of tx {}", fTx.getHashAsString());
log.error("Error was: ", throwable);
// Not much more we can do at this point.
}
});
}
} catch (VerificationException e) {
log.error("Wallet failed to verify tx", e);
// Carry on, listeners may still want to know.
}
}
} finally {
lock.unlock();
}
// Tell all listeners about this tx so they can decide whether to keep it or not. If no listener keeps a
// reference around then the memory pool will forget about it after a while too because it uses weak references.
for (final ListenerRegistration registration : eventListeners) {
registration.executor.execute(new Runnable() {
@Override
public void run() {
registration.listener.onTransaction(Peer.this, fTx);
}
});
}
}
/**
* Returns a future that wraps a list of all transactions that the given transaction depends on, recursively.
* Only transactions in peers memory pools are included; the recursion stops at transactions that are in the
* current best chain. So it doesn't make much sense to provide a tx that was already in the best chain and
* a precondition checks this.
*
* For example, if tx has 2 inputs that connect to transactions A and B, and transaction B is unconfirmed and
* has one input connecting to transaction C that is unconfirmed, and transaction C connects to transaction D
* that is in the chain, then this method will return either {B, C} or {C, B}. No ordering is guaranteed.
*
* This method is useful for apps that want to learn about how long an unconfirmed transaction might take
* to confirm, by checking for unexpectedly time locked transactions, unusually deep dependency trees or fee-paying
* transactions that depend on unconfirmed free transactions.
*
* Note that dependencies downloaded this way will not trigger the onTransaction method of event listeners.
*/
public ListenableFuture> downloadDependencies(Transaction tx) {
checkNotNull(memoryPool, "Must have a configured MemoryPool object to download dependencies.");
TransactionConfidence.ConfidenceType txConfidence = tx.getConfidence().getConfidenceType();
Preconditions.checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING);
log.info("{}: Downloading dependencies of {}", getAddress(), tx.getHashAsString());
final LinkedList results = new LinkedList();
// future will be invoked when the entire dependency tree has been walked and the results compiled.
final ListenableFuture future = downloadDependenciesInternal(tx, new Object(), results);
final SettableFuture> resultFuture = SettableFuture.create();
Futures.addCallback(future, new FutureCallback() {
public void onSuccess(Object ignored) {
resultFuture.set(results);
}
public void onFailure(Throwable throwable) {
resultFuture.setException(throwable);
}
});
return resultFuture;
}
// The marker object in the future returned is the same as the parameter. It is arbitrary and can be anything.
private ListenableFuture