org.bitcoinj.store.BlockStore Java Examples

The following examples show how to use org.bitcoinj.store.BlockStore. 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: 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: FetchBlock.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();
    System.out.println("Connecting to node");
    final NetworkParameters params = TestNet3Params.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.start();
    PeerAddress addr = new PeerAddress(params, InetAddress.getLocalHost());
    peerGroup.addAddress(addr);
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash blockHash = Sha256Hash.wrap(args[0]);
    Future<Block> future = peer.getBlock(blockHash);
    System.out.println("Waiting for node to send us the requested block: " + blockHash);
    Block block = future.get();
    System.out.println(block);
    peerGroup.stopAsync();
}
 
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: 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 #6
Source File: VersionTallyTest.java    From bcm-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(UNITTEST);
    final BlockChain chain = new BlockChain(UNITTEST, blockStore);

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

    VersionTally instance = new VersionTally(UNITTEST);
    instance.initialize(blockStore, chainHead);
    assertEquals(UNITTEST.getMajorityWindow(), instance.getCountAtOrAbove(2).intValue());
}
 
Example #7
Source File: VersionTallyTest.java    From GreenBits 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 #8
Source File: FetchBlock.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();
    System.out.println("Connecting to node");
    final NetworkParameters params = TestNet3Params.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.start();
    PeerAddress addr = new PeerAddress(params, InetAddress.getLocalHost());
    peerGroup.addAddress(addr);
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash blockHash = Sha256Hash.wrap(args[0]);
    Future<Block> future = peer.getBlock(blockHash);
    System.out.println("Waiting for node to send us the requested block: " + blockHash);
    Block block = future.get();
    System.out.println(block);
    peerGroup.stopAsync();
}
 
Example #9
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 #10
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 #11
Source File: FakeTxBuilder.java    From GreenBits 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 #12
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 #13
Source File: BlockChainTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void testDeprecatedBlockVersion(final long deprecatedVersion, final long newVersion)
        throws Exception {
    final BlockStore versionBlockStore = new MemoryBlockStore(PARAMS);
    final BlockChain versionChain = new BlockChain(PARAMS, versionBlockStore);

    // Build a historical chain of version 3 blocks
    long timeSeconds = 1231006505;
    int height = 0;
    FakeTxBuilder.BlockPair chainHead = null;

    // Put in just enough v2 blocks to be a minority
    for (height = 0; height < (PARAMS.getMajorityWindow() - PARAMS.getMajorityRejectBlockOutdated()); height++) {
        chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, deprecatedVersion, timeSeconds, height);
        versionChain.add(chainHead.block);
        timeSeconds += 60;
    }
    // Fill the rest of the window with v3 blocks
    for (; height < PARAMS.getMajorityWindow(); height++) {
        chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, newVersion, timeSeconds, height);
        versionChain.add(chainHead.block);
        timeSeconds += 60;
    }

    chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, deprecatedVersion, timeSeconds, height);
    // Trying to add a new v2 block should result in rejection
    thrown.expect(VerificationException.BlockVersionOutOfDate.class);
    try {
        versionChain.add(chainHead.block);
    } catch(final VerificationException ex) {
        throw (Exception) ex.getCause();
    }
}
 
Example #14
Source File: BlockChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void testDeprecatedBlockVersion(final long deprecatedVersion, final long newVersion)
        throws Exception {
    final BlockStore versionBlockStore = new MemoryBlockStore(UNITTEST);
    final BlockChain versionChain = new BlockChain(UNITTEST, versionBlockStore);

    // Build a historical chain of version 3 blocks
    long timeSeconds = 1231006505;
    int height = 0;
    FakeTxBuilder.BlockPair chainHead = null;

    // Put in just enough v2 blocks to be a minority
    for (height = 0; height < (UNITTEST.getMajorityWindow() - UNITTEST.getMajorityRejectBlockOutdated()); height++) {
        chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, deprecatedVersion, timeSeconds, height);
        versionChain.add(chainHead.block);
        timeSeconds += 60;
    }
    // Fill the rest of the window with v3 blocks
    for (; height < UNITTEST.getMajorityWindow(); height++) {
        chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, newVersion, timeSeconds, height);
        versionChain.add(chainHead.block);
        timeSeconds += 60;
    }

    chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, deprecatedVersion, timeSeconds, height);
    // Trying to add a new v2 block should result in rejection
    thrown.expect(VerificationException.BlockVersionOutOfDate.class);
    try {
        versionChain.add(chainHead.block);
    } catch (final VerificationException ex) {
        throw (Exception) ex.getCause();
    }
}
 
Example #15
Source File: RefreshWallet.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    File file = new File(args[0]);
    Wallet wallet = Wallet.loadFromFile(file);
    System.out.println(wallet.toString());

    // Set up the components and link them together.
    final NetworkParameters params = TestNet3Params.get();
    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, wallet, blockStore);

    final PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.startAsync();

    wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
        @Override
        public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
            System.out.println("\nReceived tx " + tx.getHashAsString());
            System.out.println(tx.toString());
        }
    });

    // Now download and process the block chain.
    peerGroup.downloadBlockChain();
    peerGroup.stopAsync();
    wallet.saveToFile(file);
    System.out.println("\nDone!\n");
    System.out.println(wallet.toString());
}
 
Example #16
Source File: FetchTransactions.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();
    System.out.println("Connecting to node");
    final NetworkParameters params = TestNet3Params.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.start();
    peerGroup.addAddress(new PeerAddress(params, InetAddress.getLocalHost()));
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash txHash = Sha256Hash.wrap(args[0]);
    ListenableFuture<Transaction> future = peer.getPeerMempoolTransaction(txHash);
    System.out.println("Waiting for node to send us the requested transaction: " + txHash);
    Transaction tx = future.get();
    System.out.println(tx);

    System.out.println("Waiting for node to send us the dependencies ...");
    List<Transaction> deps = peer.downloadDependencies(tx).get();
    for (Transaction dep : deps) {
        System.out.println("Got dependency " + dep.getHashAsString());
    }

    System.out.println("Done.");
    peerGroup.stop();
}
 
Example #17
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 #18
Source File: TestNet3Params.java    From GreenBits 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: FetchTransactions.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();
    System.out.println("Connecting to node");
    final NetworkParameters params = TestNet3Params.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.start();
    peerGroup.addAddress(new PeerAddress(params, InetAddress.getLocalHost()));
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash txHash = Sha256Hash.wrap(args[0]);
    ListenableFuture<Transaction> future = peer.getPeerMempoolTransaction(txHash);
    System.out.println("Waiting for node to send us the requested transaction: " + txHash);
    Transaction tx = future.get();
    System.out.println(tx);

    System.out.println("Waiting for node to send us the dependencies ...");
    List<Transaction> deps = peer.downloadDependencies(tx).get();
    for (Transaction dep : deps) {
        System.out.println("Got dependency " + dep.getHashAsString());
    }

    System.out.println("Done.");
    peerGroup.stop();
}
 
Example #20
Source File: RefreshWallet.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    File file = new File(args[0]);
    Wallet wallet = Wallet.loadFromFile(file);
    System.out.println(wallet.toString());

    // Set up the components and link them together.
    final NetworkParameters params = TestNet3Params.get();
    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, wallet, blockStore);

    final PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.startAsync();

    wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
        @Override
        public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
            System.out.println("\nReceived tx " + tx.getHashAsString());
            System.out.println(tx.toString());
        }
    });

    // Now download and process the block chain.
    peerGroup.downloadBlockChain();
    peerGroup.stopAsync();
    wallet.saveToFile(file);
    System.out.println("\nDone!\n");
    System.out.println(wallet.toString());
}
 
Example #21
Source File: BlockChainTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void testDeprecatedBlockVersion(final long deprecatedVersion, final long newVersion)
        throws Exception {
    final BlockStore versionBlockStore = new MemoryBlockStore(PARAMS);
    final BlockChain versionChain = new BlockChain(PARAMS, versionBlockStore);

    // Build a historical chain of version 3 blocks
    long timeSeconds = 1231006505;
    int height = 0;
    FakeTxBuilder.BlockPair chainHead = null;

    // Put in just enough v2 blocks to be a minority
    for (height = 0; height < (PARAMS.getMajorityWindow() - PARAMS.getMajorityRejectBlockOutdated()); height++) {
        chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, deprecatedVersion, timeSeconds, height);
        versionChain.add(chainHead.block);
        timeSeconds += 60;
    }
    // Fill the rest of the window with v3 blocks
    for (; height < PARAMS.getMajorityWindow(); height++) {
        chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, newVersion, timeSeconds, height);
        versionChain.add(chainHead.block);
        timeSeconds += 60;
    }

    chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, deprecatedVersion, timeSeconds, height);
    // Trying to add a new v2 block should result in rejection
    thrown.expect(VerificationException.BlockVersionOutOfDate.class);
    try {
        versionChain.add(chainHead.block);
    } catch(final VerificationException ex) {
        throw (Exception) ex.getCause();
    }
}
 
Example #22
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 #23
Source File: WalletConfig.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public BlockStore store() {
    checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
    return vStore;
}
 
Example #24
Source File: BlockChainCache.java    From jelectrum with MIT License 4 votes vote down vote up
public BlockChainCache(BlockStore store, Map<Integer, Sha256Hash> height_map, EventLog event_log)
{
  this.store = store;
  this.height_map = height_map;
  this.event_log = event_log;
}
 
Example #25
Source File: BlockMadScan.java    From jelectrum with MIT License 4 votes vote down vote up
public BlockMadScan(Config config)
    throws Exception
{
    jelly = new Jelectrum(config);

    tx_util = jelly.getDB().getTXUtil();
    queue = new LinkedBlockingQueue<Sha256Hash>();
    sem = new Semaphore(0);
    blocks_scanned = new AtomicInteger(0);
    transactions_scanned = new AtomicInteger(0);
    addr_to_tx_cache = new LRUCache<String, Set<Sha256Hash> >(250000);


    BlockStore block_store = jelly.getBlockStore();

    //StoredBlock head = block_store.getChainHead();

    //StoredBlock curr_block = head;

    //Sha256Hash genisis_hash = jelly.getNetworkParameters().getGenesisBlock().getHash();
    int queued=0;

    new RateThread("1-minute", 60000L).start();
    new RateThread("5-minute", 60000L * 5L).start();
    new RateThread("1-hour", 60000L * 60L).start();

    for(int i=0; i<500; i++)
    {
        new WorkerThread().start();
    }

    int h =0;
    while(true)
    {
        Sha256Hash curr_hash = jelly.getBlockChainCache().getBlockHashAtHeight(h);
        if (curr_hash == null) break;
        queue.put(curr_hash);
        queued++;
        h++;
        
        if  (h % 10000 == 0)
        {
            System.out.println("Block: " + h);

        }
    }

    /*while(true)
    {
        Sha256Hash curr_hash = curr_block.getHeader().getHash();
        queue.put(curr_hash);

        if  (curr_block.getHeight() % 10000 == 0)
        {
            System.out.println("Block: " + curr_block.getHeight());
        }
        queued++;

        if (curr_hash.equals(genisis_hash)) break;

        curr_block = curr_block.getPrev(block_store);

    }*/
    System.out.println("Enqueued " + queued + " blocks");

    while(queued>0)
    {
        sem.acquire();
        queued--;
        if (queued % 1000 == 0) System.out.println("" + queued + " blocks left");
    }





}
 
Example #26
Source File: BlockRewrite.java    From jelectrum with MIT License 4 votes vote down vote up
public BlockRewrite(Config config)
    throws Exception
{
    jelly = new Jelectrum(config);
    queue = new LinkedBlockingQueue<Sha256Hash>();
    sem = new Semaphore(0);
    blocks_scanned = new AtomicInteger(0);
    transactions_scanned = new AtomicInteger(0);

    BlockStore block_store = jelly.getBlockStore();

    //StoredBlock head = block_store.getChainHead();

    //StoredBlock curr_block = head;

    //Sha256Hash genisis_hash = jelly.getNetworkParameters().getGenesisBlock().getHash();
    int queued=0;

    new RateThread("1-minute", 60000L).start();
    new RateThread("5-minute", 60000L * 5L).start();
    new RateThread("1-hour", 60000L * 60L).start();

    for(int i=0; i<500; i++)
    {
        new WorkerThread().start();
    }

    int h =0;
    while(true)
    {
        Sha256Hash curr_hash = jelly.getBlockChainCache().getBlockHashAtHeight(h);
        if (curr_hash == null) break;
        queue.put(curr_hash);
        queued++;
        h++;
        
        if  (h % 10000 == 0)
        {
            System.out.println("Block: " + h);

        }
    }

    /*while(true)
    {
        Sha256Hash curr_hash = curr_block.getHeader().getHash();
        queue.put(curr_hash);

        if  (curr_block.getHeight() % 10000 == 0)
        {
            System.out.println("Block: " + curr_block.getHeight());
        }
        queued++;

        if (curr_hash.equals(genisis_hash)) break;

        curr_block = curr_block.getPrev(block_store);

    }*/
    System.out.println("Enqueued " + queued + " blocks");

    while(queued>0)
    {
        sem.acquire();
        queued--;
        if (queued % 1000 == 0) System.out.println("" + queued + " blocks left");
    }





}
 
Example #27
Source File: FakeTxBuilder.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
/** Emulates receiving a valid block that builds on top of the chain. */
public static BlockPair createFakeBlock(BlockStore blockStore, Transaction... transactions) {
    return createFakeBlock(blockStore, Block.BLOCK_VERSION_GENESIS, Utils.currentTimeSeconds(), 0, transactions);
}
 
Example #28
Source File: FakeTxBuilder.java    From GreenBits with GNU General Public License v3.0 4 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, Transaction... transactions) {
    return createFakeBlock(blockStore, version, timeSeconds, 0, transactions);
}
 
Example #29
Source File: FakeTxBuilder.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
/** Emulates receiving a valid block that builds on top of the chain. */
public static BlockPair createFakeBlock(BlockStore blockStore, int height,
                                        Transaction... transactions) {
    return createFakeBlock(blockStore, Block.BLOCK_VERSION_GENESIS, Utils.currentTimeSeconds(), height, transactions);
}
 
Example #30
Source File: FakeTxBuilder.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public static Block makeSolvedTestBlock(BlockStore blockStore, Address coinsTo) throws BlockStoreException {
    Block b = blockStore.getChainHead().getHeader().createNextBlock(coinsTo);
    b.solve();
    return b;
}