Apply "Anonymous type can be replaced with lambda" refactoring.

This commit is contained in:
Andreas Schildbach 2020-09-07 19:13:40 +02:00
parent 3290c8c541
commit c08a4d97d3
10 changed files with 103 additions and 193 deletions

View file

@ -50,13 +50,10 @@ public class DoubleSpend {
Transaction tx2 = kit.wallet().createSend(LegacyAddress.fromBase58(params, "muYPFNCv7KQEG2ZLM7Z3y96kJnNyXJ53wm"), CENT.add(SATOSHI.multiply(10))); Transaction tx2 = kit.wallet().createSend(LegacyAddress.fromBase58(params, "muYPFNCv7KQEG2ZLM7Z3y96kJnNyXJ53wm"), CENT.add(SATOSHI.multiply(10)));
final Peer peer = kit.peerGroup().getConnectedPeers().get(0); final Peer peer = kit.peerGroup().getConnectedPeers().get(0);
peer.addPreMessageReceivedEventListener(Threading.SAME_THREAD, peer.addPreMessageReceivedEventListener(Threading.SAME_THREAD,
new PreMessageReceivedEventListener() { (peer1, m) -> {
@Override
public Message onPreMessageReceived(Peer peer, Message m) {
System.err.println("Got a message!" + m.getClass().getSimpleName() + ": " + m); System.err.println("Got a message!" + m.getClass().getSimpleName() + ": " + m);
return m; return m;
} }
}
); );
peer.sendMessage(tx1); peer.sendMessage(tx1);
peer.sendMessage(tx2); peer.sendMessage(tx2);

View file

@ -91,35 +91,32 @@ public class ForwardingService {
kit.awaitRunning(); kit.awaitRunning();
// We want to know when we receive money. // We want to know when we receive money.
kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { kit.wallet().addCoinsReceivedEventListener((w, tx, prevBalance, newBalance) -> {
@Override // Runs in the dedicated "user thread" (see bitcoinj docs for more info on this).
public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) { //
// Runs in the dedicated "user thread" (see bitcoinj docs for more info on this). // The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast).
// Coin value = tx.getValueSentToMe(w);
// The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast). System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
Coin value = tx.getValueSentToMe(w); System.out.println("Transaction will be forwarded after it confirms.");
System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx); // Wait until it's made it into the block chain (may run immediately if it's already there).
System.out.println("Transaction will be forwarded after it confirms."); //
// Wait until it's made it into the block chain (may run immediately if it's already there). // For this dummy app of course, we could just forward the unconfirmed transaction. If it were
// // to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to
// For this dummy app of course, we could just forward the unconfirmed transaction. If it were // be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common
// to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to // case of waiting for a block.
// be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
// case of waiting for a block. @Override
Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() { public void onSuccess(TransactionConfidence result) {
@Override System.out.println("Confirmation received.");
public void onSuccess(TransactionConfidence result) { forwardCoins(tx);
System.out.println("Confirmation received."); }
forwardCoins(tx);
}
@Override @Override
public void onFailure(Throwable t) { public void onFailure(Throwable t) {
// This kind of future can't fail, just rethrow in case something weird happens. // This kind of future can't fail, just rethrow in case something weird happens.
throw new RuntimeException(t); throw new RuntimeException(t);
} }
}, MoreExecutors.directExecutor()); }, MoreExecutors.directExecutor());
}
}); });
Address sendToAddress = LegacyAddress.fromKey(params, kit.wallet().currentReceiveKey()); Address sendToAddress = LegacyAddress.fromKey(params, kit.wallet().currentReceiveKey());
@ -141,12 +138,9 @@ public class ForwardingService {
// Register a callback that is invoked when the transaction has propagated across the network. // Register a callback that is invoked when the transaction has propagated across the network.
// This shows a second style of registering ListenableFuture callbacks, it works when you don't // This shows a second style of registering ListenableFuture callbacks, it works when you don't
// need access to the object the future returns. // need access to the object the future returns.
sendResult.broadcastComplete.addListener(new Runnable() { sendResult.broadcastComplete.addListener(() -> {
@Override // The wallet has changed now, it'll get auto saved shortly or when the app shuts down.
public void run() { System.out.println("Sent coins onwards! Transaction hash is " + sendResult.tx.getTxId());
// The wallet has changed now, it'll get auto saved shortly or when the app shuts down.
System.out.println("Sent coins onwards! Transaction hash is " + sendResult.tx.getTxId());
}
}, MoreExecutors.directExecutor()); }, MoreExecutors.directExecutor());
} catch (KeyCrypterException | InsufficientMoneyException e) { } catch (KeyCrypterException | InsufficientMoneyException e) {
// We don't use encrypted wallets in this example - can never happen. // We don't use encrypted wallets in this example - can never happen.

View file

@ -65,42 +65,21 @@ public class Kit {
kit.startAsync(); kit.startAsync();
kit.awaitRunning(); kit.awaitRunning();
kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { kit.wallet().addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
@Override System.out.println("-----> coins resceived: " + tx.getTxId());
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { System.out.println("received: " + tx.getValue(wallet));
System.out.println("-----> coins resceived: " + tx.getTxId());
System.out.println("received: " + tx.getValue(wallet));
}
}); });
kit.wallet().addCoinsSentEventListener(new WalletCoinsSentEventListener() { kit.wallet().addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> System.out.println("coins sent"));
@Override
public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
System.out.println("coins sent");
}
});
kit.wallet().addKeyChainEventListener(new KeyChainEventListener() { kit.wallet().addKeyChainEventListener(keys -> System.out.println("new key added"));
@Override
public void onKeysAdded(List<ECKey> keys) {
System.out.println("new key added");
}
});
kit.wallet().addScriptsChangeEventListener(new ScriptsChangeEventListener() { kit.wallet().addScriptsChangeEventListener((wallet, scripts, isAddingScripts) -> System.out.println("new script added"));
@Override
public void onScriptsChanged(Wallet wallet, List<Script> scripts, boolean isAddingScripts) {
System.out.println("new script added");
}
});
kit.wallet().addTransactionConfidenceEventListener(new TransactionConfidenceEventListener() { kit.wallet().addTransactionConfidenceEventListener((wallet, tx) -> {
@Override System.out.println("-----> confidence changed: " + tx.getTxId());
public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) { TransactionConfidence confidence = tx.getConfidence();
System.out.println("-----> confidence changed: " + tx.getTxId()); System.out.println("new block depth: " + confidence.getDepthInBlocks());
TransactionConfidence confidence = tx.getConfidence();
System.out.println("new block depth: " + confidence.getDepthInBlocks());
}
}); });
// Ready to run. The kit syncs the blockchain and our wallet event listener gets notified when something happens. // Ready to run. The kit syncs the blockchain and our wallet event listener gets notified when something happens.

View file

@ -68,20 +68,14 @@ public class PeerMonitor {
peerGroup.setUserAgent("PeerMonitor", "1.0"); peerGroup.setUserAgent("PeerMonitor", "1.0");
peerGroup.setMaxConnections(4); peerGroup.setMaxConnections(4);
peerGroup.addPeerDiscovery(new DnsDiscovery(params)); peerGroup.addPeerDiscovery(new DnsDiscovery(params));
peerGroup.addConnectedEventListener(new PeerConnectedEventListener() { peerGroup.addConnectedEventListener((peer, peerCount) -> {
@Override refreshUI();
public void onPeerConnected(final Peer peer, int peerCount) { lookupReverseDNS(peer);
refreshUI();
lookupReverseDNS(peer);
}
}); });
peerGroup.addDisconnectedEventListener(new PeerDisconnectedEventListener() { peerGroup.addDisconnectedEventListener((peer, peerCount) -> {
@Override refreshUI();
public void onPeerDisconnected(final Peer peer, int peerCount) { synchronized (reverseDnsLookups) {
refreshUI(); reverseDnsLookups.remove(peer);
synchronized (reverseDnsLookups) {
reverseDnsLookups.remove(peer);
}
} }
}); });
} }
@ -102,12 +96,7 @@ public class PeerMonitor {
private void refreshUI() { private void refreshUI() {
// Tell the Swing UI thread to redraw the peers table. // Tell the Swing UI thread to redraw the peers table.
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(() -> peerTableModel.updateFromPeerGroup());
@Override
public void run() {
peerTableModel.updateFromPeerGroup();
}
});
} }
private void setupGUI() { private void setupGUI() {
@ -126,12 +115,7 @@ public class PeerMonitor {
JPanel panel = new JPanel(); JPanel panel = new JPanel();
JLabel instructions = new JLabel("Number of peers to connect to: "); JLabel instructions = new JLabel("Number of peers to connect to: ");
final SpinnerNumberModel spinnerModel = new SpinnerNumberModel(4, 0, 100, 1); final SpinnerNumberModel spinnerModel = new SpinnerNumberModel(4, 0, 100, 1);
spinnerModel.addChangeListener(new ChangeListener() { spinnerModel.addChangeListener(changeEvent -> peerGroup.setMaxConnections(spinnerModel.getNumber().intValue()));
@Override
public void stateChanged(ChangeEvent changeEvent) {
peerGroup.setMaxConnections(spinnerModel.getNumber().intValue());
}
});
JSpinner numPeersSpinner = new JSpinner(spinnerModel); JSpinner numPeersSpinner = new JSpinner(spinnerModel);
panel.add(instructions); panel.add(instructions);
panel.add(numPeersSpinner); panel.add(numPeersSpinner);
@ -153,12 +137,7 @@ public class PeerMonitor {
window.setVisible(true); window.setVisible(true);
// Refresh the UI every half second to get the latest ping times. The event handler runs in the UI thread. // Refresh the UI every half second to get the latest ping times. The event handler runs in the UI thread.
new Timer(1000, new ActionListener() { new Timer(1000, actionEvent -> peerTableModel.updateFromPeerGroup()).start();
@Override
public void actionPerformed(ActionEvent actionEvent) {
peerTableModel.updateFromPeerGroup();
}
}).start();
} }
private class PeerTableModel extends AbstractTableModel { private class PeerTableModel extends AbstractTableModel {

View file

@ -85,36 +85,30 @@ public class PrintPeers {
new PeerAddress(params, address), null); new PeerAddress(params, address), null);
final SettableFuture<Void> future = SettableFuture.create(); final SettableFuture<Void> future = SettableFuture.create();
// Once the connection has completed version handshaking ... // Once the connection has completed version handshaking ...
peer.addConnectedEventListener(new PeerConnectedEventListener() { peer.addConnectedEventListener((p, peerCount) -> {
@Override // Check the chain height it claims to have.
public void onPeerConnected(Peer p, int peerCount) { VersionMessage ver = peer.getPeerVersionMessage();
// Check the chain height it claims to have. long nodeHeight = ver.bestHeight;
VersionMessage ver = peer.getPeerVersionMessage(); synchronized (lock) {
long nodeHeight = ver.bestHeight; long diff = bestHeight[0] - nodeHeight;
synchronized (lock) { if (diff > 0) {
long diff = bestHeight[0] - nodeHeight; System.out.println("Node is behind by " + diff + " blocks: " + addr);
if (diff > 0) { } else if (diff == 0) {
System.out.println("Node is behind by " + diff + " blocks: " + addr); System.out.println("Node " + addr + " has " + nodeHeight + " blocks");
} else if (diff == 0) { bestHeight[0] = nodeHeight;
System.out.println("Node " + addr + " has " + nodeHeight + " blocks"); } else if (diff < 0) {
bestHeight[0] = nodeHeight; System.out.println("Node is ahead by " + Math.abs(diff) + " blocks: " + addr);
} else if (diff < 0) { bestHeight[0] = nodeHeight;
System.out.println("Node is ahead by " + Math.abs(diff) + " blocks: " + addr);
bestHeight[0] = nodeHeight;
}
} }
// Now finish the future and close the connection
future.set(null);
peer.close();
} }
// Now finish the future and close the connection
future.set(null);
peer.close();
}); });
peer.addDisconnectedEventListener(new PeerDisconnectedEventListener() { peer.addDisconnectedEventListener((p, peerCount) -> {
@Override if (!future.isDone())
public void onPeerDisconnected(Peer p, int peerCount) { System.out.println("Failed to talk to " + addr);
if (!future.isDone()) future.set(null);
System.out.println("Failed to talk to " + addr);
future.set(null);
}
}); });
clientManager.openConnection(address, peer); clientManager.openConnection(address, peer);
futures.add(future); futures.add(future);

View file

@ -140,15 +140,12 @@ public class BuildCheckpoints {
final long timeAgo = now - (86400 * options.valueOf(daysFlag)); final long timeAgo = now - (86400 * options.valueOf(daysFlag));
System.out.println("Checkpointing up to " + Utils.dateTimeFormat(timeAgo * 1000)); System.out.println("Checkpointing up to " + Utils.dateTimeFormat(timeAgo * 1000));
chain.addNewBestBlockListener(Threading.SAME_THREAD, new NewBestBlockListener() { chain.addNewBestBlockListener(Threading.SAME_THREAD, block -> {
@Override int height = block.getHeight();
public void notifyNewBestBlock(StoredBlock block) throws VerificationException { if (height % params.getInterval() == 0 && block.getHeader().getTimeSeconds() <= timeAgo) {
int height = block.getHeight(); System.out.println(String.format("Checkpointing block %s at height %d, time %s",
if (height % params.getInterval() == 0 && block.getHeader().getTimeSeconds() <= timeAgo) { block.getHeader().getHash(), block.getHeight(), Utils.dateTimeFormat(block.getHeader().getTime())));
System.out.println(String.format("Checkpointing block %s at height %d, time %s", checkpoints.put(height, block);
block.getHeader().getHash(), block.getHeight(), Utils.dateTimeFormat(block.getHeader().getTime())));
checkpoints.put(height, block);
}
} }
}); });

View file

@ -87,18 +87,10 @@ public class TestFeeLevel {
System.out.println("Size in bytes is " + request.tx.unsafeBitcoinSerialize().length); System.out.println("Size in bytes is " + request.tx.unsafeBitcoinSerialize().length);
System.out.println("TX is " + request.tx); System.out.println("TX is " + request.tx);
System.out.println("Waiting for " + kit.peerGroup().getMaxConnections() + " connected peers"); System.out.println("Waiting for " + kit.peerGroup().getMaxConnections() + " connected peers");
kit.peerGroup().addDisconnectedEventListener(new PeerDisconnectedEventListener() { kit.peerGroup().addDisconnectedEventListener((peer, peerCount) -> System.out.println(peerCount +
@Override " peers connected"));
public void onPeerDisconnected(Peer peer, int peerCount) { kit.peerGroup().addConnectedEventListener((peer, peerCount) -> System.out.println(peerCount +
System.out.println(peerCount + " peers connected"); " peers connected"));
}
});
kit.peerGroup().addConnectedEventListener(new PeerConnectedEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
System.out.println(peerCount + " peers connected");
}
});
kit.peerGroup().broadcastTransaction(request.tx).future().get(); kit.peerGroup().broadcastTransaction(request.tx).future().get();
System.out.println("Send complete, waiting for confirmation"); System.out.println("Send complete, waiting for confirmation");
request.tx.getConfidence().getDepthFuture(1).get(); request.tx.getConfidence().getDepthFuture(1).get();

View file

@ -814,34 +814,25 @@ public class WalletTool {
break; break;
case WALLET_TX: case WALLET_TX:
wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
@Override // Runs in a peer thread.
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { System.out.println(tx.getTxId());
// Runs in a peer thread. latch.countDown(); // Wake up main thread.
System.out.println(tx.getTxId());
latch.countDown(); // Wake up main thread.
}
}); });
wallet.addCoinsSentEventListener(new WalletCoinsSentEventListener() { wallet.addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> {
@Override // Runs in a peer thread.
public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { System.out.println(tx.getTxId());
// Runs in a peer thread. latch.countDown(); // Wake up main thread.
System.out.println(tx.getTxId());
latch.countDown(); // Wake up main thread.
}
}); });
break; break;
case BLOCK: case BLOCK:
peerGroup.addBlocksDownloadedEventListener(new BlocksDownloadedEventListener() { peerGroup.addBlocksDownloadedEventListener((peer, block, filteredBlock, blocksLeft) -> {
@Override // Check if we already ran. This can happen if a block being received triggers download of more
public void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) { // blocks, or if we receive another block whilst the peer group is shutting down.
// Check if we already ran. This can happen if a block being received triggers download of more if (latch.getCount() == 0) return;
// blocks, or if we receive another block whilst the peer group is shutting down. System.out.println(block.getHashAsString());
if (latch.getCount() == 0) return; latch.countDown();
System.out.println(block.getHashAsString());
latch.countDown();
}
}); });
break; break;

View file

@ -49,16 +49,13 @@ public class WatchMempool {
PeerGroup peerGroup = new PeerGroup(PARAMS); PeerGroup peerGroup = new PeerGroup(PARAMS);
peerGroup.setMaxConnections(32); peerGroup.setMaxConnections(32);
peerGroup.addPeerDiscovery(new DnsDiscovery(PARAMS)); peerGroup.addPeerDiscovery(new DnsDiscovery(PARAMS));
peerGroup.addOnTransactionBroadcastListener(new OnTransactionBroadcastListener() { peerGroup.addOnTransactionBroadcastListener((peer, tx) -> {
@Override Result result = DefaultRiskAnalysis.FACTORY.create(null, tx, NO_DEPS).analyze();
public void onTransaction(Peer peer, Transaction tx) { incrementCounter(TOTAL_KEY);
Result result = DefaultRiskAnalysis.FACTORY.create(null, tx, NO_DEPS).analyze(); log.info("tx {} result {}", tx.getTxId(), result);
incrementCounter(TOTAL_KEY); incrementCounter(result.name());
log.info("tx {} result {}", tx.getTxId(), result); if (result == Result.NON_STANDARD)
incrementCounter(result.name()); incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx));
if (result == Result.NON_STANDARD)
incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx));
}
}); });
peerGroup.start(); peerGroup.start();

View file

@ -47,18 +47,8 @@ public class BitcoinUIModel {
} }
public final void setWallet(Wallet wallet) { public final void setWallet(Wallet wallet) {
wallet.addChangeEventListener(Platform::runLater, new WalletChangeEventListener() { wallet.addChangeEventListener(Platform::runLater, w -> updateBalance(wallet));
@Override wallet.addCurrentKeyChangeEventListener(Platform::runLater, () -> updateAddress(wallet));
public void onWalletChanged(Wallet w) {
updateBalance(wallet);
}
});
wallet.addCurrentKeyChangeEventListener(Platform::runLater, new CurrentKeyChangeEventListener() {
@Override
public void onCurrentKeyChanged() {
updateAddress(wallet);
}
});
updateBalance(wallet); updateBalance(wallet);
updateAddress(wallet); updateAddress(wallet);
} }