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

The following examples show how to use org.bitcoinj.core.StoredBlock#getPrev() . 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: VersionTally.java    From bcm-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 2
Source File: SPVBlockStoreTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void twoStores_sequentially_grow() throws Exception {
    Address to = LegacyAddress.fromKey(UNITTEST, new ECKey());
    SPVBlockStore store = new SPVBlockStore(UNITTEST, blockStoreFile, 10, true);
    final StoredBlock block0 = store.getChainHead();
    final StoredBlock block1 = block0.build(block0.getHeader().createNextBlock(to).cloneAsHeader());
    store.put(block1);
    final StoredBlock block2 = block1.build(block1.getHeader().createNextBlock(to).cloneAsHeader());
    store.put(block2);
    store.setChainHead(block2);
    store.close();

    store = new SPVBlockStore(UNITTEST, blockStoreFile, 20, true);
    final StoredBlock read2 = store.getChainHead();
    assertEquals(block2, read2);
    final StoredBlock read1 = read2.getPrev(store);
    assertEquals(block1, read1);
    final StoredBlock read0 = read1.getPrev(store);
    assertEquals(block0, read0);
    store.close();
    assertEquals(SPVBlockStore.getFileSize(20), blockStoreFile.length());
}
 
Example 3
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 4
Source File: VersionTally.java    From GreenBits 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: MapBlockStore.java    From jelectrum with MIT License 6 votes vote down vote up
public StoredBlock getChainHead()
    throws org.bitcoinj.store.BlockStoreException
{
    StoredBlock head_blk =  file_db.getSpecialBlockStoreMap().get("head");


    StoredBlock curr = head_blk;
    int stepback=0;
    if (file_db.getBlockSavedMap()==null) throw new RuntimeException("BlockMap is null");

    while((!file_db.getBlockSavedMap().containsKey(curr.getHeader().getHash())) && (curr.getHeight()>=1))
    {   
        int step_size=10;
        if (curr.getHeight() < 1000) step_size=1;
        for(int i=0; i<step_size; i++)
        {
            stepback++;
            curr = curr.getPrev(this);
        }
    }
    setChainHead(curr);
    jelly.getEventLog().alarm("Current Head: " + curr.getHeader().getHash().toString() + " - " + curr.getHeight() + " stepback " + stepback);
    return curr;
}
 
Example 6
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 7
Source File: BlockChainCache.java    From jelectrum with MIT License 5 votes vote down vote up
public void undumbSelf(NetworkParameters params, BlockStore block_store)
  throws org.bitcoinj.store.BlockStoreException
{
  Sha256Hash genesis_hash = params.getGenesisBlock().getHash();
  StoredBlock cur = block_store.get(head);
  synchronized(update_lock)
  {
    while(true)
    {
      int height = cur.getHeight();

      if (!height_map.containsKey(height))
      {
        System.out.println("Height map missing: " + height);
        height_map.put(height, cur.getHeader().getHash());
      }
      if (main_chain.contains(cur.getHeader().getHash()))
      {
        System.out.println("Main chain missing: " + height);
        main_chain.add(cur.getHeader().getHash());
      }
      
      if (cur.getHeader().getHash().equals(genesis_hash)) return;
      
      cur = cur.getPrev(block_store);

    }


  }

}
 
Example 8
Source File: BlockChainCache.java    From jelectrum with MIT License 4 votes vote down vote up
public void update(Jelectrum jelly, StoredBlock new_head)
    throws org.bitcoinj.store.BlockStoreException
{
    System.out.println("chain update, new head: " + new_head.getHeader().getHash() + " - " + new_head.getHeight());

    if (new_head.getHeader().getHash().equals(head)) return;

    Sha256Hash genesis_hash = jelly.getNetworkParameters().getGenesisBlock().getHash();

    synchronized(update_lock)
    {
        StoredBlock blk = new_head;

        while(true)
        {
            synchronized(this)
            {
                int height = blk.getHeight();
                Sha256Hash old = height_map.put(height, blk.getHeader().getHash());
                if ((old!=null) && (old.equals(blk.getHeader().getHash())))
                {
                    break;
                }
                if (old!=null)
                {
                    main_chain.remove(old);
                }
                main_chain.add(blk.getHeader().getHash());
                updates++;

            }
            if (blk.getHeader().getHash().equals(genesis_hash)) break;
            blk = blk.getPrev(jelly.getBlockStore());
        }

        head = new_head.getHeader().getHash();
        if (updates >= UPDATES_BEFORE_SAVE)
        {
            updates=0;
            save(jelly);
        }
    }
}
 
Example 9
Source File: BlockChainCache.java    From jelectrum with MIT License 4 votes vote down vote up
public void update(Jelectrum jelly, StoredBlock new_head)
    throws org.bitcoinj.store.BlockStoreException
{
  last_head = new_head.getHeader().getHash();
  //event_log.log("BlockChainCache: chain update, new head: " + new_head.getHeader().getHash() + " - " + new_head.getHeight());

  Sha256Hash genesis_hash = jelly.getNetworkParameters().getGenesisBlock().getHash();

  StoredBlock cur = new_head;

  TreeMap<Integer, Sha256Hash> to_write = new TreeMap<>();

  int reorg=0;

  while(true)
  {
    int height = cur.getHeight();
    Sha256Hash curr_hash = cur.getHeader().getHash();

    Sha256Hash exist_hash = getBlockHashAtHeight(height);
    if ((exist_hash != null) && (!exist_hash.equals(curr_hash)))
    {
      reorg++;
    }

    if (curr_hash.equals(exist_hash)) break;

    to_write.put(height, curr_hash);
    if (curr_hash.equals(genesis_hash)) break;

    cur = cur.getPrev(store);

  }
  if (to_write.size() > 1)
  {
    event_log.log("BlockChainCache: adding " + to_write.size() + " to height map");
  }

  /**
   * Write them out in order to make sure this is recoverable if interupted in the middle
   */
  for(Map.Entry<Integer, Sha256Hash> me : to_write.entrySet())
  {
    height_map.put(me.getKey(), me.getValue());
  }
  if (reorg > 0)
  {
    event_log.alarm("BlockChainCache: re-org of " + reorg + " blocks found");
  }

}