mirror of
https://github.com/bitcoinj/bitcoinj.git
synced 2025-03-10 09:20:04 +01:00
Apply "Anonymous type can be replaced with lambda" refactoring.
This commit is contained in:
parent
3290c8c541
commit
c08a4d97d3
10 changed files with 103 additions and 193 deletions
|
@ -50,13 +50,10 @@ public class DoubleSpend {
|
|||
Transaction tx2 = kit.wallet().createSend(LegacyAddress.fromBase58(params, "muYPFNCv7KQEG2ZLM7Z3y96kJnNyXJ53wm"), CENT.add(SATOSHI.multiply(10)));
|
||||
final Peer peer = kit.peerGroup().getConnectedPeers().get(0);
|
||||
peer.addPreMessageReceivedEventListener(Threading.SAME_THREAD,
|
||||
new PreMessageReceivedEventListener() {
|
||||
@Override
|
||||
public Message onPreMessageReceived(Peer peer, Message m) {
|
||||
(peer1, m) -> {
|
||||
System.err.println("Got a message!" + m.getClass().getSimpleName() + ": " + m);
|
||||
return m;
|
||||
}
|
||||
}
|
||||
);
|
||||
peer.sendMessage(tx1);
|
||||
peer.sendMessage(tx2);
|
||||
|
|
|
@ -91,35 +91,32 @@ public class ForwardingService {
|
|||
kit.awaitRunning();
|
||||
|
||||
// We want to know when we receive money.
|
||||
kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
|
||||
@Override
|
||||
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);
|
||||
System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
|
||||
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
|
||||
// be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common
|
||||
// case of waiting for a block.
|
||||
Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
|
||||
@Override
|
||||
public void onSuccess(TransactionConfidence result) {
|
||||
System.out.println("Confirmation received.");
|
||||
forwardCoins(tx);
|
||||
}
|
||||
kit.wallet().addCoinsReceivedEventListener((w, tx, prevBalance, 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);
|
||||
System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
|
||||
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
|
||||
// be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common
|
||||
// case of waiting for a block.
|
||||
Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
|
||||
@Override
|
||||
public void onSuccess(TransactionConfidence result) {
|
||||
System.out.println("Confirmation received.");
|
||||
forwardCoins(tx);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Throwable t) {
|
||||
// This kind of future can't fail, just rethrow in case something weird happens.
|
||||
throw new RuntimeException(t);
|
||||
}
|
||||
}, MoreExecutors.directExecutor());
|
||||
}
|
||||
@Override
|
||||
public void onFailure(Throwable t) {
|
||||
// This kind of future can't fail, just rethrow in case something weird happens.
|
||||
throw new RuntimeException(t);
|
||||
}
|
||||
}, MoreExecutors.directExecutor());
|
||||
});
|
||||
|
||||
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.
|
||||
// This shows a second style of registering ListenableFuture callbacks, it works when you don't
|
||||
// need access to the object the future returns.
|
||||
sendResult.broadcastComplete.addListener(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// 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());
|
||||
}
|
||||
sendResult.broadcastComplete.addListener(() -> {
|
||||
// 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());
|
||||
} catch (KeyCrypterException | InsufficientMoneyException e) {
|
||||
// We don't use encrypted wallets in this example - can never happen.
|
||||
|
|
|
@ -65,42 +65,21 @@ public class Kit {
|
|||
kit.startAsync();
|
||||
kit.awaitRunning();
|
||||
|
||||
kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
|
||||
@Override
|
||||
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
|
||||
System.out.println("-----> coins resceived: " + tx.getTxId());
|
||||
System.out.println("received: " + tx.getValue(wallet));
|
||||
}
|
||||
kit.wallet().addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
|
||||
System.out.println("-----> coins resceived: " + tx.getTxId());
|
||||
System.out.println("received: " + tx.getValue(wallet));
|
||||
});
|
||||
|
||||
kit.wallet().addCoinsSentEventListener(new WalletCoinsSentEventListener() {
|
||||
@Override
|
||||
public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
|
||||
System.out.println("coins sent");
|
||||
}
|
||||
});
|
||||
kit.wallet().addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> System.out.println("coins sent"));
|
||||
|
||||
kit.wallet().addKeyChainEventListener(new KeyChainEventListener() {
|
||||
@Override
|
||||
public void onKeysAdded(List<ECKey> keys) {
|
||||
System.out.println("new key added");
|
||||
}
|
||||
});
|
||||
kit.wallet().addKeyChainEventListener(keys -> System.out.println("new key added"));
|
||||
|
||||
kit.wallet().addScriptsChangeEventListener(new ScriptsChangeEventListener() {
|
||||
@Override
|
||||
public void onScriptsChanged(Wallet wallet, List<Script> scripts, boolean isAddingScripts) {
|
||||
System.out.println("new script added");
|
||||
}
|
||||
});
|
||||
kit.wallet().addScriptsChangeEventListener((wallet, scripts, isAddingScripts) -> System.out.println("new script added"));
|
||||
|
||||
kit.wallet().addTransactionConfidenceEventListener(new TransactionConfidenceEventListener() {
|
||||
@Override
|
||||
public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) {
|
||||
System.out.println("-----> confidence changed: " + tx.getTxId());
|
||||
TransactionConfidence confidence = tx.getConfidence();
|
||||
System.out.println("new block depth: " + confidence.getDepthInBlocks());
|
||||
}
|
||||
kit.wallet().addTransactionConfidenceEventListener((wallet, tx) -> {
|
||||
System.out.println("-----> confidence changed: " + tx.getTxId());
|
||||
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.
|
||||
|
|
|
@ -68,20 +68,14 @@ public class PeerMonitor {
|
|||
peerGroup.setUserAgent("PeerMonitor", "1.0");
|
||||
peerGroup.setMaxConnections(4);
|
||||
peerGroup.addPeerDiscovery(new DnsDiscovery(params));
|
||||
peerGroup.addConnectedEventListener(new PeerConnectedEventListener() {
|
||||
@Override
|
||||
public void onPeerConnected(final Peer peer, int peerCount) {
|
||||
refreshUI();
|
||||
lookupReverseDNS(peer);
|
||||
}
|
||||
peerGroup.addConnectedEventListener((peer, peerCount) -> {
|
||||
refreshUI();
|
||||
lookupReverseDNS(peer);
|
||||
});
|
||||
peerGroup.addDisconnectedEventListener(new PeerDisconnectedEventListener() {
|
||||
@Override
|
||||
public void onPeerDisconnected(final Peer peer, int peerCount) {
|
||||
refreshUI();
|
||||
synchronized (reverseDnsLookups) {
|
||||
reverseDnsLookups.remove(peer);
|
||||
}
|
||||
peerGroup.addDisconnectedEventListener((peer, peerCount) -> {
|
||||
refreshUI();
|
||||
synchronized (reverseDnsLookups) {
|
||||
reverseDnsLookups.remove(peer);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -102,12 +96,7 @@ public class PeerMonitor {
|
|||
|
||||
private void refreshUI() {
|
||||
// Tell the Swing UI thread to redraw the peers table.
|
||||
SwingUtilities.invokeLater(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
peerTableModel.updateFromPeerGroup();
|
||||
}
|
||||
});
|
||||
SwingUtilities.invokeLater(() -> peerTableModel.updateFromPeerGroup());
|
||||
}
|
||||
|
||||
private void setupGUI() {
|
||||
|
@ -126,12 +115,7 @@ public class PeerMonitor {
|
|||
JPanel panel = new JPanel();
|
||||
JLabel instructions = new JLabel("Number of peers to connect to: ");
|
||||
final SpinnerNumberModel spinnerModel = new SpinnerNumberModel(4, 0, 100, 1);
|
||||
spinnerModel.addChangeListener(new ChangeListener() {
|
||||
@Override
|
||||
public void stateChanged(ChangeEvent changeEvent) {
|
||||
peerGroup.setMaxConnections(spinnerModel.getNumber().intValue());
|
||||
}
|
||||
});
|
||||
spinnerModel.addChangeListener(changeEvent -> peerGroup.setMaxConnections(spinnerModel.getNumber().intValue()));
|
||||
JSpinner numPeersSpinner = new JSpinner(spinnerModel);
|
||||
panel.add(instructions);
|
||||
panel.add(numPeersSpinner);
|
||||
|
@ -153,12 +137,7 @@ public class PeerMonitor {
|
|||
window.setVisible(true);
|
||||
|
||||
// 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() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent actionEvent) {
|
||||
peerTableModel.updateFromPeerGroup();
|
||||
}
|
||||
}).start();
|
||||
new Timer(1000, actionEvent -> peerTableModel.updateFromPeerGroup()).start();
|
||||
}
|
||||
|
||||
private class PeerTableModel extends AbstractTableModel {
|
||||
|
|
|
@ -85,36 +85,30 @@ public class PrintPeers {
|
|||
new PeerAddress(params, address), null);
|
||||
final SettableFuture<Void> future = SettableFuture.create();
|
||||
// Once the connection has completed version handshaking ...
|
||||
peer.addConnectedEventListener(new PeerConnectedEventListener() {
|
||||
@Override
|
||||
public void onPeerConnected(Peer p, int peerCount) {
|
||||
// Check the chain height it claims to have.
|
||||
VersionMessage ver = peer.getPeerVersionMessage();
|
||||
long nodeHeight = ver.bestHeight;
|
||||
synchronized (lock) {
|
||||
long diff = bestHeight[0] - nodeHeight;
|
||||
if (diff > 0) {
|
||||
System.out.println("Node is behind by " + diff + " blocks: " + addr);
|
||||
} else if (diff == 0) {
|
||||
System.out.println("Node " + addr + " has " + nodeHeight + " blocks");
|
||||
bestHeight[0] = nodeHeight;
|
||||
} else if (diff < 0) {
|
||||
System.out.println("Node is ahead by " + Math.abs(diff) + " blocks: " + addr);
|
||||
bestHeight[0] = nodeHeight;
|
||||
}
|
||||
peer.addConnectedEventListener((p, peerCount) -> {
|
||||
// Check the chain height it claims to have.
|
||||
VersionMessage ver = peer.getPeerVersionMessage();
|
||||
long nodeHeight = ver.bestHeight;
|
||||
synchronized (lock) {
|
||||
long diff = bestHeight[0] - nodeHeight;
|
||||
if (diff > 0) {
|
||||
System.out.println("Node is behind by " + diff + " blocks: " + addr);
|
||||
} else if (diff == 0) {
|
||||
System.out.println("Node " + addr + " has " + nodeHeight + " blocks");
|
||||
bestHeight[0] = nodeHeight;
|
||||
} else if (diff < 0) {
|
||||
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() {
|
||||
@Override
|
||||
public void onPeerDisconnected(Peer p, int peerCount) {
|
||||
if (!future.isDone())
|
||||
System.out.println("Failed to talk to " + addr);
|
||||
future.set(null);
|
||||
}
|
||||
peer.addDisconnectedEventListener((p, peerCount) -> {
|
||||
if (!future.isDone())
|
||||
System.out.println("Failed to talk to " + addr);
|
||||
future.set(null);
|
||||
});
|
||||
clientManager.openConnection(address, peer);
|
||||
futures.add(future);
|
||||
|
|
|
@ -140,15 +140,12 @@ public class BuildCheckpoints {
|
|||
final long timeAgo = now - (86400 * options.valueOf(daysFlag));
|
||||
System.out.println("Checkpointing up to " + Utils.dateTimeFormat(timeAgo * 1000));
|
||||
|
||||
chain.addNewBestBlockListener(Threading.SAME_THREAD, new NewBestBlockListener() {
|
||||
@Override
|
||||
public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
|
||||
int height = block.getHeight();
|
||||
if (height % params.getInterval() == 0 && block.getHeader().getTimeSeconds() <= timeAgo) {
|
||||
System.out.println(String.format("Checkpointing block %s at height %d, time %s",
|
||||
block.getHeader().getHash(), block.getHeight(), Utils.dateTimeFormat(block.getHeader().getTime())));
|
||||
checkpoints.put(height, block);
|
||||
}
|
||||
chain.addNewBestBlockListener(Threading.SAME_THREAD, block -> {
|
||||
int height = block.getHeight();
|
||||
if (height % params.getInterval() == 0 && block.getHeader().getTimeSeconds() <= timeAgo) {
|
||||
System.out.println(String.format("Checkpointing block %s at height %d, time %s",
|
||||
block.getHeader().getHash(), block.getHeight(), Utils.dateTimeFormat(block.getHeader().getTime())));
|
||||
checkpoints.put(height, block);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
@ -87,18 +87,10 @@ public class TestFeeLevel {
|
|||
System.out.println("Size in bytes is " + request.tx.unsafeBitcoinSerialize().length);
|
||||
System.out.println("TX is " + request.tx);
|
||||
System.out.println("Waiting for " + kit.peerGroup().getMaxConnections() + " connected peers");
|
||||
kit.peerGroup().addDisconnectedEventListener(new PeerDisconnectedEventListener() {
|
||||
@Override
|
||||
public void onPeerDisconnected(Peer peer, int peerCount) {
|
||||
System.out.println(peerCount + " peers connected");
|
||||
}
|
||||
});
|
||||
kit.peerGroup().addConnectedEventListener(new PeerConnectedEventListener() {
|
||||
@Override
|
||||
public void onPeerConnected(Peer peer, int peerCount) {
|
||||
System.out.println(peerCount + " peers connected");
|
||||
}
|
||||
});
|
||||
kit.peerGroup().addDisconnectedEventListener((peer, peerCount) -> System.out.println(peerCount +
|
||||
" peers connected"));
|
||||
kit.peerGroup().addConnectedEventListener((peer, peerCount) -> System.out.println(peerCount +
|
||||
" peers connected"));
|
||||
kit.peerGroup().broadcastTransaction(request.tx).future().get();
|
||||
System.out.println("Send complete, waiting for confirmation");
|
||||
request.tx.getConfidence().getDepthFuture(1).get();
|
||||
|
|
|
@ -814,34 +814,25 @@ public class WalletTool {
|
|||
break;
|
||||
|
||||
case WALLET_TX:
|
||||
wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
|
||||
@Override
|
||||
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
|
||||
// Runs in a peer thread.
|
||||
System.out.println(tx.getTxId());
|
||||
latch.countDown(); // Wake up main thread.
|
||||
}
|
||||
wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
|
||||
// Runs in a peer thread.
|
||||
System.out.println(tx.getTxId());
|
||||
latch.countDown(); // Wake up main thread.
|
||||
});
|
||||
wallet.addCoinsSentEventListener(new WalletCoinsSentEventListener() {
|
||||
@Override
|
||||
public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
|
||||
// Runs in a peer thread.
|
||||
System.out.println(tx.getTxId());
|
||||
latch.countDown(); // Wake up main thread.
|
||||
}
|
||||
wallet.addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> {
|
||||
// Runs in a peer thread.
|
||||
System.out.println(tx.getTxId());
|
||||
latch.countDown(); // Wake up main thread.
|
||||
});
|
||||
break;
|
||||
|
||||
case BLOCK:
|
||||
peerGroup.addBlocksDownloadedEventListener(new BlocksDownloadedEventListener() {
|
||||
@Override
|
||||
public void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
|
||||
// Check if we already ran. This can happen if a block being received triggers download of more
|
||||
// blocks, or if we receive another block whilst the peer group is shutting down.
|
||||
if (latch.getCount() == 0) return;
|
||||
System.out.println(block.getHashAsString());
|
||||
latch.countDown();
|
||||
}
|
||||
peerGroup.addBlocksDownloadedEventListener((peer, block, filteredBlock, blocksLeft) -> {
|
||||
// Check if we already ran. This can happen if a block being received triggers download of more
|
||||
// blocks, or if we receive another block whilst the peer group is shutting down.
|
||||
if (latch.getCount() == 0) return;
|
||||
System.out.println(block.getHashAsString());
|
||||
latch.countDown();
|
||||
});
|
||||
break;
|
||||
|
||||
|
|
|
@ -49,16 +49,13 @@ public class WatchMempool {
|
|||
PeerGroup peerGroup = new PeerGroup(PARAMS);
|
||||
peerGroup.setMaxConnections(32);
|
||||
peerGroup.addPeerDiscovery(new DnsDiscovery(PARAMS));
|
||||
peerGroup.addOnTransactionBroadcastListener(new OnTransactionBroadcastListener() {
|
||||
@Override
|
||||
public void onTransaction(Peer peer, Transaction tx) {
|
||||
Result result = DefaultRiskAnalysis.FACTORY.create(null, tx, NO_DEPS).analyze();
|
||||
incrementCounter(TOTAL_KEY);
|
||||
log.info("tx {} result {}", tx.getTxId(), result);
|
||||
incrementCounter(result.name());
|
||||
if (result == Result.NON_STANDARD)
|
||||
incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx));
|
||||
}
|
||||
peerGroup.addOnTransactionBroadcastListener((peer, tx) -> {
|
||||
Result result = DefaultRiskAnalysis.FACTORY.create(null, tx, NO_DEPS).analyze();
|
||||
incrementCounter(TOTAL_KEY);
|
||||
log.info("tx {} result {}", tx.getTxId(), result);
|
||||
incrementCounter(result.name());
|
||||
if (result == Result.NON_STANDARD)
|
||||
incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx));
|
||||
});
|
||||
peerGroup.start();
|
||||
|
||||
|
|
|
@ -47,18 +47,8 @@ public class BitcoinUIModel {
|
|||
}
|
||||
|
||||
public final void setWallet(Wallet wallet) {
|
||||
wallet.addChangeEventListener(Platform::runLater, new WalletChangeEventListener() {
|
||||
@Override
|
||||
public void onWalletChanged(Wallet w) {
|
||||
updateBalance(wallet);
|
||||
}
|
||||
});
|
||||
wallet.addCurrentKeyChangeEventListener(Platform::runLater, new CurrentKeyChangeEventListener() {
|
||||
@Override
|
||||
public void onCurrentKeyChanged() {
|
||||
updateAddress(wallet);
|
||||
}
|
||||
});
|
||||
wallet.addChangeEventListener(Platform::runLater, w -> updateBalance(wallet));
|
||||
wallet.addCurrentKeyChangeEventListener(Platform::runLater, () -> updateAddress(wallet));
|
||||
updateBalance(wallet);
|
||||
updateAddress(wallet);
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue