Java Code Examples for org.bitcoinj.core.StoredBlock#getHeader()

The following examples show how to use org.bitcoinj.core.StoredBlock#getHeader() . 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: WalletAppKitService.java    From consensusj with Apache License 2.0 6 votes vote down vote up
/**
 * Get a BlockInfo for the specified hash
 *
 * @param blockChain The blockchain object to pull the data from
 * @param blockHash The hash of the desired block
 * @param includeTx whether to include transactions (currently must be false)
 * @return block information (currently incomplete and untested)
 * @throws BlockStoreException Something went wrong
 */
private static BlockInfo getBlockInfoByHash(AbstractBlockChain blockChain, Sha256Hash blockHash, BlockInfo.IncludeTxFlag includeTx) throws BlockStoreException {
    if (includeTx == BlockInfo.IncludeTxFlag.YES) {
        throw new IllegalArgumentException("Including transactions not supported yet");
    }
    StoredBlock block = getStoredBlockByHash(blockChain, blockHash);
    Block header = block.getHeader();
    int blockHeight = block.getHeight();
    int confirmations = blockChain.getBestChainHeight() - blockHeight;
    log.trace("building BlockInfo for hash: {} height: {}", blockHash, blockHeight);
    return new BlockInfo(header.getHash(),
            confirmations,
            header.getMessageSize(),
            blockHeight,
            (int) header.getVersion(),
            header.getMerkleRoot(),
            -1,     // Unknown number of Transactions
            (includeTx == BlockInfo.IncludeTxFlag.IDONLY) ? hashListFromTxList(header.getTransactions()) : null,
            (int) header.getTimeSeconds(),
            header.getNonce(),
            null, // TODO: Return "bits" here
            new BigDecimal(header.getDifficultyTargetAsInteger()),  // TODO: Verify this is correct
            block.getChainWork().toString(),
            block.getPrev(blockChain.getBlockStore()).getHeader().getHash(),
            null);  // TODO: Extend BlockStore to make this information retrievable
}
 
Example 2
Source File: ElectrumNotifier.java    From jelectrum with MIT License 6 votes vote down vote up
public void populateBlockData(StoredBlock blk, JSONObject block_data)
    throws org.json.JSONException
{
    Block header = blk.getHeader();
    block_data.put("nonce", header.getNonce());
    block_data.put("prev_block_hash", header.getPrevBlockHash().toString());
    block_data.put("timestamp", header.getTimeSeconds());
    block_data.put("merkle_root", header.getMerkleRoot().toString());
    block_data.put("block_height", blk.getHeight());
    block_data.put("version",header.getVersion());
    block_data.put("bits", header.getDifficultyTarget());
    block_data.put("height", blk.getHeight());
    block_data.put("hex", Util.getHeaderHex(header));
    //block_data.put("utxo_root", jelly.getUtxoTrieMgr().getRootHash(header.getHash()));



}
 
Example 3
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 4
Source File: AbstractBitcoinNetParams.java    From bcm-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 5
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 6
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 7
Source File: AbstractBitcoinNetParams.java    From GreenBits 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));
}