Skip to content

Commit

Permalink
Allow some monkey-patching of Peer methods/Peer creation.
Browse files Browse the repository at this point in the history
Fix a bug in the min version required feature.
  • Loading branch information
mikehearn committed Oct 8, 2015
1 parent 0079c27 commit 761834b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
29 changes: 15 additions & 14 deletions core/src/main/java/org/bitcoinj/core/Peer.java
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ public void run() {
}
}

private void processUTXOMessage(UTXOsMessage m) {
protected void processUTXOMessage(UTXOsMessage m) {
SettableFuture<UTXOsMessage> future = null;
lock.lock();
try {
Expand Down Expand Up @@ -505,7 +505,7 @@ private void processVersionMessage(VersionMessage m) throws ProtocolException {
versionHandshakeFuture.set(this);
}

private void startFilteredBlock(FilteredBlock m) {
protected 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
Expand All @@ -520,7 +520,7 @@ private void startFilteredBlock(FilteredBlock m) {
}
}

private void processNotFoundMessage(NotFoundMessage m) {
protected 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
Expand All @@ -539,7 +539,7 @@ private void processNotFoundMessage(NotFoundMessage m) {
}
}

private void processAlert(AlertMessage m) {
protected void processAlert(AlertMessage m) {
try {
if (m.isSignatureValid()) {
log.info("Received alert from peer {}: {}", this, m.getStatusBar());
Expand All @@ -554,7 +554,7 @@ private void processAlert(AlertMessage m) {
}
}

private void processHeaders(HeadersMessage m) throws ProtocolException {
protected 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
Expand Down Expand Up @@ -634,7 +634,7 @@ private void processHeaders(HeadersMessage m) throws ProtocolException {
}
}

private void processGetData(GetDataMessage getdata) {
protected void processGetData(GetDataMessage getdata) {
log.info("{}: Received getdata message: {}", getAddress(), getdata.toString());
ArrayList<Message> items = new ArrayList<Message>();
for (ListenerRegistration<PeerDataEventListener> registration : dataEventListeners) {
Expand All @@ -652,7 +652,7 @@ private void processGetData(GetDataMessage getdata) {
}
}

private void processTransaction(final Transaction tx) throws VerificationException {
protected void processTransaction(final Transaction tx) throws VerificationException {
// Check a few basic syntax issues to ensure the received TX isn't nonsense.
tx.verify();
lock.lock();
Expand Down Expand Up @@ -784,7 +784,7 @@ public void onFailure(Throwable throwable) {
}

// The marker object in the future returned is the same as the parameter. It is arbitrary and can be anything.
private ListenableFuture<Object> downloadDependenciesInternal(final Transaction tx,
protected ListenableFuture<Object> downloadDependenciesInternal(final Transaction tx,
final Object marker,
final List<Transaction> results) {
final SettableFuture<Object> resultFuture = SettableFuture.create();
Expand Down Expand Up @@ -865,7 +865,7 @@ public void onFailure(Throwable throwable) {
return resultFuture;
}

private void processBlock(Block m) {
protected void processBlock(Block m) {
if (log.isDebugEnabled()) {
log.debug("{}: Received broadcast block {}", getAddress(), m.getHashAsString());
}
Expand Down Expand Up @@ -927,7 +927,7 @@ private void processBlock(Block m) {
}

// TODO: Fix this duplication.
private void endFilteredBlock(FilteredBlock m) {
protected void endFilteredBlock(FilteredBlock m) {
if (log.isDebugEnabled())
log.debug("{}: Received broadcast filtered block {}", getAddress(), m.getHash().toString());
if (!vDownloadData) {
Expand Down Expand Up @@ -1062,7 +1062,7 @@ public void run() {
}
}

private void processInv(InventoryMessage inv) {
protected void processInv(InventoryMessage inv) {
List<InventoryItem> items = inv.getItems();

// Separate out the blocks and transactions, we'll handle them differently
Expand Down Expand Up @@ -1502,7 +1502,7 @@ public long getPingTime() {
}
}

private void processPong(Pong m) {
protected void processPong(Pong m) {
// Iterates over a snapshot of the list, so we can run unlocked here.
for (PendingPing ping : pendingPings) {
if (m.getNonce() == ping.nonce) {
Expand Down Expand Up @@ -1574,8 +1574,9 @@ public long getBestHeight() {
*/
public boolean setMinProtocolVersion(int minProtocolVersion) {
this.vMinProtocolVersion = minProtocolVersion;
if (getVersionMessage().clientVersion < minProtocolVersion) {
log.warn("{}: Disconnecting due to new min protocol version {}", this, minProtocolVersion);
VersionMessage ver = getPeerVersionMessage();
if (ver != null && ver.clientVersion < minProtocolVersion) {
log.warn("{}: Disconnecting due to new min protocol version {}, got: {}", this, minProtocolVersion, ver.clientVersion);
close();
return true;
}
Expand Down
14 changes: 10 additions & 4 deletions core/src/main/java/org/bitcoinj/core/PeerGroup.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ public class PeerGroup implements TransactionBroadcaster {

protected final ReentrantLock lock = Threading.lock("peergroup");

private final NetworkParameters params;
@Nullable private final AbstractBlockChain chain;
protected final NetworkParameters params;
@Nullable protected final AbstractBlockChain chain;

// This executor is used to queue up jobs: it's used when we don't want to use locks for mutual exclusion,
// typically because the job might call in to user provided code that needs/wants the freedom to use the API
Expand Down Expand Up @@ -123,7 +123,7 @@ public class PeerGroup implements TransactionBroadcaster {
// The version message to use for new connections.
@GuardedBy("lock") private VersionMessage versionMessage;
// Switch for enabling download of pending transaction dependencies.
@GuardedBy("lock") private boolean downloadTxDependencies;
@GuardedBy("lock") protected boolean downloadTxDependencies;
// How many connections we want to have open at the current time. If we lose connections, we'll try opening more
// until we reach this count.
@GuardedBy("lock") private int maxConnections;
Expand Down Expand Up @@ -1301,7 +1301,7 @@ protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, i
ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight();
ver.time = Utils.currentTimeSeconds();

Peer peer = new Peer(params, ver, address, chain, downloadTxDependencies);
Peer peer = createPeer(address, ver);
peer.addConnectionEventListener(Threading.SAME_THREAD, startupListener);
peer.setMinProtocolVersion(vMinRequiredProtocolVersion);
pendingPeers.add(peer);
Expand Down Expand Up @@ -1329,6 +1329,12 @@ protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, i
return peer;
}

/** You can override this to customise the creation of {@link Peer} objects. */
@GuardedBy("lock")
protected Peer createPeer(PeerAddress address, VersionMessage ver) {
return new Peer(params, ver, address, chain, downloadTxDependencies);
}

/**
* Sets the timeout between when a connection attempt to a peer begins and when the version message exchange
* completes. This does not apply to currently pending peers.
Expand Down

0 comments on commit 761834b

Please sign in to comment.