org.bitcoinj.core.PeerGroup Java Examples

The following examples show how to use org.bitcoinj.core.PeerGroup. 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: WalletConfig.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
private PeerGroup createPeerGroup() {
    // no proxy case.
    if (socks5Proxy == null) {
        return new PeerGroup(params, vChain);
    } else {
        // proxy case (tor).
        Proxy proxy = new Proxy(Proxy.Type.SOCKS,
                new InetSocketAddress(socks5Proxy.getInetAddress().getHostName(),
                        socks5Proxy.getPort()));

        ProxySocketFactory proxySocketFactory = new ProxySocketFactory(proxy);
        // we dont use tor mode if we have a local node running
        BlockingClientManager blockingClientManager = bisqEnvironment.isBitcoinLocalhostNodeRunning() ?
                new BlockingClientManager() :
                new BlockingClientManager(proxySocketFactory);

        PeerGroup peerGroup = new PeerGroup(params, vChain, blockingClientManager);

        blockingClientManager.setConnectTimeoutMillis(TIMEOUT);
        peerGroup.setConnectTimeoutMillis(TIMEOUT);

        return peerGroup;
    }
}
 
Example #2
Source File: WatchMempool.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    BriefLogFormatter.init();
    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.getHash(), result);
            incrementCounter(result.name());
            if (result == Result.NON_STANDARD)
                incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx));
        }
    });
    peerGroup.start();

    while (true) {
        Thread.sleep(STATISTICS_FREQUENCY_MS);
        printCounters();
    }
}
 
Example #3
Source File: LevelDB.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * This is just a test runner that will download blockchain till block
     * 390000 then exit.
     */
    FullPrunedBlockStore store = new LevelDBFullPrunedBlockStore(
            MainNetParams.get(), args[0], 1000, 100 * 1024 * 1024l,
            10 * 1024 * 1024, 100000, true, 390000);

    FullPrunedBlockChain vChain = new FullPrunedBlockChain(
            MainNetParams.get(), store);
    vChain.setRunScripts(false);

    PeerGroup vPeerGroup = new PeerGroup(MainNetParams.get(), vChain);
    vPeerGroup.setUseLocalhostPeerWhenPossible(true);
    vPeerGroup.addAddress(InetAddress.getLocalHost());

    vPeerGroup.start();
    vPeerGroup.downloadBlockChain();
}
 
Example #4
Source File: WatchMempool.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    BriefLogFormatter.init();
    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.getHash(), result);
            incrementCounter(result.name());
            if (result == Result.NON_STANDARD)
                incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx));
        }
    });
    peerGroup.start();

    while (true) {
        Thread.sleep(STATISTICS_FREQUENCY_MS);
        printCounters();
    }
}
 
Example #5
Source File: LevelDB.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * This is just a test runner that will download blockchain till block
     * 390000 then exit.
     */
    FullPrunedBlockStore store = new LevelDBFullPrunedBlockStore(
            MainNetParams.get(), args[0], 1000, 100 * 1024 * 1024l,
            10 * 1024 * 1024, 100000, true, 390000);

    FullPrunedBlockChain vChain = new FullPrunedBlockChain(
            MainNetParams.get(), store);
    vChain.setRunScripts(false);

    PeerGroup vPeerGroup = new PeerGroup(MainNetParams.get(), vChain);
    vPeerGroup.setUseLocalhostPeerWhenPossible(true);
    vPeerGroup.addAddress(InetAddress.getLocalHost());

    vPeerGroup.start();
    vPeerGroup.downloadBlockChain();
}
 
Example #6
Source File: WalletsSetup.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@Inject
public WalletsSetup(RegTestHost regTestHost,
                    AddressEntryList addressEntryList,
                    Preferences preferences,
                    Socks5ProxyProvider socks5ProxyProvider,
                    BisqEnvironment bisqEnvironment,
                    BitcoinNodes bitcoinNodes,
                    @Named(BtcOptionKeys.USER_AGENT) String userAgent,
                    @Named(BtcOptionKeys.WALLET_DIR) File appDir,
                    @Named(BtcOptionKeys.USE_ALL_PROVIDED_NODES) String useAllProvidedNodes,
                    @Named(BtcOptionKeys.NUM_CONNECTIONS_FOR_BTC) String numConnectionForBtc,
                    @Named(BtcOptionKeys.SOCKS5_DISCOVER_MODE) String socks5DiscoverModeString) {
    this.regTestHost = regTestHost;
    this.addressEntryList = addressEntryList;
    this.preferences = preferences;
    this.socks5ProxyProvider = socks5ProxyProvider;
    this.bisqEnvironment = bisqEnvironment;
    this.bitcoinNodes = bitcoinNodes;
    this.numConnectionForBtc = numConnectionForBtc != null ? Integer.parseInt(numConnectionForBtc) : DEFAULT_CONNECTIONS;
    this.useAllProvidedNodes = "true".equals(useAllProvidedNodes);
    this.userAgent = userAgent;

    this.socks5DiscoverMode = evaluateMode(socks5DiscoverModeString);

    btcWalletFileName = "bisq_" + BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode() + ".wallet";
    params = BisqEnvironment.getParameters();
    walletDir = new File(appDir, "wallet");
    PeerGroup.setIgnoreHttpSeeds(true);
}
 
Example #7
Source File: WalletsSetup.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Inject
public WalletsSetup(RegTestHost regTestHost,
                    AddressEntryList addressEntryList,
                    Preferences preferences,
                    Socks5ProxyProvider socks5ProxyProvider,
                    Config config,
                    LocalBitcoinNode localBitcoinNode,
                    BtcNodes btcNodes,
                    @Named(Config.USER_AGENT) String userAgent,
                    @Named(Config.WALLET_DIR) File walletDir,
                    @Named(Config.USE_ALL_PROVIDED_NODES) boolean useAllProvidedNodes,
                    @Named(Config.NUM_CONNECTIONS_FOR_BTC) int numConnectionsForBtc,
                    @Named(Config.SOCKS5_DISCOVER_MODE) String socks5DiscoverModeString) {
    this.regTestHost = regTestHost;
    this.addressEntryList = addressEntryList;
    this.preferences = preferences;
    this.socks5ProxyProvider = socks5ProxyProvider;
    this.config = config;
    this.localBitcoinNode = localBitcoinNode;
    this.btcNodes = btcNodes;
    this.numConnectionsForBtc = numConnectionsForBtc;
    this.useAllProvidedNodes = useAllProvidedNodes;
    this.userAgent = userAgent;
    this.socks5DiscoverMode = evaluateMode(socks5DiscoverModeString);
    this.walletDir = walletDir;

    btcWalletFileName = "bisq_" + config.baseCurrencyNetwork.getCurrencyCode() + ".wallet";
    params = Config.baseCurrencyNetworkParameters();
    PeerGroup.setIgnoreHttpSeeds(true);
}
 
Example #8
Source File: NetworkMonitorActivity.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onResumeWithService() {

    registerReceiver(uiUpdated, new IntentFilter("PEERGROUP_UPDATED"));

    if (mService.isForcedOff()) {
        // FIXME: Should pass flag to activity so it shows it was forced logged out
        startActivity(new Intent(this, FirstScreenActivity.class));
        finish();
        return;
    }

    mPeers.clear();

    final PeerGroup peerGroup = mService.getSPVPeerGroup();
    if (peerGroup == null || !peerGroup.isRunning())
        return;

    mService.enableSPVPingMonitoring();

    for (final Peer peer : peerGroup.getConnectedPeers())
        mPeers.add(new PrettyPeer(peer));

    final String bloomDetails;
    if (!mPeers.isEmpty())
        bloomDetails = mPeers.get(0).mPeer.getBloomFilter().toString();
    else
        bloomDetails = getString(R.string.network_monitor_bloom_info);

    final int currentBlock = mService.getCurrentBlock();
    final int spvHeight = mService.getSPVHeight();
    mBloomInfoText.setText(getString(R.string.network_monitor_banner, bloomDetails, currentBlock - spvHeight));

    mPeerList.setAdapter(mPeerListAdapter);

    peerGroup.addConnectedEventListener(this);
    peerGroup.addDisconnectedEventListener(this);
    mRefreshCallback.run();
}
 
Example #9
Source File: NetworkMonitorActivity.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPauseWithService() {

    mService.disableSPVPingMonitoring();
    mRefreshHandler.removeCallbacks(mRefreshCallback);

    unregisterReceiver(uiUpdated);
    final PeerGroup peerGroup = mService.getSPVPeerGroup();
    if (peerGroup != null) {
        peerGroup.removeConnectedEventListener(this);
        peerGroup.removeDisconnectedEventListener(this);
    }

    mPeers.clear();
}
 
Example #10
Source File: SPV.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public PeerGroup getPeerGroup(){
    return mPeerGroup;
}
 
Example #11
Source File: TxBroadcaster.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void broadcastTx(Wallet wallet, PeerGroup peerGroup, Transaction tx, Callback callback, int delayInSec) {
    Timer timeoutTimer;
    final String txId = tx.getHashAsString();
    if (!broadcastTimerMap.containsKey(txId)) {
        timeoutTimer = UserThread.runAfter(() -> {
            log.warn("Broadcast of tx {} not completed after {} sec.", txId, delayInSec);
            stopAndRemoveTimer(txId);
            UserThread.execute(() -> callback.onTimeout(new TxBroadcastTimeoutException(tx, delayInSec, wallet)));
        }, delayInSec);

        broadcastTimerMap.put(txId, timeoutTimer);
    } else {
        // Would be the wrong way how to use the API (calling 2 times a broadcast with same tx).
        // An arbitrator reported that got the error after a manual payout, need to investigate why...
        stopAndRemoveTimer(txId);
        UserThread.execute(() -> callback.onFailure(new TxBroadcastException("We got broadcastTx called with a tx " +
                "which has an open timeoutTimer. txId=" + txId, txId)));
    }

    // We decided the least risky scenario is to commit the tx to the wallet and broadcast it later.
    // If it's a bsq tx WalletManager.publishAndCommitBsqTx() should have committed the tx to both bsq and btc
    // wallets so the next line causes no effect.
    // If it's a btc tx, the next line adds the tx to the wallet.
    wallet.maybeCommitTx(tx);

    Futures.addCallback(peerGroup.broadcastTransaction(tx).future(), new FutureCallback<>() {
        @Override
        public void onSuccess(@Nullable Transaction result) {
            // We expect that there is still a timeout in our map, otherwise the timeout got triggered
            if (broadcastTimerMap.containsKey(txId)) {
                stopAndRemoveTimer(txId);
                // At regtest we get called immediately back but we want to make sure that the handler is not called
                // before the caller is finished.
                UserThread.execute(() -> callback.onSuccess(tx));
            } else {
                log.warn("We got an onSuccess callback for a broadcast which already triggered the timeout. txId={}", txId);
            }
        }

        @Override
        public void onFailure(@NotNull Throwable throwable) {
            stopAndRemoveTimer(txId);
            UserThread.execute(() -> callback.onFailure(new TxBroadcastException("We got an onFailure from " +
                    "the peerGroup.broadcastTransaction callback.", throwable)));
        }
    });
}
 
Example #12
Source File: TxBroadcaster.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void broadcastTx(Wallet wallet, PeerGroup peerGroup, Transaction localTx, Callback callback) {
    broadcastTx(wallet, peerGroup, localTx, callback, DEFAULT_BROADCAST_TIMEOUT);
}
 
Example #13
Source File: WalletConfig.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public PeerGroup peerGroup() {
    checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
    return vPeerGroup;
}
 
Example #14
Source File: WalletsSetup.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public PeerGroup getPeerGroup() {
    return walletConfig.peerGroup();
}
 
Example #15
Source File: WalletAppKitService.java    From consensusj with Apache License 2.0 4 votes vote down vote up
public PeerGroup getPeerGroup() {
    kit.awaitRunning();
    return kit.peerGroup();
}
 
Example #16
Source File: BitcoinConfig.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Bean
PeerStompService peerStompService(Context context,
                                  PeerGroup peerGroup,
                                  SimpMessageSendingOperations messagingTemplate) {
    return new PeerStompService(context, peerGroup, messagingTemplate);
}
 
Example #17
Source File: SPV.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
private void updateUnspentOutputs(final List<JSONMap> utxos) {
    final Set<TransactionOutPoint> newUtxos = new HashSet<>();
    boolean recalculateBloom = false;

    Log.d(TAG, Var("number of utxos", utxos.size()));
    for (final JSONMap utxo : utxos) {
        final Integer prevIndex = utxo.getInt("pt_idx");
        final Integer subaccount = utxo.getInt("subaccount");
        final Integer pointer = utxo.getInt("pointer");
        final Sha256Hash txHash = utxo.getHash("txhash");

        if (isVerified(txHash)) {
            addToUtxo(txHash, prevIndex, subaccount, pointer);
            addUtxoToValues(txHash, false /* updateVerified */);
        } else {
            recalculateBloom = true;
            addToBloomFilter(utxo.getInt("block_height"), txHash, prevIndex, subaccount, pointer);
        }
        newUtxos.add(createOutPoint(prevIndex, txHash, mService.getNetworkParameters()));
    }

    final List<Integer> changedSubaccounts = new ArrayList<>();
    for (final TransactionOutPoint oldUtxo : new HashSet<>(mCountedUtxoValues.keySet())) {
        if (!newUtxos.contains(oldUtxo)) {
            recalculateBloom = true;

            final int subAccount = mUnspentDetails.get(oldUtxo).getSubAccount();
            final Coin verifiedBalance = getVerifiedBalance(subAccount);
            mVerifiedCoinBalances.put(subAccount,
                                      verifiedBalance.subtract(mCountedUtxoValues.get(oldUtxo)));
            changedSubaccounts.add(subAccount);
            mCountedUtxoValues.remove(oldUtxo);
            mUnspentDetails.remove(oldUtxo);
            mUnspentOutpoints.get(oldUtxo.getHash()).remove(((int) oldUtxo.getIndex()));
        }
    }

    if (recalculateBloom && mPeerGroup != null)
        mPeerGroup.recalculateFastCatchupAndFilter(PeerGroup.FilterRecalculateMode.SEND_IF_CHANGED);

    fireBalanceChanged(changedSubaccounts);
}
 
Example #18
Source File: TxBroadcaster.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void broadcastTx(Wallet wallet, PeerGroup peerGroup, Transaction localTx, Callback callback) {
    broadcastTx(wallet, peerGroup, localTx, callback, DEFAULT_BROADCAST_TIMEOUT);
}
 
Example #19
Source File: SPV.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
void updateUnspentOutputs() {
    final NetworkData networkData = mService.getNetwork();
    final boolean currentlyEnabled = isEnabled();
    Log.d(TAG, "updateUnspentOutputs: " + Var("currentlyEnabled", currentlyEnabled));

    final List<TransactionData> utxos = new ArrayList<>();
    for (final SubaccountData subaccountData : mSubaccounts) {
        try {
            List<TransactionData> transactionDataList = getUtxos(subaccountData.getPointer());
            utxos.addAll(transactionDataList);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    final Set<TransactionOutPoint> newUtxos = new HashSet<>();
    boolean recalculateBloom = false;

    Log.d(TAG, Var("number of utxos", utxos.size()));
    for (final TransactionData utxo : utxos) {
        final Integer prevIndex = utxo.getPtIdx();
        final Integer subaccount = utxo.getSubaccount();
        final Integer pointer = utxo.getPointer();
        final Sha256Hash txHash = utxo.getTxhashAsSha256Hash();

        if (isVerified(txHash.toString())) {
            addToUtxo(txHash, prevIndex, subaccount, pointer);
            addUtxoToValues(txHash, false /* updateVerified */);
        } else {
            recalculateBloom = true;
            addToBloomFilter(utxo.getBlockHeight(), txHash, prevIndex, subaccount, pointer);
        }
        newUtxos.add(createOutPoint(prevIndex, txHash, networkData.getNetworkParameters()));
    }

    mPeerGroup.setFastCatchupTimeSecs(1393545600);  // GA inception

    final List<Integer> changedSubaccounts = new ArrayList<>();
    for (final TransactionOutPoint oldUtxo : new HashSet<>(mCountedUtxoValues.keySet())) {
        if (!newUtxos.contains(oldUtxo)) {
            recalculateBloom = true;

            final int subAccount = mUnspentDetails.get(oldUtxo).getSubAccount();
            final Coin verifiedBalance = getVerifiedBalance(subAccount);
            mVerifiedCoinBalances.put(subAccount,
                                      verifiedBalance.subtract(mCountedUtxoValues.get(oldUtxo)));
            changedSubaccounts.add(subAccount);
            mCountedUtxoValues.remove(oldUtxo);
            mUnspentDetails.remove(oldUtxo);
            mUnspentOutpoints.get(oldUtxo.getHash()).remove(((int) oldUtxo.getIndex()));
        }
    }

    if (recalculateBloom && mPeerGroup != null)
        mPeerGroup.recalculateFastCatchupAndFilter(PeerGroup.FilterRecalculateMode.SEND_IF_CHANGED);
}
 
Example #20
Source File: SPV.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public PeerGroup getPeerGroup(){
    return mPeerGroup;
}
 
Example #21
Source File: WalletConfig.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public PeerGroup peerGroup() {
    checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
    return vPeerGroup;
}
 
Example #22
Source File: WalletsSetup.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public PeerGroup getPeerGroup() {
    return walletConfig.peerGroup();
}
 
Example #23
Source File: WalletsSetup.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public void initialize(@Nullable DeterministicSeed seed, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
    Log.traceCall();

    // Tell bitcoinj to execute event handlers on the JavaFX UI thread. This keeps things simple and means
    // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
    // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
    // a future version.

    Threading.USER_THREAD = UserThread.getExecutor();

    Timer timeoutTimer = UserThread.runAfter(() ->
            exceptionHandler.handleException(new TimeoutException("Wallet did not initialize in " +
                    STARTUP_TIMEOUT + " seconds.")), STARTUP_TIMEOUT);

    backupWallets();

    final Socks5Proxy socks5Proxy = preferences.getUseTorForBitcoinJ() ? socks5ProxyProvider.getSocks5Proxy() : null;
    log.info("Socks5Proxy for bitcoinj: socks5Proxy=" + socks5Proxy);

    walletConfig = new WalletConfig(params,
            socks5Proxy,
            walletDir,
            bisqEnvironment,
            userAgent,
            numConnectionForBtc,
            btcWalletFileName,
            BSQ_WALLET_FILE_NAME,
            SPV_CHAIN_FILE_NAME) {
        @Override
        protected void onSetupCompleted() {
            //We are here in the btcj thread Thread[ STARTING,5,main]
            super.onSetupCompleted();

            final PeerGroup peerGroup = walletConfig.peerGroup();

            // We don't want to get our node white list polluted with nodes from AddressMessage calls.
            if (preferences.getBitcoinNodes() != null && !preferences.getBitcoinNodes().isEmpty())
                peerGroup.setAddPeersFromAddressMessage(false);

            peerGroup.addConnectedEventListener((peer, peerCount) -> {
                // We get called here on our user thread
                numPeers.set(peerCount);
                connectedPeers.set(peerGroup.getConnectedPeers());
            });
            peerGroup.addDisconnectedEventListener((peer, peerCount) -> {
                // We get called here on our user thread
                numPeers.set(peerCount);
                connectedPeers.set(peerGroup.getConnectedPeers());
            });

            // Map to user thread
            UserThread.execute(() -> {
                addressEntryList.onWalletReady(walletConfig.getBtcWallet());
                timeoutTimer.stop();
                setupCompletedHandlers.stream().forEach(Runnable::run);
            });

            // onSetupCompleted in walletAppKit is not the called on the last invocations, so we add a bit of delay
            UserThread.runAfter(resultHandler::handleResult, 100, TimeUnit.MILLISECONDS);
        }
    };

    if (params == RegTestParams.get()) {
        walletConfig.setMinBroadcastConnections(1);
        if (regTestHost == RegTestHost.LOCALHOST) {
            walletConfig.setPeerNodesForLocalHost();
        } else if (regTestHost == RegTestHost.REG_TEST_SERVER) {
            walletConfig.setMinBroadcastConnections(1);
            configPeerNodesForRegTestServer();
        } else {
            configPeerNodes(socks5Proxy);
        }
    } else if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) {
        walletConfig.setMinBroadcastConnections(1);
        walletConfig.setPeerNodesForLocalHost();
    } else {
        configPeerNodes(socks5Proxy);
    }

    walletConfig.setDownloadListener(downloadListener)
            .setBlockingStartup(false);

    // If seed is non-null it means we are restoring from backup.
    walletConfig.setSeed(seed);

    walletConfig.addListener(new Service.Listener() {
        @Override
        public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
            walletConfig = null;
            log.error("Service failure from state: {}; failure={}", from, failure);
            timeoutTimer.stop();
            UserThread.execute(() -> exceptionHandler.handleException(failure));
        }
    }, Threading.USER_THREAD);

    walletConfig.startAsync();
}
 
Example #24
Source File: TxBroadcaster.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void broadcastTx(Wallet wallet, PeerGroup peerGroup, Transaction tx, Callback callback, int delayInSec) {
    Timer timeoutTimer;
    final String txId = tx.getHashAsString();
    if (!broadcastTimerMap.containsKey(txId)) {
        timeoutTimer = UserThread.runAfter(() -> {
            log.warn("Broadcast of tx {} not completed after {} sec.", txId, delayInSec);
            stopAndRemoveTimer(txId);
            UserThread.execute(() -> callback.onTimeout(new TxBroadcastTimeoutException(tx, delayInSec, wallet)));
        }, delayInSec);

        broadcastTimerMap.put(txId, timeoutTimer);
    } else {
        // Would be due a wrong way how to use the API (calling 2 times a broadcast with same tx).
        stopAndRemoveTimer(txId);
        UserThread.execute(() -> callback.onFailure(new TxBroadcastException("We got broadcastTx called with a tx " +
                "which has an open timeoutTimer. txId=" + txId, txId)));
    }

    Futures.addCallback(peerGroup.broadcastTransaction(tx).future(), new FutureCallback<Transaction>() {
        @Override
        public void onSuccess(@Nullable Transaction result) {
            if (result != null) {
                if (txId.equals(result.getHashAsString())) {
                    // We expect that there is still a timeout in our map, otherwise the timeout got triggered
                    if (broadcastTimerMap.containsKey(txId)) {
                        wallet.maybeCommitTx(tx);
                        stopAndRemoveTimer(txId);
                        // At regtest we get called immediately back but we want to make sure that the handler is not called
                        // before the caller is finished.
                        UserThread.execute(() -> callback.onSuccess(tx));
                    } else {
                        stopAndRemoveTimer(txId);
                        log.warn("We got an onSuccess callback for a broadcast which already triggered the timeout.", txId);
                    }
                } else {
                    stopAndRemoveTimer(txId);
                    UserThread.execute(() -> callback.onTxMalleability(new TxMalleabilityException(tx, result)));
                }
            } else {
                stopAndRemoveTimer(txId);
                UserThread.execute(() -> callback.onFailure(new TxBroadcastException("Transaction returned from the " +
                        "broadcastTransaction call back is null.", txId)));
            }
        }

        @Override
        public void onFailure(@NotNull Throwable throwable) {
            stopAndRemoveTimer(txId);
            UserThread.execute(() -> callback.onFailure(new TxBroadcastException("We got an onFailure from " +
                    "the peerGroup.broadcastTransaction callback.", throwable)));
        }
    });
}
 
Example #25
Source File: SPV.java    From GreenBits with GNU General Public License v3.0 votes vote down vote up
public void enablePingMonitoring() { setPingInterval(PeerGroup.DEFAULT_PING_INTERVAL_MSEC); } 
Example #26
Source File: GaService.java    From GreenBits with GNU General Public License v3.0 votes vote down vote up
public PeerGroup getSPVPeerGroup() { return mSPV.getPeerGroup(); } 
Example #27
Source File: SPV.java    From green_android with GNU General Public License v3.0 votes vote down vote up
public PeerGroup getSPVPeerGroup() { return getPeerGroup(); } 
Example #28
Source File: SPV.java    From green_android with GNU General Public License v3.0 votes vote down vote up
public void enablePingMonitoring() { setPingInterval(PeerGroup.DEFAULT_PING_INTERVAL_MSEC); }