org.bitcoinj.utils.Threading Java Examples

The following examples show how to use org.bitcoinj.utils.Threading. 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: PeerGroup.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private void setDownloadPeer(@Nullable Peer peer) {
    lock.lock();
    try {
        if (downloadPeer == peer)
            return;
        if (downloadPeer != null) {
            log.info("Unsetting download peer: {}", downloadPeer);
            if (downloadListener != null) {
                removeDataEventListenerFromPeer(downloadPeer, downloadListener);
            }
            downloadPeer.setDownloadData(false);
        }
        downloadPeer = peer;
        if (downloadPeer != null) {
            log.info("Setting download peer: {}", downloadPeer);
            if (downloadListener != null) {
                addDataEventListenerToPeer(Threading.SAME_THREAD, peer, downloadListener);
            }
            downloadPeer.setDownloadData(true);
            if (chain != null)
                downloadPeer.setDownloadParameters(fastCatchupTimeSecs, bloomFilterMerger.getLastFilter() != null);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #2
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private Transaction cleanupCommon(Address destination) throws Exception {
    receiveATransaction(wallet, myAddress);

    Coin v2 = valueOf(0, 50);
    SendRequest req = SendRequest.to(destination, v2);
    wallet.completeTx(req);

    Transaction t2 = req.tx;

    // Broadcast the transaction and commit.
    broadcastAndCommit(wallet, t2);

    // At this point we have one pending and one spent

    Coin v1 = valueOf(0, 10);
    Transaction t = sendMoneyToWallet(null, v1, myAddress);
    Threading.waitForUserCode();
    sendMoneyToWallet(null, t);
    assertEquals("Wrong number of PENDING", 2, wallet.getPoolSize(Pool.PENDING));
    assertEquals("Wrong number of UNSPENT", 0, wallet.getPoolSize(Pool.UNSPENT));
    assertEquals("Wrong number of ALL", 3, wallet.getTransactions(true).size());
    assertEquals(valueOf(0, 60), wallet.getBalance(Wallet.BalanceType.ESTIMATED));

    // Now we have another incoming pending
    return t;
}
 
Example #3
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 #4
Source File: KeyChainGroupTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void events() throws Exception {
    // Check that events are registered with the right chains and that if a chain is added, it gets the event
    // listeners attached properly even post-hoc.
    final AtomicReference<ECKey> ran = new AtomicReference<>(null);
    final KeyChainEventListener listener = new KeyChainEventListener() {
        @Override
        public void onKeysAdded(List<ECKey> keys) {
            ran.set(keys.get(0));
        }
    };
    group.addEventListener(listener, Threading.SAME_THREAD);
    ECKey key = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertEquals(key, ran.getAndSet(null));
    ECKey key2 = new ECKey();
    group.importKeys(key2);
    assertEquals(key2, ran.getAndSet(null));
    group.removeEventListener(listener);
    ECKey key3 = new ECKey();
    group.importKeys(key3);
    assertNull(ran.get());
}
 
Example #5
Source File: KeyChainGroupTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void events() throws Exception {
    // Check that events are registered with the right chains and that if a chain is added, it gets the event
    // listeners attached properly even post-hoc.
    final AtomicReference<ECKey> ran = new AtomicReference<>(null);
    final KeyChainEventListener listener = new KeyChainEventListener() {
        @Override
        public void onKeysAdded(List<ECKey> keys) {
            ran.set(keys.get(0));
        }
    };
    group.addEventListener(listener, Threading.SAME_THREAD);
    ECKey key = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertEquals(key, ran.getAndSet(null));
    ECKey key2 = new ECKey();
    group.importKeys(key2);
    assertEquals(key2, ran.getAndSet(null));
    group.removeEventListener(listener);
    ECKey key3 = new ECKey();
    group.importKeys(key3);
    assertNull(ran.get());
}
 
Example #6
Source File: PeerGroup.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <p>Link the given wallet to this PeerGroup. This is used for three purposes:</p>
 * <p>
 * <ol>
 * <li>So the wallet receives broadcast transactions.</li>
 * <li>Announcing pending transactions that didn't get into the chain yet to our peers.</li>
 * <li>Set the fast catchup time using {@link PeerGroup#setFastCatchupTimeSecs(long)}, to optimize chain
 * download.</li>
 * </ol>
 * <p>
 * <p>Note that this should be done before chain download commences because if you add a wallet with keys earlier
 * than the current chain head, the relevant parts of the chain won't be redownloaded for you.</p>
 * <p>
 * <p>The Wallet will have an event listener registered on it, so to avoid leaks remember to use
 * {@link PeerGroup#removeWallet(Wallet)} on it if you wish to keep the Wallet but lose the PeerGroup.</p>
 */
public void addWallet(Wallet wallet) {
    lock.lock();
    try {
        checkNotNull(wallet);
        checkState(!wallets.contains(wallet));
        wallets.add(wallet);
        wallet.setTransactionBroadcaster(this);
        wallet.addCoinsReceivedEventListener(Threading.SAME_THREAD, walletCoinsReceivedEventListener);
        wallet.addKeyChainEventListener(Threading.SAME_THREAD, walletKeyEventListener);
        wallet.addScriptChangeEventListener(Threading.SAME_THREAD, walletScriptEventListener);
        addPeerFilterProvider(wallet);
        for (Peer peer : peers) {
            peer.addWallet(wallet);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #7
Source File: PeerGroup.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <p>Start downloading the blockchain from the first available peer.</p>
 * <p>
 * <p>If no peers are currently connected, the download will be started once a peer starts.  If the peer dies,
 * the download will resume with another peer.</p>
 *
 * @param listener a listener for chain download events, may not be null
 */
public void startBlockChainDownload(PeerDataEventListener listener) {
    lock.lock();
    try {
        if (downloadPeer != null) {
            if (this.downloadListener != null) {
                removeDataEventListenerFromPeer(downloadPeer, this.downloadListener);
            }
            if (listener != null) {
                addDataEventListenerToPeer(Threading.USER_THREAD, downloadPeer, listener);
            }
        }
        this.downloadListener = listener;
        // TODO: be more nuanced about which peer to download from.  We can also try
        // downloading from multiple peers and handle the case when a new peer comes along
        // with a longer chain after we thought we were done.
        if (!peers.isEmpty()) {
            startBlockChainDownloadFromPeer(peers.iterator().next()); // Will add the new download listener
        }
    } finally {
        lock.unlock();
    }
}
 
Example #8
Source File: PeerGroup.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <p>Link the given wallet to this PeerGroup. This is used for three purposes:</p>
 *
 * <ol>
 *   <li>So the wallet receives broadcast transactions.</li>
 *   <li>Announcing pending transactions that didn't get into the chain yet to our peers.</li>
 *   <li>Set the fast catchup time using {@link PeerGroup#setFastCatchupTimeSecs(long)}, to optimize chain
 *       download.</li>
 * </ol>
 *
 * <p>Note that this should be done before chain download commences because if you add a wallet with keys earlier
 * than the current chain head, the relevant parts of the chain won't be redownloaded for you.</p>
 *
 * <p>The Wallet will have an event listener registered on it, so to avoid leaks remember to use
 * {@link PeerGroup#removeWallet(Wallet)} on it if you wish to keep the Wallet but lose the PeerGroup.</p>
 */
public void addWallet(Wallet wallet) {
    lock.lock();
    try {
        checkNotNull(wallet);
        checkState(!wallets.contains(wallet));
        wallets.add(wallet);
        wallet.setTransactionBroadcaster(this);
        wallet.addCoinsReceivedEventListener(Threading.SAME_THREAD, walletCoinsReceivedEventListener);
        wallet.addKeyChainEventListener(Threading.SAME_THREAD, walletKeyEventListener);
        wallet.addScriptChangeEventListener(Threading.SAME_THREAD, walletScriptEventListener);
        addPeerFilterProvider(wallet);
        for (Peer peer : peers) {
            peer.addWallet(wallet);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #9
Source File: PeerGroup.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void setDownloadPeer(@Nullable Peer peer) {
    lock.lock();
    try {
        if (downloadPeer == peer)
            return;
        if (downloadPeer != null) {
            log.info("Unsetting download peer: {}", downloadPeer);
            if (downloadListener != null) {
                removeDataEventListenerFromPeer(downloadPeer, downloadListener);
            }
            downloadPeer.setDownloadData(false);
        }
        downloadPeer = peer;
        if (downloadPeer != null) {
            log.info("Setting download peer: {}", downloadPeer);
            if (downloadListener != null) {
                addDataEventListenerToPeer(Threading.SAME_THREAD, peer, downloadListener);
            }
            downloadPeer.setDownloadData(true);
            if (chain != null)
                downloadPeer.setDownloadParameters(fastCatchupTimeSecs, bloomFilterMerger.getLastFilter() != null);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #10
Source File: PeerGroup.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <p>Start downloading the blockchain from the first available peer.</p>
 *
 * <p>If no peers are currently connected, the download will be started once a peer starts.  If the peer dies,
 * the download will resume with another peer.</p>
 *
 * @param listener a listener for chain download events, may not be null
 */
public void startBlockChainDownload(PeerDataEventListener listener) {
    lock.lock();
    try {
        if (downloadPeer != null) {
            if (this.downloadListener != null) {
                removeDataEventListenerFromPeer(downloadPeer, this.downloadListener);
            }
            if (listener != null) {
                addDataEventListenerToPeer(Threading.USER_THREAD, downloadPeer, listener);
            }
        }
        this.downloadListener = listener;
        // TODO: be more nuanced about which peer to download from.  We can also try
        // downloading from multiple peers and handle the case when a new peer comes along
        // with a longer chain after we thought we were done.
        if (!peers.isEmpty()) {
            startBlockChainDownloadFromPeer(peers.iterator().next()); // Will add the new download listener
        }
    } finally {
        lock.unlock();
    }
}
 
Example #11
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 #12
Source File: PeerSocketHandler.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/** Catch any exceptions, logging them and then closing the channel. */
private void exceptionCaught(Exception e) {
    PeerAddress addr = getAddress();
    String s = addr == null ? "?" : addr.toString();
    if (e instanceof ConnectException || e instanceof IOException) {
        // Short message for network errors
        log.info(s + " - " + e.getMessage());
    } else {
        log.warn(s + " - ", e);
        Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
        if (handler != null)
            handler.uncaughtException(Thread.currentThread(), e);
    }

    close();
}
 
Example #13
Source File: PeerGroup.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void startBlockChainDownloadFromPeer(Peer peer) {
    lock.lock();
    try {
        setDownloadPeer(peer);

        if (chainDownloadSpeedCalculator == null) {
            // Every second, run the calculator which will log how fast we are downloading the chain.
            chainDownloadSpeedCalculator = new ChainDownloadSpeedCalculator();
            executor.scheduleAtFixedRate(chainDownloadSpeedCalculator, 1, 1, TimeUnit.SECONDS);
        }
        peer.addBlocksDownloadedEventListener(Threading.SAME_THREAD, chainDownloadSpeedCalculator);

        // startBlockChainDownload will setDownloadData(true) on itself automatically.
        peer.startBlockChainDownload();
    } finally {
        lock.unlock();
    }
}
 
Example #14
Source File: PaymentChannelServer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveContractMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(majorVersion == 1 || majorVersion == 2);
    checkState(step == InitStep.WAITING_ON_CONTRACT && msg.hasProvideContract());
    log.info("Got contract, broadcasting and responding with CHANNEL_OPEN");
    final Protos.ProvideContract providedContract = msg.getProvideContract();

    if (majorVersion == 2) {
        state = new PaymentChannelV2ServerState(broadcaster, wallet, myKey, expireTime);
        checkState(providedContract.hasClientKey(), "ProvideContract didn't have a client key in protocol v2");
        ((PaymentChannelV2ServerState)state).provideClientKey(providedContract.getClientKey().toByteArray());
    }

    //TODO notify connection handler that timeout should be significantly extended as we wait for network propagation?
    final Transaction contract = wallet.getParams().getDefaultSerializer().makeTransaction(providedContract.getTx().toByteArray());
    step = InitStep.WAITING_ON_MULTISIG_ACCEPTANCE;
    state.provideContract(contract)
            .addListener(new Runnable() {
                @Override
                public void run() {
                    multisigContractPropogated(providedContract, contract.getHash());
                }
            }, Threading.SAME_THREAD);
}
 
Example #15
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private Transaction cleanupCommon(Address destination) throws Exception {
    receiveATransaction(wallet, myAddress);

    Coin v2 = valueOf(0, 50);
    SendRequest req = SendRequest.to(destination, v2);
    wallet.completeTx(req);

    Transaction t2 = req.tx;

    // Broadcast the transaction and commit.
    broadcastAndCommit(wallet, t2);

    // At this point we have one pending and one spent

    Coin v1 = valueOf(0, 10);
    Transaction t = sendMoneyToWallet(null, v1, myAddress);
    Threading.waitForUserCode();
    sendMoneyToWallet(null, t);
    assertEquals("Wrong number of PENDING", 2, wallet.getPoolSize(Pool.PENDING));
    assertEquals("Wrong number of UNSPENT", 0, wallet.getPoolSize(Pool.UNSPENT));
    assertEquals("Wrong number of ALL", 3, wallet.getTransactions(true).size());
    assertEquals(valueOf(0, 60), wallet.getBalance(Wallet.BalanceType.ESTIMATED));

    // Now we have another incoming pending
    return t;
}
 
Example #16
Source File: PeerSocketHandler.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/** Catch any exceptions, logging them and then closing the channel. */
private void exceptionCaught(Exception e) {
    PeerAddress addr = getAddress();
    String s = addr == null ? "?" : addr.toString();
    if (e instanceof ConnectException || e instanceof IOException) {
        // Short message for network errors
        log.info(s + " - " + e.getMessage());
    } else {
        log.warn(s + " - ", e);
        Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
        if (handler != null)
            handler.uncaughtException(Thread.currentThread(), e);
    }

    close();
}
 
Example #17
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private Transaction cleanupCommon(Address destination) throws Exception {
    receiveATransaction(wallet, myAddress);

    Coin v2 = valueOf(0, 50);
    SendRequest req = SendRequest.to(destination, v2);
    wallet.completeTx(req);

    Transaction t2 = req.tx;

    // Broadcast the transaction and commit.
    broadcastAndCommit(wallet, t2);

    // At this point we have one pending and one spent

    Coin v1 = valueOf(0, 10);
    Transaction t = sendMoneyToWallet(null, v1, myAddress);
    Threading.waitForUserCode();
    sendMoneyToWallet(null, t);
    assertEquals("Wrong number of PENDING", 2, wallet.getPoolSize(Pool.PENDING));
    assertEquals("Wrong number of UNSPENT", 0, wallet.getPoolSize(Pool.UNSPENT));
    assertEquals("Wrong number of ALL", 3, wallet.getTransactions(true).size());
    assertEquals(valueOf(0, 60), wallet.getBalance(Wallet.BalanceType.ESTIMATED));

    // Now we have another incoming pending
    return t;
}
 
Example #18
Source File: Peer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <p>Construct a peer that reads/writes from the given block chain. Transactions stored in a {@link org.bitcoinj.core.TxConfidenceTable}
 * will have their confidence levels updated when a peer announces it, to reflect the greater likelyhood that
 * the transaction is valid.</p>
 *
 * <p>Note that this does <b>NOT</b> 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 org.bitcoinj.net.NioClientManager#openConnection(java.net.SocketAddress, StreamConnection)}
 * or
 * {@link org.bitcoinj.net.NioClient#NioClient(java.net.SocketAddress, StreamConnection, int)}.</p>
 *
 * <p>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.</p>
 */
public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress,
            @Nullable AbstractBlockChain chain, int downloadTxDependencyDepth) {
    super(params, remoteAddress);
    this.params = Preconditions.checkNotNull(params);
    this.versionMessage = Preconditions.checkNotNull(ver);
    this.vDownloadTxDependencyDepth = chain != null ? downloadTxDependencyDepth : 0;
    this.blockChain = chain;  // Allowed to be null.
    this.vDownloadData = chain != null;
    this.getDataFutures = new CopyOnWriteArrayList<>();
    this.getAddrFutures = new LinkedList<>();
    this.fastCatchupTimeSecs = params.getGenesisBlock().getTimeSeconds();
    this.pendingPings = new CopyOnWriteArrayList<>();
    this.vMinProtocolVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.PONG);
    this.wallets = new CopyOnWriteArrayList<>();
    this.context = Context.get();

    this.versionHandshakeFuture.addListener(new Runnable() {
        @Override
        public void run() {
            versionHandshakeComplete();
        }
    }, Threading.SAME_THREAD);
}
 
Example #19
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void keyEvents() throws Exception {
    // Check that we can register an event listener, generate some keys and the callbacks are invoked properly.
    wallet = new Wallet(PARAMS);
    final List<ECKey> keys = Lists.newLinkedList();
    wallet.addKeyChainEventListener(Threading.SAME_THREAD, new KeyChainEventListener() {
        @Override
        public void onKeysAdded(List<ECKey> k) {
            keys.addAll(k);
        }
    });
    wallet.freshReceiveKey();
    assertEquals(1, keys.size());
}
 
Example #20
Source File: Peer.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/** Deprecated: use the more specific event handler methods instead */
@Deprecated @SuppressWarnings("deprecation")
public void addEventListener(AbstractPeerEventListener listener) {
    addBlocksDownloadedEventListener(Threading.USER_THREAD, listener);
    addChainDownloadStartedEventListener(Threading.USER_THREAD, listener);
    addConnectedEventListener(Threading.USER_THREAD, listener);
    addDisconnectedEventListener(Threading.USER_THREAD, listener);
    addGetDataEventListener(Threading.USER_THREAD, listener);
    addOnTransactionBroadcastListener(Threading.USER_THREAD, listener);
    addPreMessageReceivedEventListener(Threading.USER_THREAD, listener);
}
 
Example #21
Source File: DeterministicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void events() throws Exception {
    // Check that we get the right events at the right time.
    final List<List<ECKey>> listenerKeys = Lists.newArrayList();
    long secs = 1389353062L;
    chain = new DeterministicKeyChain(ENTROPY, "", secs);
    chain.addEventListener(new AbstractKeyChainEventListener() {
        @Override
        public void onKeysAdded(List<ECKey> keys) {
            listenerKeys.add(keys);
        }
    }, Threading.SAME_THREAD);
    assertEquals(0, listenerKeys.size());
    chain.setLookaheadSize(5);
    assertEquals(0, listenerKeys.size());
    ECKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(1, listenerKeys.size());  // 1 event
    final List<ECKey> firstEvent = listenerKeys.get(0);
    assertEquals(1, firstEvent.size());
    assertTrue(firstEvent.contains(key));   // order is not specified.
    listenerKeys.clear();

    chain.maybeLookAhead();
    final List<ECKey> secondEvent = listenerKeys.get(0);
    assertEquals(12, secondEvent.size());  // (5 lookahead keys, +1 lookahead threshold) * 2 chains
    listenerKeys.clear();

    chain.getKey(KeyChain.KeyPurpose.CHANGE);
    // At this point we've entered the threshold zone so more keys won't immediately trigger more generations.
    assertEquals(0, listenerKeys.size());  // 1 event
    final int lookaheadThreshold = chain.getLookaheadThreshold() + chain.getLookaheadSize();
    for (int i = 0; i < lookaheadThreshold; i++)
        chain.getKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(1, listenerKeys.size());  // 1 event
    assertEquals(1, listenerKeys.get(0).size());  // 1 key.
}
 
Example #22
Source File: Peer.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void maybeRestartChainDownload() {
    lock.lock();
    try {
        if (awaitingFreshFilter == null)
            return;
        if (!vDownloadData) {
            // This branch should be harmless but I want to know how often it happens in reality.
            log.warn("Lost download peer status whilst awaiting fresh filter.");
            return;
        }
        // Ping/pong to wait for blocks that are still being streamed to us to finish being downloaded and
        // discarded.
        ping().addListener(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                checkNotNull(awaitingFreshFilter);
                GetDataMessage getdata = new GetDataMessage(params);
                for (Sha256Hash hash : awaitingFreshFilter)
                    getdata.addFilteredBlock(hash);
                awaitingFreshFilter = null;
                lock.unlock();

                log.info("Restarting chain download");
                sendMessage(getdata);
                // TODO: This bizarre ping-after-getdata hack probably isn't necessary.
                // It's to ensure we know when the end of a filtered block stream of txns is, but we should just be
                // able to match txns with the merkleblock. Ask Matt why it's written this way.
                sendMessage(new Ping((long) (Math.random() * Long.MAX_VALUE)));
            }
        }, Threading.SAME_THREAD);
    } finally {
        lock.unlock();
    }
}
 
Example #23
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void receiveATransactionAmount(Wallet wallet, Address toAddress, Coin amount) {
    final ListenableFuture<Coin> availFuture = wallet.getBalanceFuture(amount, Wallet.BalanceType.AVAILABLE);
    final ListenableFuture<Coin> estimatedFuture = wallet.getBalanceFuture(amount, Wallet.BalanceType.ESTIMATED);
    assertFalse(availFuture.isDone());
    assertFalse(estimatedFuture.isDone());
    // Send some pending coins to the wallet.
    Transaction t1 = sendMoneyToWallet(wallet, null, amount, toAddress);
    Threading.waitForUserCode();
    final ListenableFuture<TransactionConfidence> depthFuture = t1.getConfidence().getDepthFuture(1);
    assertFalse(depthFuture.isDone());
    assertEquals(ZERO, wallet.getBalance());
    assertEquals(amount, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    assertFalse(availFuture.isDone());
    // Our estimated balance has reached the requested level.
    assertTrue(estimatedFuture.isDone());
    assertEquals(1, wallet.getPoolSize(Pool.PENDING));
    assertEquals(0, wallet.getPoolSize(Pool.UNSPENT));
    // Confirm the coins.
    sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
    assertEquals("Incorrect confirmed tx balance", amount, wallet.getBalance());
    assertEquals("Incorrect confirmed tx PENDING pool size", 0, wallet.getPoolSize(Pool.PENDING));
    assertEquals("Incorrect confirmed tx UNSPENT pool size", 1, wallet.getPoolSize(Pool.UNSPENT));
    assertEquals("Incorrect confirmed tx ALL pool size", 1, wallet.getTransactions(true).size());
    Threading.waitForUserCode();
    assertTrue(availFuture.isDone());
    assertTrue(estimatedFuture.isDone());
    assertTrue(depthFuture.isDone());
}
 
Example #24
Source File: BasicKeyChainTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setup() {
    chain = new BasicKeyChain();
    onKeysAdded = new AtomicReference<>();
    onKeysAddedRan = new AtomicBoolean();
    chain.addEventListener(new AbstractKeyChainEventListener() {
        @Override
        public void onKeysAdded(List<ECKey> keys2) {
            onKeysAdded.set(keys2);
            onKeysAddedRan.set(true);
        }
    }, Threading.SAME_THREAD);
}
 
Example #25
Source File: ChannelConnectionTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    Utils.setMockClock(); // Use mock clock
    Context.propagate(new Context(PARAMS, 3, Coin.ZERO, false)); // Shorter event horizon for unit tests.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
    wallet.addExtension(new StoredPaymentChannelClientStates(wallet, failBroadcaster));
    serverWallet = new Wallet(PARAMS);
    serverWallet.addExtension(new StoredPaymentChannelServerStates(serverWallet, failBroadcaster));
    serverWallet.freshReceiveKey();
    // Use an atomic boolean to indicate failure because fail()/assert*() dont work in network threads
    fail = new AtomicBoolean(false);

    // Set up a way to monitor broadcast transactions. When you expect a broadcast, you must release a permit
    // to the broadcastTxPause semaphore so state can be queried in between.
    broadcasts = new LinkedBlockingQueue<>();
    broadcastTxPause = new Semaphore(0);
    mockBroadcaster = new TransactionBroadcaster() {
        @Override
        public TransactionBroadcast broadcastTransaction(Transaction tx) {
            broadcastTxPause.acquireUninterruptibly();
            SettableFuture<Transaction> future = SettableFuture.create();
            future.set(tx);
            broadcasts.add(tx);
            return TransactionBroadcast.createMockBroadcast(tx, future);
        }
    };

    // Because there are no separate threads in the tests here (we call back into client/server in server/client
    // handlers), we have lots of lock cycles. A normal user shouldn't have this issue as they are probably not both
    // client+server running in the same thread.
    Threading.warnOnLockCycles();

    ECKey.FAKE_SIGNATURES = true;
}
 
Example #26
Source File: Peer.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/** Deprecated: use the more specific event handler methods instead */
@Deprecated @SuppressWarnings("deprecation")
public void addEventListener(AbstractPeerEventListener listener) {
    addBlocksDownloadedEventListener(Threading.USER_THREAD, listener);
    addChainDownloadStartedEventListener(Threading.USER_THREAD, listener);
    addConnectedEventListener(Threading.USER_THREAD, listener);
    addDisconnectedEventListener(Threading.USER_THREAD, listener);
    addGetDataEventListener(Threading.USER_THREAD, listener);
    addOnTransactionBroadcastListener(Threading.USER_THREAD, listener);
    addPreMessageReceivedEventListener(Threading.USER_THREAD, listener);
}
 
Example #27
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 #28
Source File: BasicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setup() {
    chain = new BasicKeyChain();
    onKeysAdded = new AtomicReference<>();
    onKeysAddedRan = new AtomicBoolean();
    chain.addEventListener(new AbstractKeyChainEventListener() {
        @Override
        public void onKeysAdded(List<ECKey> keys2) {
            onKeysAdded.set(keys2);
            onKeysAddedRan.set(true);
        }
    }, Threading.SAME_THREAD);
}
 
Example #29
Source File: PeerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void startBlockChainDownload() throws Exception {
    Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block;
    blockChain.add(b1);
    Block b2 = makeSolvedTestBlock(b1);
    blockChain.add(b2);

    connect();
    fail.set(true);
    peer.addChainDownloadStartedEventListener(Threading.SAME_THREAD, new ChainDownloadStartedEventListener() {
        @Override
        public void onChainDownloadStarted(Peer p, int blocksLeft) {
            if (p == peer && blocksLeft == 108)
                fail.set(false);
        }
    });
    peer.startBlockChainDownload();

    BlockLocator expectedLocator = new BlockLocator();
    expectedLocator = expectedLocator.add(b2.getHash());
    expectedLocator = expectedLocator.add(b1.getHash());
    expectedLocator = expectedLocator.add(UNITTEST.getGenesisBlock().getHash());

    GetBlocksMessage message = (GetBlocksMessage) outbound(writeTarget);
    assertEquals(message.getLocator(), expectedLocator);
    assertEquals(Sha256Hash.ZERO_HASH, message.getStopHash());
}
 
Example #30
Source File: PeerGroup.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/** Use the more specific listener methods instead */
@Deprecated @SuppressWarnings("deprecation")
public void addEventListener(AbstractPeerEventListener listener, Executor executor) {
    addBlocksDownloadedEventListener(Threading.USER_THREAD, listener);
    addChainDownloadStartedEventListener(Threading.USER_THREAD, listener);
    addConnectedEventListener(Threading.USER_THREAD, listener);
    addDisconnectedEventListener(Threading.USER_THREAD, listener);
    addDiscoveredEventListener(Threading.USER_THREAD, listener);
    addGetDataEventListener(Threading.USER_THREAD, listener);
    addOnTransactionBroadcastListener(Threading.USER_THREAD, listener);
    addPreMessageReceivedEventListener(Threading.USER_THREAD, listener);
}