org.bitcoinj.store.BlockStoreException Java Examples

The following examples show how to use org.bitcoinj.store.BlockStoreException. 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
@Override
protected void shutDown() throws Exception {
    // Runs in a separate thread.
    try {
        Context.propagate(context);
        vPeerGroup.stop();
        vBtcWallet.saveToFile(vBtcWalletFile);
        if (vBsqWallet != null && vBsqWalletFile != null)
            //noinspection ConstantConditions,ConstantConditions
            vBsqWallet.saveToFile(vBsqWalletFile);
        vStore.close();

        vPeerGroup = null;
        vBtcWallet = null;
        vBsqWallet = null;
        vStore = null;
        vChain = null;
    } catch (BlockStoreException e) {
        throw new IOException(e);
    } catch (Throwable ignore) {
    }
}
 
Example #2
Source File: VersionTallyTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testInitialize() throws BlockStoreException {
    final BlockStore blockStore = new MemoryBlockStore(PARAMS);
    final BlockChain chain = new BlockChain(PARAMS, blockStore);

    // Build a historical chain of version 2 blocks
    long timeSeconds = 1231006505;
    StoredBlock chainHead = null;
    for (int height = 0; height < PARAMS.getMajorityWindow(); height++) {
        chainHead = FakeTxBuilder.createFakeBlock(blockStore, 2, timeSeconds, height).storedBlock;
        assertEquals(2, chainHead.getHeader().getVersion());
        timeSeconds += 60;
    }

    VersionTally instance = new VersionTally(PARAMS);
    instance.initialize(blockStore, chainHead);
    assertEquals(PARAMS.getMajorityWindow(), instance.getCountAtOrAbove(2).intValue());
}
 
Example #3
Source File: BlockChain.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void rollbackBlockStore(int height) throws BlockStoreException {
    lock.lock();
    try {
        int currentHeight = getBestChainHeight();
        checkArgument(height >= 0 && height <= currentHeight, "Bad height: %s", height);
        if (height == currentHeight)
            return; // nothing to do

        // Look for the block we want to be the new chain head
        StoredBlock newChainHead = blockStore.getChainHead();
        while (newChainHead.getHeight() > height) {
            newChainHead = newChainHead.getPrev(blockStore);
            if (newChainHead == null)
                throw new BlockStoreException("Unreachable height");
        }

        // Modify store directly
        blockStore.put(newChainHead);
        this.setChainHead(newChainHead);
    } finally {
        lock.unlock();
    }
}
 
Example #4
Source File: VersionTally.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initialize the version tally from the block store. Note this does not
 * search backwards past the start of the block store, so if starting from
 * a checkpoint this may not fill the window.
 *
 * @param blockStore block store to load blocks from.
 * @param chainHead current chain tip.
 */
public void initialize(final BlockStore blockStore, final StoredBlock chainHead)
    throws BlockStoreException {
    StoredBlock versionBlock = chainHead;
    final Stack<Long> versions = new Stack<>();

    // We don't know how many blocks back we can go, so load what we can first
    versions.push(versionBlock.getHeader().getVersion());
    for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) {
        versionBlock = versionBlock.getPrev(blockStore);
        if (null == versionBlock) {
            break;
        }
        versions.push(versionBlock.getHeader().getVersion());
    }

    // Replay the versions into the tally
    while (!versions.isEmpty()) {
        add(versions.pop());
    }
}
 
Example #5
Source File: BlockChain.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void rollbackBlockStore(int height) throws BlockStoreException {
    lock.lock();
    try {
        int currentHeight = getBestChainHeight();
        checkArgument(height >= 0 && height <= currentHeight, "Bad height: %s", height);
        if (height == currentHeight)
            return; // nothing to do

        // Look for the block we want to be the new chain head
        StoredBlock newChainHead = blockStore.getChainHead();
        while (newChainHead.getHeight() > height) {
            newChainHead = newChainHead.getPrev(blockStore);
            if (newChainHead == null)
                throw new BlockStoreException("Unreachable height");
        }

        // Modify store directly
        blockStore.put(newChainHead);
        this.setChainHead(newChainHead);
    } finally {
        lock.unlock();
    }
}
 
Example #6
Source File: BlockChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block blockHeader)
        throws BlockStoreException, VerificationException {
    StoredBlock newBlock = storedPrev.build(blockHeader);
    blockStore.put(newBlock);
    return newBlock;
}
 
Example #7
Source File: FullPrunedBlockChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs a block chain connected to the given list of wallets and a store.
 */
public FullPrunedBlockChain(Context context, List<Wallet> listeners, FullPrunedBlockStore blockStore) throws BlockStoreException {
    super(context, listeners, blockStore);
    this.blockStore = blockStore;
    // Ignore upgrading for now
    this.chainHead = blockStore.getVerifiedChainHead();
}
 
Example #8
Source File: BlockChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block blockHeader, TransactionOutputChanges txOutChanges)
        throws BlockStoreException, VerificationException {
    StoredBlock newBlock = storedPrev.build(blockHeader);
    blockStore.put(newBlock);
    return newBlock;
}
 
Example #9
Source File: FullPrunedBlockChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block block)
        throws BlockStoreException, VerificationException {
    StoredBlock newBlock = storedPrev.build(block);
    blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), block.transactions));
    return newBlock;
}
 
Example #10
Source File: FullPrunedBlockChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block header, TransactionOutputChanges txOutChanges)
        throws BlockStoreException, VerificationException {
    StoredBlock newBlock = storedPrev.build(header);
    blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), txOutChanges));
    return newBlock;
}
 
Example #11
Source File: BlockChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block blockHeader)
        throws BlockStoreException, VerificationException {
    StoredBlock newBlock = storedPrev.build(blockHeader);
    blockStore.put(newBlock);
    return newBlock;
}
 
Example #12
Source File: FullPrunedBlockChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block block)
        throws BlockStoreException, VerificationException {
    StoredBlock newBlock = storedPrev.build(block);
    blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), block.transactions));
    return newBlock;
}
 
Example #13
Source File: BlockChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block blockHeader, TransactionOutputChanges txOutChanges)
        throws BlockStoreException, VerificationException {
    StoredBlock newBlock = storedPrev.build(blockHeader);
    blockStore.put(newBlock);
    return newBlock;
}
 
Example #14
Source File: TestNet3Params.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock,
                                       final BlockStore blockStore) throws VerificationException, BlockStoreException {
    if (!isDifficultyTransitionPoint(storedPrev.getHeight()) && nextBlock.getTime().after(testnetDiffDate)) {
        Block prev = storedPrev.getHeader();

        // After 15th February 2012 the rules on the testnet change to avoid people running up the difficulty
        // and then leaving, making it too hard to mine a block. On non-difficulty transition points, easy
        // blocks are allowed if there has been a span of 20 minutes without one.
        final long timeDelta = nextBlock.getTimeSeconds() - prev.getTimeSeconds();
        // There is an integer underflow bug in bitcoin-qt that means mindiff blocks are accepted when time
        // goes backwards.
        if (timeDelta >= 0 && timeDelta <= NetworkParameters.TARGET_SPACING * 2) {
            // Walk backwards until we find a block that doesn't have the easiest proof of work, then check
            // that difficulty is equal to that one.
            StoredBlock cursor = storedPrev;
            while (!cursor.getHeader().equals(getGenesisBlock()) &&
                    cursor.getHeight() % getInterval() != 0 &&
                    cursor.getHeader().getDifficultyTargetAsInteger().equals(getMaxTarget()))
                cursor = cursor.getPrev(blockStore);
            BigInteger cursorTarget = cursor.getHeader().getDifficultyTargetAsInteger();
            BigInteger newTarget = nextBlock.getDifficultyTargetAsInteger();
            if (!cursorTarget.equals(newTarget))
                throw new VerificationException("Testnet block transition that is not allowed: " +
                        Long.toHexString(cursor.getHeader().getDifficultyTarget()) + " vs " +
                        Long.toHexString(nextBlock.getDifficultyTarget()));
        }
    } else {
        super.checkDifficultyTransitions(storedPrev, nextBlock, blockStore);
    }
}
 
Example #15
Source File: PostgresFullPrunedBlockChainTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public FullPrunedBlockStore createStore(NetworkParameters params, int blockCount)
        throws BlockStoreException {
    if(useSchema) {
        return new PostgresFullPrunedBlockStore(params, blockCount, DB_HOSTNAME, DB_NAME, DB_USERNAME, DB_PASSWORD, DB_SCHEMA);
    }
    else {
        return new PostgresFullPrunedBlockStore(params, blockCount, DB_HOSTNAME, DB_NAME, DB_USERNAME, DB_PASSWORD);
    }
}
 
Example #16
Source File: FullPrunedBlockChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs a block chain connected to the given list of wallets and a store.
 */
public FullPrunedBlockChain(Context context, List<Wallet> listeners, FullPrunedBlockStore blockStore) throws BlockStoreException {
    super(context, listeners, blockStore);
    this.blockStore = blockStore;
    // Ignore upgrading for now
    this.chainHead = blockStore.getVerifiedChainHead();
}
 
Example #17
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Emulates receiving a valid block that builds on top of the chain.
 */
public static BlockPair createFakeBlock(BlockStore blockStore, long version, long timeSeconds, int height, Transaction... transactions) {
    try {
        return createFakeBlock(blockStore, blockStore.getChainHead(), version, timeSeconds, height, transactions);
    } catch (BlockStoreException e) {
        throw new RuntimeException(e);  // Cannot happen.
    }
}
 
Example #18
Source File: TestNet3Params.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock,
    final BlockStore blockStore) throws VerificationException, BlockStoreException {
    if (!isDifficultyTransitionPoint(storedPrev.getHeight()) && nextBlock.getTime().after(testnetDiffDate)) {
        Block prev = storedPrev.getHeader();

        // After 15th February 2012 the rules on the testnet change to avoid people running up the difficulty
        // and then leaving, making it too hard to mine a block. On non-difficulty transition points, easy
        // blocks are allowed if there has been a span of 20 minutes without one.
        final long timeDelta = nextBlock.getTimeSeconds() - prev.getTimeSeconds();
        // There is an integer underflow bug in bitcoin-qt that means mindiff blocks are accepted when time
        // goes backwards.
        if (timeDelta >= 0 && timeDelta <= NetworkParameters.TARGET_SPACING * 2) {
    	// Walk backwards until we find a block that doesn't have the easiest proof of work, then check
    	// that difficulty is equal to that one.
    	StoredBlock cursor = storedPrev;
    	while (!cursor.getHeader().equals(getGenesisBlock()) &&
                   cursor.getHeight() % getInterval() != 0 &&
                   cursor.getHeader().getDifficultyTargetAsInteger().equals(getMaxTarget()))
                cursor = cursor.getPrev(blockStore);
    	BigInteger cursorTarget = cursor.getHeader().getDifficultyTargetAsInteger();
    	BigInteger newTarget = nextBlock.getDifficultyTargetAsInteger();
    	if (!cursorTarget.equals(newTarget))
                throw new VerificationException("Testnet block transition that is not allowed: " +
            	Long.toHexString(cursor.getHeader().getDifficultyTarget()) + " vs " +
            	Long.toHexString(nextBlock.getDifficultyTarget()));
        }
    } else {
        super.checkDifficultyTransitions(storedPrev, nextBlock, blockStore);
    }
}
 
Example #19
Source File: FakeTxBuilder.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/** Emulates receiving a valid block that builds on top of the chain. */
public static BlockPair createFakeBlock(BlockStore blockStore, long version, long timeSeconds, int height, Transaction... transactions) {
    try {
        return createFakeBlock(blockStore, blockStore.getChainHead(), version, timeSeconds, height, transactions);
    } catch (BlockStoreException e) {
        throw new RuntimeException(e);  // Cannot happen.
    }
}
 
Example #20
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static Block makeSolvedTestBlock(Block prev, Address to, Transaction... transactions) throws BlockStoreException {
    Block b = prev.createNextBlock(to);
    // Coinbase tx already exists.
    for (Transaction tx : transactions) {
        b.addTransaction(tx);
    }
    b.solve();
    return b;
}
 
Example #21
Source File: PostgresFullPrunedBlockChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public FullPrunedBlockStore createStore(NetworkParameters params, int blockCount)
        throws BlockStoreException {
    if (useSchema) {
        return new PostgresFullPrunedBlockStore(params, blockCount, DB_HOSTNAME, DB_NAME, DB_USERNAME, DB_PASSWORD, DB_SCHEMA);
    } else {
        return new PostgresFullPrunedBlockStore(params, blockCount, DB_HOSTNAME, DB_NAME, DB_USERNAME, DB_PASSWORD);
    }
}
 
Example #22
Source File: LevelDBFullPrunedBlockChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public FullPrunedBlockStore createStore(NetworkParameters params,
                                        int blockCount) throws BlockStoreException {
    deleteFiles();
    return new LevelDBFullPrunedBlockStore(params, "test-leveldb",
            blockCount);
}
 
Example #23
Source File: SPV.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void stopSync() {
    synchronized (mStateLock) {
        Log.d(TAG, "stopSync: " + Var("isEnabled", isEnabled()));

        if (mPeerGroup != null && mPeerGroup.isRunning()) {
            Log.d(TAG, "Stopping peer group");
            final Intent i = new Intent("PEERGROUP_UPDATED");
            i.putExtra("peergroup", "stopSPVSync");
            mService.sendBroadcast(i);
            mPeerGroup.stop();
        }

        if (mNotifyManager != null)
            mNotifyManager.cancel(mNotificationId);

        if (mBlockChain != null) {
            Log.d(TAG, "Disposing of block chain");
            //mBlockChain.removeTransactionReceivedListener(mTxListner);
            mBlockChain = null;
        }

        if (mPeerGroup != null) {
            Log.d(TAG, "Deleting peer group");
            mPeerGroup.removePeerFilterProvider(mPeerFilter);
            mPeerGroup = null;
        }

        if (mBlockStore != null) {
            Log.d(TAG, "Closing block store");
            try {
                mBlockStore.close();
                mBlockStore = null;
            } catch (final BlockStoreException x) {
                throw new RuntimeException(x);
            }
        }
    }
}
 
Example #24
Source File: BlockChain.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void notSettingChainHead() throws BlockStoreException {
    // We don't use DB transactions here, so we don't need to do anything
}
 
Example #25
Source File: BlockChain.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void doSetChainHead(StoredBlock chainHead) throws BlockStoreException {
    blockStore.setChainHead(chainHead);
}
 
Example #26
Source File: AbstractBitcoinNetParams.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock,
	final BlockStore blockStore) throws VerificationException, BlockStoreException {
    final Block prev = storedPrev.getHeader();

    // Is this supposed to be a difficulty transition point?
    if (!isDifficultyTransitionPoint(storedPrev.getHeight())) {

        // No ... so check the difficulty didn't actually change.
        if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget())
            throw new VerificationException("Unexpected change in difficulty at height " + storedPrev.getHeight() +
                    ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs " +
                    Long.toHexString(prev.getDifficultyTarget()));
        return;
    }

    // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
    // two weeks after the initial block chain download.
    final Stopwatch watch = Stopwatch.createStarted();
    Sha256Hash hash = prev.getHash();
    StoredBlock cursor = null;
    final int interval = this.getInterval();
    for (int i = 0; i < interval; i++) {
        cursor = blockStore.get(hash);
        if (cursor == null) {
            // This should never happen. If it does, it means we are following an incorrect or busted chain.
            throw new VerificationException(
                    "Difficulty transition point but we did not find a way back to the last transition point. Not found: " + hash);
        }
        hash = cursor.getHeader().getPrevBlockHash();
    }
    checkState(cursor != null && isDifficultyTransitionPoint(cursor.getHeight() - 1),
            "Didn't arrive at a transition point.");
    watch.stop();
    if (watch.elapsed(TimeUnit.MILLISECONDS) > 50)
        log.info("Difficulty transition traversal took {}", watch);

    Block blockIntervalAgo = cursor.getHeader();
    int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds());
    // Limit the adjustment step.
    final int targetTimespan = this.getTargetTimespan();
    if (timespan < targetTimespan / 4)
        timespan = targetTimespan / 4;
    if (timespan > targetTimespan * 4)
        timespan = targetTimespan * 4;

    BigInteger newTarget = Utils.decodeCompactBits(prev.getDifficultyTarget());
    newTarget = newTarget.multiply(BigInteger.valueOf(timespan));
    newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan));

    if (newTarget.compareTo(this.getMaxTarget()) > 0) {
        log.info("Difficulty hit proof of work limit: {}", newTarget.toString(16));
        newTarget = this.getMaxTarget();
    }

    int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3;
    long receivedTargetCompact = nextBlock.getDifficultyTarget();

    // The calculated difficulty is to a higher precision than received, so reduce here.
    BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
    newTarget = newTarget.and(mask);
    long newTargetCompact = Utils.encodeCompactBits(newTarget);

    if (newTargetCompact != receivedTargetCompact)
        throw new VerificationException("Network provided difficulty bits do not match what was calculated: " +
                Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact));
}
 
Example #27
Source File: MemoryFullPrunedBlockChainTest.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void resetStore(FullPrunedBlockStore store) throws BlockStoreException {
    //No-op for memory store, because it's not persistent
}
 
Example #28
Source File: AbstractBitcoinNetParams.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock,
                                       final BlockStore blockStore) throws VerificationException, BlockStoreException {
    Block prev = storedPrev.getHeader();

    // Is this supposed to be a difficulty transition point?
    if (!isDifficultyTransitionPoint(storedPrev)) {

        // No ... so check the difficulty didn't actually change.
        if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget())
            throw new VerificationException("Unexpected change in difficulty at height " + storedPrev.getHeight() +
                    ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs " +
                    Long.toHexString(prev.getDifficultyTarget()));
        return;
    }

    // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
    // two weeks after the initial block chain download.
    final Stopwatch watch = Stopwatch.createStarted();
    StoredBlock cursor = blockStore.get(prev.getHash());
    for (int i = 0; i < this.getInterval() - 1; i++) {
        if (cursor == null) {
            // This should never happen. If it does, it means we are following an incorrect or busted chain.
            throw new VerificationException(
                    "Difficulty transition point but we did not find a way back to the genesis block.");
        }
        cursor = blockStore.get(cursor.getHeader().getPrevBlockHash());
    }
    watch.stop();
    if (watch.elapsed(TimeUnit.MILLISECONDS) > 50)
        log.info("Difficulty transition traversal took {}", watch);

    Block blockIntervalAgo = cursor.getHeader();
    int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds());
    // Limit the adjustment step.
    final int targetTimespan = this.getTargetTimespan();
    if (timespan < targetTimespan / 4)
        timespan = targetTimespan / 4;
    if (timespan > targetTimespan * 4)
        timespan = targetTimespan * 4;

    BigInteger newTarget = Utils.decodeCompactBits(prev.getDifficultyTarget());
    newTarget = newTarget.multiply(BigInteger.valueOf(timespan));
    newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan));

    if (newTarget.compareTo(this.getMaxTarget()) > 0) {
        log.info("Difficulty hit proof of work limit: {}", newTarget.toString(16));
        newTarget = this.getMaxTarget();
    }

    int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3;
    long receivedTargetCompact = nextBlock.getDifficultyTarget();

    // The calculated difficulty is to a higher precision than received, so reduce here.
    BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
    newTarget = newTarget.and(mask);
    long newTargetCompact = Utils.encodeCompactBits(newTarget);

    if (newTargetCompact != receivedTargetCompact)
        throw new VerificationException("Network provided difficulty bits do not match what was calculated: " +
                Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact));
}
 
Example #29
Source File: WalletAppSetup.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
void init(@Nullable Consumer<String> chainFileLockedExceptionHandler,
          @Nullable Consumer<String> spvFileCorruptedHandler,
          @Nullable Runnable showFirstPopupIfResyncSPVRequestedHandler,
          Runnable walletPasswordHandler,
          Runnable downloadCompleteHandler,
          Runnable walletInitializedHandler

) {
    log.info("init");

    ObjectProperty<Throwable> walletServiceException = new SimpleObjectProperty<>();
    btcInfoBinding = EasyBind.combine(walletsSetup.downloadPercentageProperty(),
            walletsSetup.numPeersProperty(),
            walletServiceException,
            (downloadPercentage, numPeers, exception) -> {
                String result;
                if (exception == null) {
                    double percentage = (double) downloadPercentage;
                    int peers = (int) numPeers;
                    getBtcSyncProgress().set(percentage);
                    if (percentage == 1) {
                        result = Res.get("mainView.footer.btcInfo",
                                peers,
                                Res.get("mainView.footer.btcInfo.synchronizedWith"),
                                getBtcNetworkAsString());
                        getBtcSplashSyncIconId().set("image-connection-synced");

                        downloadCompleteHandler.run();
                    } else if (percentage > 0.0) {
                        result = Res.get("mainView.footer.btcInfo",
                                peers,
                                Res.get("mainView.footer.btcInfo.synchronizedWith"),
                                getBtcNetworkAsString() + ": " + formatter.formatToPercentWithSymbol(percentage));
                    } else {
                        result = Res.get("mainView.footer.btcInfo",
                                peers,
                                Res.get("mainView.footer.btcInfo.connectingTo"),
                                getBtcNetworkAsString());
                    }
                } else {
                    result = Res.get("mainView.footer.btcInfo",
                            getNumBtcPeers(),
                            Res.get("mainView.footer.btcInfo.connectionFailed"),
                            getBtcNetworkAsString());
                    log.error(exception.getMessage());
                    if (exception instanceof TimeoutException) {
                        getWalletServiceErrorMsg().set(Res.get("mainView.walletServiceErrorMsg.timeout"));
                    } else if (exception.getCause() instanceof BlockStoreException) {
                        if (exception.getCause().getCause() instanceof ChainFileLockedException && chainFileLockedExceptionHandler != null) {
                            chainFileLockedExceptionHandler.accept(Res.get("popup.warning.startupFailed.twoInstances"));
                        } else if (spvFileCorruptedHandler != null) {
                            spvFileCorruptedHandler.accept(Res.get("error.spvFileCorrupted", exception.getMessage()));
                        }
                    } else {
                        getWalletServiceErrorMsg().set(Res.get("mainView.walletServiceErrorMsg.connectionError", exception.toString()));
                    }
                }
                return result;

            });
    btcInfoBinding.subscribe((observable, oldValue, newValue) -> {
        getBtcInfo().set(newValue);
    });

    walletsSetup.initialize(null,
            () -> {
                numBtcPeers = walletsSetup.numPeersProperty().get();

                // We only check one wallet as we apply encryption to all or none
                if (walletsManager.areWalletsEncrypted()) {
                    walletPasswordHandler.run();
                } else {
                    if (preferences.isResyncSpvRequested()) {
                        if (showFirstPopupIfResyncSPVRequestedHandler != null)
                            showFirstPopupIfResyncSPVRequestedHandler.run();
                    } else {
                        walletInitializedHandler.run();
                    }
                }
            },
            walletServiceException::set);
}
 
Example #30
Source File: FullPrunedBlockChain.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void doSetChainHead(StoredBlock chainHead) throws BlockStoreException {
    checkState(lock.isHeldByCurrentThread());
    blockStore.setVerifiedChainHead(chainHead);
    blockStore.commitDatabaseBatchWrite();
}