Search in sources :

Example 1 with BlockChain

use of org.bitcoinj.core.BlockChain in project bitcoin-wallet by bitcoin-wallet.

the class BlockchainService method onCreate.

@Override
public void onCreate() {
    serviceCreatedAt = System.currentTimeMillis();
    log.debug(".onCreate()");
    super.onCreate();
    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    application = (WalletApplication) getApplication();
    config = application.getConfiguration();
    final Wallet wallet = application.getWallet();
    peerConnectivityListener = new PeerConnectivityListener();
    broadcastPeerState(0);
    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();
    if (!blockChainFileExists) {
        log.info("blockchain does not exist, resetting wallet");
        wallet.reset();
    }
    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        // detect corruptions as early as possible
        blockStore.getChainHead();
        final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
        if (!blockChainFileExists && earliestKeyCreationTime > 0) {
            try {
                final Stopwatch watch = Stopwatch.createStarted();
                final InputStream checkpointsInputStream = getAssets().open(Constants.Files.CHECKPOINTS_FILENAME);
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore, earliestKeyCreationTime);
                watch.stop();
                log.info("checkpoints loaded from '{}', took {}", Constants.Files.CHECKPOINTS_FILENAME, watch);
            } catch (final IOException x) {
                log.error("problem reading checkpoints, continuing without", x);
            }
        }
    } catch (final BlockStoreException x) {
        blockChainFile.delete();
        final String msg = "blockstore cannot be created";
        log.error(msg, x);
        throw new Error(msg, x);
    }
    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    // implicitly start PeerGroup
    registerReceiver(connectivityReceiver, intentFilter);
    application.getWallet().addCoinsReceivedEventListener(Threading.SAME_THREAD, walletEventListener);
    application.getWallet().addCoinsSentEventListener(Threading.SAME_THREAD, walletEventListener);
    application.getWallet().addChangeEventListener(Threading.SAME_THREAD, walletEventListener);
    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
Also used : IntentFilter(android.content.IntentFilter) BlockStoreException(org.bitcoinj.store.BlockStoreException) BlockChain(org.bitcoinj.core.BlockChain) Wallet(org.bitcoinj.wallet.Wallet) InputStream(java.io.InputStream) SPVBlockStore(org.bitcoinj.store.SPVBlockStore) Stopwatch(com.google.common.base.Stopwatch) IOException(java.io.IOException) PowerManager(android.os.PowerManager) File(java.io.File)

Example 2 with BlockChain

use of org.bitcoinj.core.BlockChain in project catena-java by alinush.

the class ReorganizeChainTest method setUp.

@Before
public void setUp() throws Exception {
    Context.propagate(new Context(params, 10000, Transaction.DEFAULT_TX_FEE, true));
    semAppended = new Semaphore(0);
    semWithdrawn = new Semaphore(0);
    // Step 0: Catena wallet already started with a listener that signals when statements are appended and withdrawn
    wallet = new ClientWallet(params);
    wallet.addExtension(new CatenaWalletExtension());
    // Generate a key to send mining rewards to
    genCoinsKey = new ECKey();
    wallet.importKey(genCoinsKey);
    genCoinsAddr = genCoinsKey.toAddress(params);
    // need to tell the wallet about the chain address by calling this
    wallet.addWatchedAddress(genCoinsAddr);
    // Generate a black hole key, where funds are send to be lost
    blackholeAddr = new ECKey().toAddress(params);
    // Add semaphores to wallet
    wallet.addStatementListener(new SemaphoredStatementListener(wallet, semAppended, semWithdrawn));
    wallet.addReorganizeEventListener(new WalletReorganizeEventListener() {

        @Override
        public void onReorganize(Wallet wallet) {
            log.debug("Fork detected!");
        }
    });
    // TODO: can set an onReorganize listener here
    chain = new BlockChain(params, wallet, new MemoryBlockStore(params));
    // Set a listener to wait for those coins
    final Semaphore sem = new Semaphore(0);
    wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {

        @Override
        public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
            // log.debug("Got initial coins from mining reward: {}", newBalance);
            sem.release();
        }
    });
    // Create the first block, so we can get some coins.
    lastBlock = params.getGenesisBlock().createNextBlock(genCoinsAddr);
    chain.add(lastBlock);
    // Bury the first block with enough blocks, so we can spend those coins
    for (int i = 0; i < params.getSpendableCoinbaseDepth(); i++) {
        lastBlock = lastBlock.createNextBlock(blackholeAddr);
        chain.add(lastBlock);
    }
    log.debug("Created {} blocks.", chain.getBestChainHeight());
    assertTrue("timed out waiting to receive coins from block reward", sem.tryAcquire(10, TimeUnit.SECONDS));
    // Create the root-of-trust TXN
    Transaction tx = issueStatement("testchain", false);
    log.debug("Created root-of-trust TXN {}", tx.getHash());
    // wallet.getCatenaExtension().setRootOfTrustTxid(rootOfTrustTxid); // already set by issueStatement
    wallet.addChangeEventListener(Threading.SAME_THREAD, new CatenaWalletListener(wallet));
}
Also used : Context(org.bitcoinj.core.Context) BlockChain(org.bitcoinj.core.BlockChain) ClientWallet(org.catena.client.ClientWallet) Wallet(org.bitcoinj.wallet.Wallet) CatenaWalletExtension(org.catena.common.CatenaWalletExtension) ClientWallet(org.catena.client.ClientWallet) ECKey(org.bitcoinj.core.ECKey) WalletReorganizeEventListener(org.bitcoinj.wallet.listeners.WalletReorganizeEventListener) WalletCoinsReceivedEventListener(org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener) Semaphore(java.util.concurrent.Semaphore) MemoryBlockStore(org.bitcoinj.store.MemoryBlockStore) SemaphoredStatementListener(org.catena.common.SemaphoredStatementListener) Coin(org.bitcoinj.core.Coin) Transaction(org.bitcoinj.core.Transaction) Before(org.junit.Before)

Example 3 with BlockChain

use of org.bitcoinj.core.BlockChain in project bisq-core by bisq-network.

the class WalletConfig method startUp.

@Override
protected void startUp() throws Exception {
    // Runs in a separate thread.
    Context.propagate(context);
    if (!directory.exists()) {
        if (!directory.mkdirs()) {
            throw new IOException("Could not create directory " + directory.getAbsolutePath());
        }
    }
    log.info("Wallet directory: {}", directory);
    try {
        File chainFile = new File(directory, spvChainFileName);
        boolean chainFileExists = chainFile.exists();
        // BTC wallet
        vBtcWalletFile = new File(directory, btcWalletFileName);
        boolean shouldReplayWallet = (vBtcWalletFile.exists() && !chainFileExists) || seed != null;
        BisqKeyChainGroup keyChainGroup;
        if (seed != null)
            keyChainGroup = new BisqKeyChainGroup(params, new BtcDeterministicKeyChain(seed), true);
        else
            keyChainGroup = new BisqKeyChainGroup(params, true);
        vBtcWallet = createOrLoadWallet(vBtcWalletFile, shouldReplayWallet, keyChainGroup, false, seed);
        vBtcWallet.allowSpendingUnconfirmedTransactions();
        if (seed != null)
            keyChainGroup = new BisqKeyChainGroup(params, new BisqDeterministicKeyChain(seed), false);
        else
            keyChainGroup = new BisqKeyChainGroup(params, new BisqDeterministicKeyChain(vBtcWallet.getKeyChainSeed()), false);
        // BSQ wallet
        if (BisqEnvironment.isBaseCurrencySupportingBsq()) {
            vBsqWalletFile = new File(directory, bsqWalletFileName);
            vBsqWallet = createOrLoadWallet(vBsqWalletFile, shouldReplayWallet, keyChainGroup, true, seed);
        }
        // Initiate Bitcoin network objects (block store, blockchain and peer group)
        vStore = provideBlockStore(chainFile);
        if (!chainFileExists || seed != null) {
            if (checkpoints != null) {
                // Initialize the chain file with a checkpoint to speed up first-run sync.
                long time;
                if (seed != null) {
                    // we created both wallets at the same time
                    time = seed.getCreationTimeSeconds();
                    if (chainFileExists) {
                        log.info("Deleting the chain file in preparation from restore.");
                        vStore.close();
                        if (!chainFile.delete())
                            throw new IOException("Failed to delete chain file in preparation for restore.");
                        vStore = new SPVBlockStore(params, chainFile);
                    }
                } else {
                    time = vBtcWallet.getEarliestKeyCreationTime();
                }
                if (time > 0)
                    CheckpointManager.checkpoint(params, checkpoints, vStore, time);
                else
                    log.warn("Creating a new uncheckpointed block store due to a wallet with a creation time of zero: this will result in a very slow chain sync");
            } else if (chainFileExists) {
                log.info("Deleting the chain file in preparation from restore.");
                vStore.close();
                if (!chainFile.delete())
                    throw new IOException("Failed to delete chain file in preparation for restore.");
                vStore = new SPVBlockStore(params, chainFile);
            }
        }
        vChain = new BlockChain(params, vStore);
        vPeerGroup = createPeerGroup();
        vPeerGroup.setBroadcastToAllPeers(true);
        if (minBroadcastConnections > 0)
            vPeerGroup.setMinBroadcastConnections(minBroadcastConnections);
        vPeerGroup.setUserAgent(userAgent, Version.VERSION);
        // before we're actually connected the broadcast waits for an appropriate number of connections.
        if (peerAddresses != null) {
            for (PeerAddress addr : peerAddresses) vPeerGroup.addAddress(addr);
            log.info("We try to connect to {} btc nodes", numConnectionForBtc);
            vPeerGroup.setMaxConnections(Math.min(numConnectionForBtc, peerAddresses.length));
            peerAddresses = null;
        } else if (!params.equals(RegTestParams.get())) {
            vPeerGroup.addPeerDiscovery(discovery != null ? discovery : new DnsDiscovery(params));
        }
        vChain.addWallet(vBtcWallet);
        vPeerGroup.addWallet(vBtcWallet);
        if (vBsqWallet != null) {
            // noinspection ConstantConditions
            vChain.addWallet(vBsqWallet);
            // noinspection ConstantConditions
            vPeerGroup.addWallet(vBsqWallet);
        }
        onSetupCompleted();
        if (blockingStartup) {
            vPeerGroup.start();
            // Make sure we shut down cleanly.
            installShutdownHook();
            final DownloadProgressTracker listener = new DownloadProgressTracker();
            vPeerGroup.startBlockChainDownload(listener);
            listener.await();
        } else {
            Futures.addCallback(vPeerGroup.startAsync(), new FutureCallback() {

                @Override
                public void onSuccess(@Nullable Object result) {
                    final PeerDataEventListener listener = downloadListener == null ? new DownloadProgressTracker() : downloadListener;
                    vPeerGroup.startBlockChainDownload(listener);
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                    throw new RuntimeException(t);
                }
            });
        }
    } catch (BlockStoreException e) {
        throw new IOException(e);
    }
}
Also used : BlockChain(org.bitcoinj.core.BlockChain) BlockStoreException(org.bitcoinj.store.BlockStoreException) PeerDataEventListener(org.bitcoinj.core.listeners.PeerDataEventListener) SPVBlockStore(org.bitcoinj.store.SPVBlockStore) IOException(java.io.IOException) DnsDiscovery(org.bitcoinj.net.discovery.DnsDiscovery) PeerAddress(org.bitcoinj.core.PeerAddress) DownloadProgressTracker(org.bitcoinj.core.listeners.DownloadProgressTracker) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Aggregations

BlockChain (org.bitcoinj.core.BlockChain)3 File (java.io.File)2 IOException (java.io.IOException)2 BlockStoreException (org.bitcoinj.store.BlockStoreException)2 SPVBlockStore (org.bitcoinj.store.SPVBlockStore)2 Wallet (org.bitcoinj.wallet.Wallet)2 IntentFilter (android.content.IntentFilter)1 PowerManager (android.os.PowerManager)1 Stopwatch (com.google.common.base.Stopwatch)1 FutureCallback (com.google.common.util.concurrent.FutureCallback)1 InputStream (java.io.InputStream)1 RandomAccessFile (java.io.RandomAccessFile)1 Semaphore (java.util.concurrent.Semaphore)1 Coin (org.bitcoinj.core.Coin)1 Context (org.bitcoinj.core.Context)1 ECKey (org.bitcoinj.core.ECKey)1 PeerAddress (org.bitcoinj.core.PeerAddress)1 Transaction (org.bitcoinj.core.Transaction)1 DownloadProgressTracker (org.bitcoinj.core.listeners.DownloadProgressTracker)1 PeerDataEventListener (org.bitcoinj.core.listeners.PeerDataEventListener)1