Java Code Examples for org.bitcoinj.core.StoredBlock#getHeight()
The following examples show how to use
org.bitcoinj.core.StoredBlock#getHeight() .
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 |
/** * 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: MapBlockStore.java From jelectrum with MIT License | 6 votes |
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 3
Source File: TestNet3Params.java From bcm-android with GNU General Public License v3.0 | 5 votes |
@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: LevelDBFullPrunedBlockStore.java From bcm-android with GNU General Public License v3.0 | 5 votes |
@Override public void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException { if (instrument) beginMethod("setVerifiedChainHead"); Sha256Hash hash = chainHead.getHeader().getHash(); this.verifiedChainHeadHash = hash; this.verifiedChainHeadBlock = chainHead; batchPut(getKey(KeyType.VERIFIED_CHAIN_HEAD_SETTING), hash.getBytes()); if (this.chainHeadBlock.getHeight() < chainHead.getHeight()) setChainHead(chainHead); removeUndoableBlocksWhereHeightIsLessThan(chainHead.getHeight() - fullStoreDepth); if (instrument) endMethod("setVerifiedChainHead"); }
Example 5
Source File: LevelDBFullPrunedBlockStore.java From green_android with GNU General Public License v3.0 | 5 votes |
@Override public void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException { if (instrument) beginMethod("setVerifiedChainHead"); Sha256Hash hash = chainHead.getHeader().getHash(); this.verifiedChainHeadHash = hash; this.verifiedChainHeadBlock = chainHead; batchPut(getKey(KeyType.VERIFIED_CHAIN_HEAD_SETTING), hash.getBytes()); if (this.chainHeadBlock.getHeight() < chainHead.getHeight()) setChainHead(chainHead); removeUndoableBlocksWhereHeightIsLessThan(chainHead.getHeight() - fullStoreDepth); if (instrument) endMethod("setVerifiedChainHead"); }
Example 6
Source File: HeadersStore.java From java-stratum with Apache License 2.0 | 5 votes |
public void truncate(StoredBlock checkpoint) { int index = checkpoint.getHeight(); lock.lock(); try { Block block = get(index); if (block == null) channel.write(ByteBuffer.wrap(checkpoint.getHeader().cloneAsHeader().bitcoinSerialize()), index * HEADER_SIZE); channel.truncate((index + 1) * HEADER_SIZE); } catch (IOException e) { propagate(e); } finally { lock.unlock(); } }
Example 7
Source File: LevelDBFullPrunedBlockStore.java From GreenBits with GNU General Public License v3.0 | 5 votes |
@Override public void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException { if (instrument) beginMethod("setVerifiedChainHead"); Sha256Hash hash = chainHead.getHeader().getHash(); this.verifiedChainHeadHash = hash; this.verifiedChainHeadBlock = chainHead; batchPut(getKey(KeyType.VERIFIED_CHAIN_HEAD_SETTING), hash.getBytes()); if (this.chainHeadBlock.getHeight() < chainHead.getHeight()) setChainHead(chainHead); removeUndoableBlocksWhereHeightIsLessThan(chainHead.getHeight() - fullStoreDepth); if (instrument) endMethod("setVerifiedChainHead"); }
Example 8
Source File: BlockChainCache.java From jelectrum with MIT License | 5 votes |
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 9
Source File: BlockChainCache.java From jelectrum with MIT License | 5 votes |
public boolean isBlockInMainChain(Sha256Hash hash) { try { StoredBlock sb = store.get(hash); int h = sb.getHeight(); return (hash.equals(getBlockHashAtHeight(h))); } catch(org.bitcoinj.store.BlockStoreException e) { throw new RuntimeException(e); } }
Example 10
Source File: AbstractBitcoinNetParams.java From bcm-android with GNU General Public License v3.0 | 4 votes |
@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 11
Source File: AbstractBitcoinNetParams.java From bisq-core with GNU Affero General Public License v3.0 | 4 votes |
@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 12
Source File: AbstractBitcoinNetParams.java From green_android with GNU General Public License v3.0 | 4 votes |
@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 13
Source File: AbstractBitcoinNetParams.java From GreenBits with GNU General Public License v3.0 | 4 votes |
@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 14
Source File: BlockChainCache.java From jelectrum with MIT License | 4 votes |
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 15
Source File: BlockChainCache.java From jelectrum with MIT License | 4 votes |
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"); } }
Example 16
Source File: AbstractBitcoinNetParams.java From bisq-core with GNU Affero General Public License v3.0 | 2 votes |
/** * Checks if we are at a difficulty transition point. * * @param storedPrev The previous stored block * @return If this is a difficulty transition point */ protected boolean isDifficultyTransitionPoint(StoredBlock storedPrev) { return ((storedPrev.getHeight() + 1) % this.getInterval()) == 0; }