Java Code Examples for org.bitcoinj.core.Block#getHash()

The following examples show how to use org.bitcoinj.core.Block#getHash() . 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: BlockSummary.java    From jelectrum with MIT License 6 votes vote down vote up
public BlockSummary(int height, Block blk, TXUtil tx_util, Map<Sha256Hash, TransactionSummary> tx_cache)
{
  this.height = height;
  this.block_hash = blk.getHash();

  tx_map = new HashMap<>();

  for(Transaction tx : blk.getTransactions())
  {
    TransactionSummary tx_sum = new TransactionSummary(tx, tx_util, tx_cache);

    tx_map.put(tx.getHash(), tx_sum);
    synchronized(tx_cache)
    {
      tx_cache.put(tx.getHash(), tx_sum);
    }
  }
}
 
Example 3
Source File: Importer.java    From jelectrum with MIT License 6 votes vote down vote up
public void saveBlock(Block b)
{
    try
    {
      Sha256Hash hash = b.getHash();
      needed_prev_blocks.offer(b.getPrevBlockHash());
      int h = block_store.getHeight(hash);

      synchronized(in_progress)
      {
        if (!in_progress.containsKey(hash))
        {
          in_progress.put(hash, new Semaphore(0));
        }
      }

      jelly.getEventLog().log("Enqueing block: " + hash + " - " + h); 
      block_queue.put(b);
    }
    catch(java.lang.InterruptedException e)
    {
        throw new RuntimeException(e);
    }

}
 
Example 4
Source File: WalletProtobufSerializerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testLastBlockSeenHash() throws Exception {
    // Test the lastBlockSeenHash field works.

    // LastBlockSeenHash should be empty if never set.
    Wallet wallet = new Wallet(UNITTEST);
    Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(wallet);
    ByteString lastSeenBlockHash = walletProto.getLastSeenBlockHash();
    assertTrue(lastSeenBlockHash.isEmpty());

    // Create a block.
    Block block = UNITTEST.getDefaultSerializer()
            .makeBlock(ByteStreams.toByteArray(BlockTest.class.getResourceAsStream("block_testnet700000.dat")));
    Sha256Hash blockHash = block.getHash();
    wallet.setLastBlockSeenHash(blockHash);
    wallet.setLastBlockSeenHeight(1);

    // Roundtrip the wallet and check it has stored the blockHash.
    Wallet wallet1 = roundTrip(wallet);
    assertEquals(blockHash, wallet1.getLastBlockSeenHash());
    assertEquals(1, wallet1.getLastBlockSeenHeight());

    // Test the Satoshi genesis block (hash of all zeroes) is roundtripped ok.
    Block genesisBlock = MAINNET.getGenesisBlock();
    wallet.setLastBlockSeenHash(genesisBlock.getHash());
    Wallet wallet2 = roundTrip(wallet);
    assertEquals(genesisBlock.getHash(), wallet2.getLastBlockSeenHash());
}
 
Example 5
Source File: MapBlockStore.java    From jelectrum with MIT License 5 votes vote down vote up
public void put(Block b)
    throws org.bitcoinj.store.BlockStoreException
{
  Sha256Hash hash = b.getHash();
  Block header = b.cloneAsHeader();

  Sha256Hash prev = b.getPrevBlockHash();
  StoredBlock prev_sb = file_db.getBlockStoreMap().get(prev);

  StoredBlock sb = prev_sb.build(header);

  file_db.getBlockStoreMap().put(hash, sb);

  setChainHead(sb);
}
 
Example 6
Source File: MapBlockStore.java    From jelectrum with MIT License 5 votes vote down vote up
public void putAll(List<Block> blks)
    throws org.bitcoinj.store.BlockStoreException
{
  HashMap<Sha256Hash, StoredBlock> insert_map = new HashMap<>();

  StoredBlock last = null;

  for(Block b : blks)
  {
    Sha256Hash hash = b.getHash();
    Sha256Hash prev = b.getPrevBlockHash();

    if (!hash.equals(jelly.getNetworkParameters().getGenesisBlock().getHash()))
    {
      StoredBlock prev_sb = insert_map.get(prev);
      if (prev_sb == null)
      {
        prev_sb = file_db.getBlockStoreMap().get(prev);
      }
      Assert.assertNotNull(prev_sb);

      Block header = b.cloneAsHeader();
      StoredBlock sb = prev_sb.build(header);

      last = sb;

      insert_map.put(hash, sb);
    }
  }


  file_db.getBlockStoreMap().putAll(insert_map);

  if (last != null) setChainHead(last);

}
 
Example 7
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 8
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 9
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));
}