org.bitcoinj.utils.ListenerRegistration Java Examples

The following examples show how to use org.bitcoinj.utils.ListenerRegistration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Peer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private void versionHandshakeComplete() {
    log.debug("{}: Handshake complete.", this);
    setTimeoutEnabled(false);
    for (final ListenerRegistration<PeerConnectedEventListener> registration : connectedEventListeners) {
        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();
    }
}
 
Example #2
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private void versionHandshakeComplete() {
    log.debug("{}: Handshake complete.", this);
    setTimeoutEnabled(false);
    for (final ListenerRegistration<PeerConnectedEventListener> registration : connectedEventListeners) {
        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();
    }
}
 
Example #3
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
protected void processGetData(GetDataMessage getdata) {
    log.info("{}: Received getdata message: {}", getAddress(), getdata.toString());
    ArrayList<Message> items = new ArrayList<>();
    for (ListenerRegistration<GetDataEventListener> registration : getDataEventListeners) {
        if (registration.executor != Threading.SAME_THREAD) continue;
        List<Message> listenerItems = registration.listener.getData(this, getdata);
        if (listenerItems == null) continue;
        items.addAll(listenerItems);
    }
    if (items.isEmpty()) {
        return;
    }
    log.info("{}: Sending {} items gathered from listeners to peer", getAddress(), items.size());
    for (Message item : items) {
        sendMessage(item);
    }
}
 
Example #4
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Starts an asynchronous download of the block chain. The chain download is deemed to be complete once we've
 * downloaded the same number of blocks that the peer advertised having in its version handshake message.
 */
public void startBlockChainDownload() {
    setDownloadData(true);
    // TODO: peer might still have blocks that we don't have, and even have a heavier
    // chain even if the chain block count is lower.
    final int blocksLeft = getPeerBlockHeightDifference();
    if (blocksLeft >= 0) {
        for (final ListenerRegistration<ChainDownloadStartedEventListener> registration : chainDownloadStartedEventListeners) {
            registration.executor.execute(new Runnable() {
                @Override
                public void run() {
                    registration.listener.onChainDownloadStarted(Peer.this, blocksLeft);
                }
            });
        }
        // When we just want as many blocks as possible, we can set the target hash to zero.
        lock.lock();
        try {
            blockChainDownloadLocked(Sha256Hash.ZERO_HASH);
        } finally {
            lock.unlock();
        }
    }
}
 
Example #5
Source File: Peer.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void versionHandshakeComplete() {
    log.debug("{}: Handshake complete.", this);
    setTimeoutEnabled(false);
    for (final ListenerRegistration<PeerConnectedEventListener> registration : connectedEventListeners) {
        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();
    }
}
 
Example #6
Source File: Peer.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
protected void processGetData(GetDataMessage getdata) {
    log.info("{}: Received getdata message: {}", getAddress(), getdata.toString());
    ArrayList<Message> items = new ArrayList<>();
    for (ListenerRegistration<GetDataEventListener> registration : getDataEventListeners) {
        if (registration.executor != Threading.SAME_THREAD)
            continue;
        List<Message> listenerItems = registration.listener.getData(this, getdata);
        if (listenerItems == null)
            continue;
        items.addAll(listenerItems);
    }
    if (items.isEmpty()) {
        return;
    }
    log.info("{}: Sending {} items gathered from listeners to peer", getAddress(), items.size());
    for (Message item : items) {
        sendMessage(item);
    }
}
 
Example #7
Source File: ElectrumMultiWallet.java    From java-stratum with Apache License 2.0 6 votes vote down vote up
private void notifyHeight(final long height) {
    final boolean isSynced = isChainSynced && isHistorySynced;
    log.info("notify height {} {} {}", isChainSynced, isHistorySynced, height);
    for (final ListenerRegistration<MultiWalletEventListener> registration : eventListeners) {
        if (registration.executor == Threading.SAME_THREAD) {
            registration.listener.onSyncState(this, isSynced, height);
        } else {
            registration.executor.execute(new Runnable() {
                @Override
                public void run() {
                    registration.listener.onSyncState(ElectrumMultiWallet.this, isSynced, height);
                }
            });
        }
    }
}
 
Example #8
Source File: Peer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Starts an asynchronous download of the block chain. The chain download is deemed to be complete once we've
 * downloaded the same number of blocks that the peer advertised having in its version handshake message.
 */
public void startBlockChainDownload() {
    setDownloadData(true);
    // TODO: peer might still have blocks that we don't have, and even have a heavier
    // chain even if the chain block count is lower.
    final int blocksLeft = getPeerBlockHeightDifference();
    if (blocksLeft >= 0) {
        for (final ListenerRegistration<ChainDownloadStartedEventListener> registration : chainDownloadStartedEventListeners) {
            registration.executor.execute(new Runnable() {
                @Override
                public void run() {
                    registration.listener.onChainDownloadStarted(Peer.this, blocksLeft);
                }
            });
        }
        // When we just want as many blocks as possible, we can set the target hash to zero.
        lock.lock();
        try {
            blockChainDownloadLocked(Sha256Hash.ZERO_HASH);
        } finally {
            lock.unlock();
        }
    }
}
 
Example #9
Source File: Peer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
protected void processGetData(GetDataMessage getdata) {
    log.info("{}: Received getdata message: {}", getAddress(), getdata.toString());
    ArrayList<Message> items = new ArrayList<>();
    for (ListenerRegistration<GetDataEventListener> registration : getDataEventListeners) {
        if (registration.executor != Threading.SAME_THREAD) continue;
        List<Message> listenerItems = registration.listener.getData(this, getdata);
        if (listenerItems == null) continue;
        items.addAll(listenerItems);
    }
    if (items.isEmpty()) {
        return;
    }
    log.info("{}: Sending {} items gathered from listeners to peer", getAddress(), items.size());
    for (Message item : items) {
        sendMessage(item);
    }
}
 
Example #10
Source File: Peer.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Starts an asynchronous download of the block chain. The chain download is deemed to be complete once we've
 * downloaded the same number of blocks that the peer advertised having in its version handshake message.
 */
public void startBlockChainDownload() {
    setDownloadData(true);
    // TODO: peer might still have blocks that we don't have, and even have a heavier
    // chain even if the chain block count is lower.
    final int blocksLeft = getPeerBlockHeightDifference();
    if (blocksLeft >= 0) {
        for (final ListenerRegistration<ChainDownloadStartedEventListener> registration : chainDownloadStartedEventListeners) {
            registration.executor.execute(new Runnable() {
                @Override
                public void run() {
                    registration.listener.onChainDownloadStarted(Peer.this, blocksLeft);
                }
            });
        }
        // When we just want as many blocks as possible, we can set the target hash to zero.
        lock.lock();
        try {
            blockChainDownloadLocked(Sha256Hash.ZERO_HASH);
        } finally {
            lock.unlock();
        }
    }
}
 
Example #11
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void queueOnKeysAdded(final List<ECKey> keys) {
    checkState(lock.isHeldByCurrentThread());
    for (final ListenerRegistration<KeyChainEventListener> registration : listeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onKeysAdded(keys);
            }
        });
    }
}
 
Example #12
Source File: Peer.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void invokeOnBlocksDownloaded(final Block block, @Nullable final FilteredBlock fb) {
    // 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
    // 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());
    for (final ListenerRegistration<BlocksDownloadedEventListener> registration : blocksDownloadedEventListeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onBlocksDownloaded(Peer.this, block, fb, blocksLeft);
            }
        });
    }
}
 
Example #13
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void connectionClosed() {
    for (final ListenerRegistration<PeerDisconnectedEventListener> registration : disconnectedEventListeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onPeerDisconnected(Peer.this, 0);
            }
        });
    }
}
 
Example #14
Source File: Peer.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void connectionClosed() {
    for (final ListenerRegistration<PeerDisconnectedEventListener> registration : disconnectedEventListeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onPeerDisconnected(Peer.this, 0);
            }
        });
    }
}
 
Example #15
Source File: ElectrumMultiWallet.java    From java-stratum with Apache License 2.0 5 votes vote down vote up
private void notifyTransaction(final Transaction tx, final boolean isNewCoin) {
    for (final ListenerRegistration<MultiWalletEventListener> registration : eventListeners) {
        if (registration.executor == Threading.SAME_THREAD) {
            registration.listener.onTransaction(this, tx, isNewCoin);
        } else {
            registration.executor.execute(new Runnable() {
                @Override
                public void run() {
                    registration.listener.onTransaction(ElectrumMultiWallet.this, tx, isNewCoin);
                }
            });
        }
    }
}
 
Example #16
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void queueOnKeysAdded(final List<ECKey> keys) {
    checkState(lock.isHeldByCurrentThread());
    for (final ListenerRegistration<KeyChainEventListener> registration : listeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onKeysAdded(keys);
            }
        });
    }
}
 
Example #17
Source File: Peer.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void invokeOnBlocksDownloaded(final Block block, @Nullable final FilteredBlock fb) {
    // 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
    // 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());
    for (final ListenerRegistration<BlocksDownloadedEventListener> registration : blocksDownloadedEventListeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onBlocksDownloaded(Peer.this, block, fb, blocksLeft);
            }
        });
    }
}
 
Example #18
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void invokeOnBlocksDownloaded(final Block block, @Nullable final FilteredBlock fb) {
    // 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
    // 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());
    for (final ListenerRegistration<BlocksDownloadedEventListener> registration : blocksDownloadedEventListeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onBlocksDownloaded(Peer.this, block, fb, blocksLeft);
            }
        });
    }
}
 
Example #19
Source File: BasicKeyChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void queueOnKeysAdded(final List<ECKey> keys) {
    checkState(lock.isHeldByCurrentThread());
    for (final ListenerRegistration<KeyChainEventListener> registration : listeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onKeysAdded(keys);
            }
        });
    }
}
 
Example #20
Source File: Peer.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void connectionClosed() {
    for (final ListenerRegistration<PeerDisconnectedEventListener> registration : disconnectedEventListeners) {
        registration.executor.execute(new Runnable() {
            @Override
            public void run() {
                registration.listener.onPeerDisconnected(Peer.this, 0);
            }
        });
    }
}
 
Example #21
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean removeEventListener(KeyChainEventListener listener) {
    return ListenerRegistration.removeFromList(listener, listeners);
}
 
Example #22
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public boolean removeChainDownloadStartedEventListener(ChainDownloadStartedEventListener listener) {
    return ListenerRegistration.removeFromList(listener, chainDownloadStartedEventListeners);
}
 
Example #23
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void addEventListener(KeyChainEventListener listener, Executor executor) {
    listeners.add(new ListenerRegistration<>(listener, executor));
}
 
Example #24
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public boolean removeConnectedEventListener(PeerConnectedEventListener listener) {
    return ListenerRegistration.removeFromList(listener, connectedEventListeners);
}
 
Example #25
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public List<ListenerRegistration<KeyChainEventListener>> getListeners() {
    return new ArrayList<>(listeners);
}
 
Example #26
Source File: ElectrumMultiWallet.java    From java-stratum with Apache License 2.0 4 votes vote down vote up
@Override
public boolean removeEventListener(MultiWalletEventListener listener) {
    return ListenerRegistration.removeFromList(listener, eventListeners);
}
 
Example #27
Source File: ElectrumMultiWallet.java    From java-stratum with Apache License 2.0 4 votes vote down vote up
@Override
public void addEventListener(MultiWalletEventListener listener, Executor executor) {
    eventListeners.add(new ListenerRegistration<>(listener, executor));
}
 
Example #28
Source File: Peer.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public boolean removeDisconnectedEventListener(PeerDisconnectedEventListener listener) {
    return ListenerRegistration.removeFromList(listener, disconnectedEventListeners);
}
 
Example #29
Source File: Peer.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Override
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<PreMessageReceivedEventListener> registration : preMessageReceivedEventListeners) {
        // 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;
    }

    // No further communication is possible until version handshake is complete.
    if (!(m instanceof VersionMessage || m instanceof VersionAck
            || (versionHandshakeFuture.isDone() && !versionHandshakeFuture.isCancelled())))
        throw new ProtocolException(
                "Received " + m.getClass().getSimpleName() + " before version handshake is complete.");

    if (m instanceof Ping) {
        processPing((Ping) m);
    } else if (m instanceof Pong) {
        processPong((Pong) m);
    } else 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.
        processAddressMessage((AddressMessage) m);
    } 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) {
        processVersionAck((VersionAck) m);
    } else if (m instanceof UTXOsMessage) {
        processUTXOMessage((UTXOsMessage) m);
    } else if (m instanceof RejectMessage) {
        log.error("{} {}: Received {}", this, getPeerVersionMessage().subVer, m);
    } else {
        log.warn("{}: Received unhandled message: {}", this, m);
    }
}
 
Example #30
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
/** Registers a listener that is invoked when a blockchain downloaded starts. */
public void addChainDownloadStartedEventListener(Executor executor, ChainDownloadStartedEventListener listener) {
    chainDownloadStartedEventListeners.add(new ListenerRegistration(listener, executor));
}