org.bitcoinj.core.Block Java Examples

The following examples show how to use org.bitcoinj.core.Block. 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: 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 #2
Source File: HeadersStore.java    From java-stratum with Apache License 2.0 6 votes vote down vote up
public boolean add(Block block) {
    checkState(block.getTransactions() == null);
    lock.lock();
    try {
        if (!block.getPrevBlockHash().equals(top().getHash())) {
            log.error("block.prev = {}, but expecting {}@{}", block.getPrevBlockHash(), top().getHash(), getHeight());
            return false;
        }
        channel.write(ByteBuffer.wrap(block.bitcoinSerialize()), channel.size());
        return true;
    } catch (Exception e) {
        throw propagate(e);
    } finally {
        lock.unlock();
    }
}
 
Example #3
Source File: MerkleTest.java    From jelectrum with MIT License 6 votes vote down vote up
@Test
public void bigMerkleFirst()
    throws Exception
{
    Sha256Hash block_hash = new Sha256Hash("000000000000000083d9b2fcc1d14e53c97604648e4610091ba5f9eb4d1b930b");

    Block blk = jelly.getDB().getBlock(block_hash).getBlock(jelly.getNetworkParameters());

    JSONObject result = Util.getMerkleTreeForTransaction(blk.getTransactions(), new Sha256Hash("5672d9a9055237c3801ad03af38b75216e23f2f977fe1b38616046d87b6c4c5e"));
    JSONArray merk = result.getJSONArray("merkle");

    Assert.assertEquals(0, result.getInt("pos"));
    Assert.assertEquals(10, merk.length());
    Assert.assertEquals("e958da99798f1edb0455334d1eba8cb924d0192ff5eebd759ae932492e7eb616",merk.getString(5));
    Assert.assertEquals("34325213ee37ae23a5266de8f812de5f13cda4deceb81601783811f858ae201b",merk.getString(9));

    System.out.println(result);

}
 
Example #4
Source File: HeadersStore.java    From java-stratum with Apache License 2.0 6 votes vote down vote up
/**
 * Get the block at height index.
 *
 * Returns null if we didn't see the block yet, or if we started at a checkpoint after the block.
 */
public Block get(long index) {
    lock.lock();
    try {
        if (channel.size() < (index+1) * HEADER_SIZE)
            return null;
        ByteBuffer b = ByteBuffer.allocate((int)HEADER_SIZE);
        int n = channel.read(b, index * HEADER_SIZE);
        if (n == 0) return null;
        if (n != HEADER_SIZE)
            throw new RuntimeException("partial read from store file");
        if (Arrays.equals(b.array(), EMPTY))
            return null;
        return new Block(params, b.array());
    } catch (IOException e) {
        throw propagate(e);
    } finally {
        lock.unlock();
    }
}
 
Example #5
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 #6
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 #7
Source File: LittleDB.java    From jelectrum with MIT License 6 votes vote down vote up
@Override
public void addBlockThings(int height, Block b)
{ 
  //System.out.println("Adding block " + height + " " + b.getHash());

  //Make my own copy, which is needed for working in a single block (from importer)
  HashMap<Sha256Hash, TransactionSummary> import_block_cache = new HashMap<Sha256Hash, TransactionSummary>();

  BlockSummary block_summary = new BlockSummary(height, b, tx_util, import_block_cache);

  // Put everything in the shared cache for other threads, which hit it in getTransactionSummary below
  synchronized(import_tx_summary_cache)
  {
    import_tx_summary_cache.putAll(import_block_cache);
  }

  getBlockSummaryMap().put(b.getHash(), block_summary);
  
  long t1=System.nanoTime();
  cake.addAddresses(height, block_summary.getAllAddresses());
  TimeRecord.record(t1, "cake_add_addresses");

}
 
Example #8
Source File: DownloadProgressTracker.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
    if (caughtUp)
        return;

    if (blocksLeft == 0) {
        caughtUp = true;
        doneDownload();
        future.set(peer.getBestHeight());
    }

    if (blocksLeft < 0 || originalBlocksLeft <= 0)
        return;

    double pct = 100.0 - (100.0 * (blocksLeft / (double) originalBlocksLeft));
    if ((int) pct != lastPercent) {
        progress(pct, blocksLeft, new Date(block.getTimeSeconds() * 1000));
        lastPercent = (int) pct;
    }
}
 
Example #9
Source File: MerkleTest.java    From jelectrum with MIT License 6 votes vote down vote up
@Test
public void bigMerkleLast()
    throws Exception
{
    Sha256Hash block_hash = new Sha256Hash("000000000000000083d9b2fcc1d14e53c97604648e4610091ba5f9eb4d1b930b");

    Block blk = jelly.getDB().getBlock(block_hash).getBlock(jelly.getNetworkParameters());

    JSONObject result = Util.getMerkleTreeForTransaction(blk.getTransactions(), new Sha256Hash("32bb3d77f14a69e9998af9e6d60a2b4fa9c2bb0022f271928d01bfe7e4720b69"));
    JSONArray merk = result.getJSONArray("merkle");

    Assert.assertEquals(978, result.getInt("pos"));
    Assert.assertEquals(10, merk.length());
    Assert.assertEquals("6c915f47db641cefdcd379230ad52cb428780a01fe7ce59e25b28607e67d428e",merk.getString(9));

    System.out.println(result);

}
 
Example #10
Source File: TXUtil.java    From jelectrum with MIT License 6 votes vote down vote up
public void saveTxCache(Block block)
{

HashMap<Sha256Hash, Transaction> m = new HashMap<>(512, 0.5f);

for(Transaction tx : block.getTransactions())
{
	m.put(tx.getHash(), SerializedTransaction.scrubTransaction(params,tx));
}

synchronized(tx_cache_lock)
{
  	if (transaction_cache == null)
  	{
    	transaction_cache = new LRUCache<Sha256Hash, Transaction>(TX_CACHE_SIZE);
  	}
  	transaction_cache.putAll(m);
}
}
 
Example #11
Source File: ScriptHashTest.java    From jelectrum with MIT License 6 votes vote down vote up
private void testBlock(String block_id)
  throws Exception
{
  
  SerializedBlock sblock = jelly.getDB().getBlock(Sha256Hash.wrap(block_id));
  Block block = sblock.getBlock(jelly.getNetworkParameters());

  tx_util.saveTxCache(block);

  for(Transaction tx : block.getTransactions())
  {
    if (!tx.isCoinBase())
    {
      testTransaction(tx.getTxId().toString());
    }
  }

}
 
Example #12
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 #13
Source File: DownloadProgressTracker.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
    if (caughtUp)
        return;

    if (blocksLeft == 0) {
        caughtUp = true;
        if (lastPercent != 100) {
            lastPercent = 100;
            progress(lastPercent, blocksLeft, new Date(block.getTimeSeconds() * 1000));
        }
        doneDownload();
        future.set(peer.getBestHeight());
        return;
    }

    if (blocksLeft < 0 || originalBlocksLeft <= 0)
        return;

    double pct = 100.0 - (100.0 * (blocksLeft / (double) originalBlocksLeft));
    if ((int) pct != lastPercent) {
        progress(pct, blocksLeft, new Date(block.getTimeSeconds() * 1000));
        lastPercent = (int) pct;
    }
}
 
Example #14
Source File: NetworkParameters.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private static Block createGenesis(NetworkParameters n) {
    Block genesisBlock = new Block(n, Block.BLOCK_VERSION_GENESIS);
    Transaction t = new Transaction(n);
    try {
        // A script containing the difficulty bits and the following message:
        //
        //   "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"
        byte[] bytes = Utils.HEX.decode
                ("04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73");
        t.addInput(new TransactionInput(n, t, bytes));
        ByteArrayOutputStream scriptPubKeyBytes = new ByteArrayOutputStream();
        Script.writeBytes(scriptPubKeyBytes, Utils.HEX.decode
                ("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"));
        scriptPubKeyBytes.write(ScriptOpCodes.OP_CHECKSIG);
        t.addOutput(new TransactionOutput(n, t, FIFTY_COINS, scriptPubKeyBytes.toByteArray()));
    } catch (Exception e) {
        // Cannot happen.
        throw new RuntimeException(e);
    }
    genesisBlock.addTransaction(t);
    return genesisBlock;
}
 
Example #15
Source File: BlockDownloadThread.java    From jelectrum with MIT License 6 votes vote down vote up
private void downloadBlock(int height)
  throws Exception
{
  Sha256Hash hash = null;
  try
  {
    hash = jelly.getBitcoinRPC().getBlockHash(height);

    if (downloaded.contains(hash)) return;

    SerializedBlock block = jelly.getBitcoinRPC().getBlock(hash);
    Block b = block.getBlock(jelly.getNetworkParameters());

    jelly.getBlockStore().put(b);


    jelly.getImporter().saveBlock(b);
    downloaded.add(hash);
  }
  catch(Exception e)
  {
    jelly.getEventLog().alarm(String.format("Error in download of block %d (%s) - %s", height, hash, e.toString()));
    throw e;
  }
}
 
Example #16
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void lastBlockSeen() throws Exception {
    Coin v1 = valueOf(5, 0);
    Coin v2 = valueOf(0, 50);
    Coin v3 = valueOf(0, 25);
    Transaction t1 = createFakeTx(PARAMS, v1, myAddress);
    Transaction t2 = createFakeTx(PARAMS, v2, myAddress);
    Transaction t3 = createFakeTx(PARAMS, v3, myAddress);

    Block genesis = blockStore.getChainHead().getHeader();
    Block b10 = makeSolvedTestBlock(genesis, t1);
    Block b11 = makeSolvedTestBlock(genesis, t2);
    Block b2 = makeSolvedTestBlock(b10, t3);
    Block b3 = makeSolvedTestBlock(b2);

    // Receive a block on the best chain - this should set the last block seen hash.
    chain.add(b10);
    assertEquals(b10.getHash(), wallet.getLastBlockSeenHash());
    assertEquals(b10.getTimeSeconds(), wallet.getLastBlockSeenTimeSecs());
    assertEquals(1, wallet.getLastBlockSeenHeight());
    // Receive a block on the side chain - this should not change the last block seen hash.
    chain.add(b11);
    assertEquals(b10.getHash(), wallet.getLastBlockSeenHash());
    // Receive block 2 on the best chain - this should change the last block seen hash.
    chain.add(b2);
    assertEquals(b2.getHash(), wallet.getLastBlockSeenHash());
    // Receive block 3 on the best chain - this should change the last block seen hash despite having no txns.
    chain.add(b3);
    assertEquals(b3.getHash(), wallet.getLastBlockSeenHash());
}
 
Example #17
Source File: Importer.java    From jelectrum with MIT License 5 votes vote down vote up
public void run()
{
    while(true)
    {
        
        try
        {
            while (jelly.getSpaceLimited())
            {
              setStatus("SPACE_LIMIT_WAIT");
              Thread.sleep(5000);
            }
            setStatus("BLK_QUEUE_WAIT");
            Block blk = block_queue.take();
            setStatus("BLK_WORK_START");

            while(true)
            {
                try
                {
                    putInternal(blk, this);
                    break;
                }
                catch(Throwable t)
                {
                    System.out.println("Block "+blk.getHash()+" save failed.  Retrying");
                    jelly.getEventLog().log("Block "+blk.getHash()+" save failed.  Retrying");

                    t.printStackTrace();
                }
            }
        }
        catch(Throwable e)
        {
            e.printStackTrace();
        }

    }
}
 
Example #18
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void duplicatedBlock() {
    final Transaction tx = createFakeTx(PARAMS, COIN, myAddress);
    StoredBlock block = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, tx).storedBlock;
    wallet.notifyNewBestBlock(block);
    wallet.notifyNewBestBlock(block);
}
 
Example #19
Source File: LittleDB.java    From jelectrum with MIT License 5 votes vote down vote up
@Override
public SerializedTransaction getTransaction(Sha256Hash hash)
{
  if (debug) System.out.println("Looking up tx: " + hash);
  long t1=System.nanoTime();
  Set<Sha256Hash> block_list = getTxToBlockMap(hash);
  //System.out.println("Get tx: " + hash + " - blocks: " + block_list);

  for(Sha256Hash block_hash : block_list)
  {
    SerializedBlock sb = getBlock(block_hash);
    if (sb != null)
    {
      Block b = sb.getBlock(network_parameters);

      for(Transaction tx : b.getTransactions())
      {
        if (tx.getHash().equals(hash))
        {
          TimeRecord.record(t1, "db_get_tx_found");
          return new SerializedTransaction(tx, b.getTime().getTime());
        }
      }

    }
  }
  TimeRecord.record(t1, "db_get_tx_not_found");
  return null;

}
 
Example #20
Source File: MerkleTest.java    From jelectrum with MIT License 5 votes vote down vote up
@Test
public void testTreeHash()
{
    Sha256Hash block_hash = new Sha256Hash("0000000021529d056348e04f7ed506286d0b332811e6c0f5f11194d54fccdfff");
    Block blk = jelly.getDB().getBlock(block_hash).getBlock(jelly.getNetworkParameters());
    Assert.assertEquals(2, blk.getTransactions().size());
    Sha256Hash a = blk.getTransactions().get(0).getHash();
    Sha256Hash b = blk.getTransactions().get(1).getHash();

    Assert.assertEquals(new Sha256Hash("d0e7fce322c043b0f740d4b7ac523f1e58fac3d7ce8782eecbe7e6dc67f68a19"), a);
    Assert.assertEquals(new Sha256Hash("90dfdd37056e892ce908ee2ea864193dc31cd71aa3629bb58c73d657bdf241e8"), b);
    //a = Util.swapEndian(a);
    //b = Util.swapEndian(b);

    //a = Util.doubleHash(a);
    //b = Util.doubleHash(b);


    Sha256Hash tree = Util.treeHash(a,b);

    //tree = Util.swapEndian(tree);

    Sha256Hash expected = blk.getMerkleRoot();

    Assert.assertEquals(expected, tree);
    System.out.println(tree);

}
 
Example #21
Source File: BitcoinRPC.java    From jelectrum with MIT License 5 votes vote down vote up
public JSONObject submitBlock(Block blk)
    throws java.io.IOException, org.json.JSONException
{
    Random rnd = new Random();

    JSONObject msg = new JSONObject();
    msg.put("method", "submitblock");
    msg.put("id", "" + rnd.nextInt());
    
    JSONArray params = new JSONArray();
    params.put(Hex.encodeHexString(blk.bitcoinSerialize()));
    msg.put("params", params);
    //System.out.println(msg.toString(2));
    return sendPost(msg);
}
 
Example #22
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 #23
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 #24
Source File: BlockHexDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public Block deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                byte[] payload = HexUtil.hexStringToByteArray(p.getValueAsString()); // convert  to hex
                return context.getParams().getDefaultSerializer().makeBlock(payload);
            } catch (ProtocolException e) {
                throw new InvalidFormatException(p, "Invalid Block", p.getValueAsString(), Block.class);
            }
        default:
            return (Block) ctxt.handleUnexpectedToken(Block.class, p);
    }
}
 
Example #25
Source File: RpcClientModule.java    From consensusj with Apache License 2.0 5 votes vote down vote up
public RpcClientModule(NetworkParameters netParams) {
    super("BitcoinJMappingClient", new Version(1, 0, 0, null, null, null));

    this.addDeserializer(Address.class, new AddressDeserializer(netParams))
        .addDeserializer(Block.class, new BlockHexDeserializer(netParams))
        .addDeserializer(Coin.class, new CoinDeserializer())
        .addDeserializer(ECKey.class, new ECKeyDeserializer())
        .addDeserializer(Sha256Hash.class, new Sha256HashDeserializer())
        .addSerializer(Address.class, new AddressSerializer())
        .addSerializer(Coin.class, new CoinSerializer())
        .addSerializer(ECKey.class, new ECKeySerializer())
        .addSerializer(Sha256Hash.class, new Sha256HashSerializer())
        .addSerializer(Transaction.class, new TransactionHexSerializer());
}
 
Example #26
Source File: HeadersStore.java    From java-stratum with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void duplicatedBlock() {
    final Transaction tx = createFakeTx(PARAMS, COIN, myAddress);
    StoredBlock block = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, tx).storedBlock;
    wallet.notifyNewBestBlock(block);
    wallet.notifyNewBestBlock(block);
}
 
Example #28
Source File: HeadersStore.java    From java-stratum with Apache License 2.0 5 votes vote down vote up
/** After this call, the store will be at height index. */
public void truncate(long index) {
    lock.lock();
    try {
        Block block = get(index);
        if (block == null)
            throw new RuntimeException("trying to truncate to a block we don't have " + index);
        channel.truncate((index + 1) * HEADER_SIZE);
    } catch (IOException e) {
        propagate(e);
    } finally {
        lock.unlock();
    }
}
 
Example #29
Source File: HeadersStore.java    From java-stratum with Apache License 2.0 5 votes vote down vote up
public Block top() {
    lock.lock();
    try {
        return get(getHeight());
    } finally {
        lock.unlock();
    }
}
 
Example #30
Source File: HeadersStore.java    From java-stratum with Apache License 2.0 5 votes vote down vote up
public HeadersStore(NetworkParameters params, File file, StoredBlock checkpoint, URL initialStore) {
    this.params = params;
    try {
        // Set up the backing file.
        if (initialStore != null && !file.exists()) {
            uncompressInitialStore(initialStore, file);
        }
        randomFile = new RandomAccessFile(file, "rw");
        channel = randomFile.getChannel();
        fileLock = channel.tryLock();
        if (fileLock == null)
            throw new RuntimeException("Store file is already locked by another process");
        if ((randomFile.length() % HEADER_SIZE) != 0) {
            log.warn("file length not round multiple of header size {}", randomFile.length());
            channel.truncate(0);
        }
        if (channel.size() == 0) {
            // Write genesis anyway
            channel.write(ByteBuffer.wrap(params.getGenesisBlock().cloneAsHeader().bitcoinSerialize()), 0);
            if (checkpoint != null) {
                Block header = checkpoint.getHeader().cloneAsHeader();
                channel.write(ByteBuffer.wrap(header.bitcoinSerialize()), checkpoint.getHeight() * HEADER_SIZE);
            }
        }
    } catch (IOException e) {
        if (randomFile != null)
            try {
                randomFile.close();
            } catch (IOException e1) {
                propagate(e1);
            }
        propagate(e);
    }
}