private void createNewStore(NetworkParameters params, File file) throws BlockStoreException { // Create a new block store if the file wasn't found or anything went wrong whilst reading. blockCache.clear(); try { if (file.exists()) { if (!file.delete()) throw new BlockStoreException("Could not delete old store in order to recreate it"); } // Create fresh. The d makes writes synchronous. this.file = new RandomAccessFile(file, "rwd"); this.channel = this.file.getChannel(); lock(); this.file.write(FILE_FORMAT_VERSION); } catch (IOException e1) { // We could not load a block store nor could we create a new one! throw new BlockStoreException(e1); } try { // Set up the genesis block. When we start out fresh, it is by definition the top of the // chain. Block genesis = params.genesisBlock.cloneAsHeader(); StoredBlock storedGenesis = new StoredBlock(genesis, genesis.getWork(), 0); this.chainHead = storedGenesis.getHeader().getHash(); this.file.write(this.chainHead.getBytes()); put(storedGenesis); } catch (VerificationException e1) { throw new RuntimeException(e1); // Cannot happen. } catch (IOException e) { throw new BlockStoreException(e); } }
public static void write(FileChannel channel, StoredBlock block) throws IOException { ByteBuffer buf = ByteBuffer.allocate(Record.SIZE); buf.putInt(block.getHeight()); byte[] chainWorkBytes = block.getChainWork().toByteArray(); checkState( chainWorkBytes.length <= CHAIN_WORK_BYTES, "Ran out of space to store chain work!"); if (chainWorkBytes.length < CHAIN_WORK_BYTES) { // Pad to the right size. buf.put(EMPTY_BYTES, 0, CHAIN_WORK_BYTES - chainWorkBytes.length); } buf.put(chainWorkBytes); buf.put(block.getHeader().cloneAsHeader().feathercoinSerialize()); buf.position(0); channel.position(channel.size()); if (channel.write(buf) < Record.SIZE) throw new IOException("Failed to write record!"); channel.position(channel.size() - Record.SIZE); }
public synchronized void setChainHead(StoredBlock chainHead) throws BlockStoreException { ensureOpen(); try { this.chainHead = chainHead.getHeader().getHash(); // Write out new hash to the first 32 bytes of the file past one (first byte is version // number). channel.write(ByteBuffer.wrap(this.chainHead.getBytes()), 1); } catch (IOException e) { throw new BlockStoreException(e); } }
public synchronized void put(StoredBlock block) throws BlockStoreException { ensureOpen(); try { Sha256Hash hash = block.getHeader().getHash(); // Append to the end of the file. Record.write(channel, block); blockCache.put(hash, block); } catch (IOException e) { throw new BlockStoreException(e); } }