org.ethereum.core.Block Java Examples

The following examples show how to use org.ethereum.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: BlockQueue.java    From ethereumj with MIT License 6 votes vote down vote up
/**
 * adding single block to the queue usually
 *        a result of a NEW_BLOCK message announce.
 * @param block - new block
 */
public void addBlock(Block block){

    if (block.getNumber() != getLastBlock().getNumber() + 1){
        logger.error("Block download out of sync: lastBlock.index: [{}], receivedBlock.index: [{}]",
                getLastBlock().getNumber(), block.getNumber());
        return;
    }

    blockReceivedQueue.add(block);
    lastBlock = block;

    logger.debug("Blocks waiting to be proceed:  queue.size: [{}] lastBlock.number: [{}]" ,
            blockReceivedQueue.size(),
            lastBlock.getNumber());
}
 
Example #2
Source File: IndexedBlockStore.java    From nuls-v2 with MIT License 6 votes vote down vote up
public synchronized List<Block> getBlocksByNumber(long number) {

        List<Block> result = new ArrayList<>();

        if (number >= index.size()) {
            return result;
        }

        List<BlockInfo> blockInfos = index.get((int) number);

        if (blockInfos == null) {
            return result;
        }

        for (BlockInfo blockInfo : blockInfos) {

            byte[] hash = blockInfo.getHash();
            Block block = blocks.get(hash);

            result.add(block);
        }
        return result;
    }
 
Example #3
Source File: IndexedBlockStore.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
public synchronized Block getChainBlockByNumber(long number) {
    if (number >= index.size()) {
        return null;
    }

    List<BlockInfo> blockInfos = index.get((int) number);

    if (blockInfos == null) {
        return null;
    }

    for (BlockInfo blockInfo : blockInfos) {

        if (blockInfo.isMainChain()) {

            byte[] hash = blockInfo.getHash();
            return blocks.get(hash);
        }
    }

    return null;
}
 
Example #4
Source File: ContractCallDialog.java    From ethereumj with MIT License 6 votes vote down vote up
private void playContractCall() {   	
      byte[] addr = Utils.addressStringToBytes(contractAddrInput.getText());
if(addr == null) {
	alertStatusMsg("Not a valid contract address");
      	return;
}

ContractDetails contractDetails = UIEthereumManager.ethereum
		.getRepository().getContractDetails(addr);
      if (contractDetails == null) {
          alertStatusMsg("No contract for that address");
          return;
      }

      final byte[] programCode = contractDetails.getCode();
      if (programCode == null || programCode.length == 0) {
          alertStatusMsg("Such account exist but no code in the db");
          return;
      }

      Transaction tx = createTransaction();
      if (tx == null) return;

      Block lastBlock = UIEthereumManager.ethereum.getBlockchain().getLastBlock();
      ProgramPlayDialog.createAndShowGUI(programCode, tx, lastBlock);
  }
 
Example #5
Source File: IndexedBlockStore.java    From nuls with MIT License 6 votes vote down vote up
public void init(Source<byte[], byte[]> index, Source<byte[], byte[]> blocks) {
    indexDS = index;
    this.index = new DataSourceArray<>(
            new ObjectDataSource<>(index, BLOCK_INFO_SERIALIZER, 512));
    this.blocksDS = blocks;
    this.blocks = new ObjectDataSource<>(blocks, new Serializer<Block, byte[]>() {
        @Override
        public byte[] serialize(Block block) {
            return block.getEncoded();
        }

        @Override
        public Block deserialize(byte[] bytes) {
            return bytes == null ? null : new Block(bytes);
        }
    }, 256);
}
 
Example #6
Source File: IndexedBlockStore.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
public synchronized Block getBestBlock() {

    Long maxLevel = getMaxNumber();
    if (maxLevel < 0) {
        return null;
    }

    Block bestBlock = getChainBlockByNumber(maxLevel);
    if (bestBlock != null) {
        return bestBlock;
    }

    // That scenario can happen
    // if there is a fork branch that is
    // higher than main branch but has
    // less TD than the main branch TD
    while (bestBlock == null) {
        --maxLevel;
        bestBlock = getChainBlockByNumber(maxLevel);
    }

    return bestBlock;
}
 
Example #7
Source File: IndexedBlockStore.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
public synchronized BigInteger getTotalDifficultyForHash(byte[] hash) {
    Block block = this.getBlockByHash(hash);
    if (block == null) {
        return ZERO;
    }

    Long level = block.getNumber();
    List<BlockInfo> blockInfos = index.get(level.intValue());
    for (BlockInfo blockInfo : blockInfos) {
        if (areEqual(blockInfo.getHash(), hash)) {
            return blockInfo.totalDifficulty;
        }
    }

    return ZERO;
}
 
Example #8
Source File: IndexedBlockStore.java    From nuls with MIT License 6 votes vote down vote up
@Override
public synchronized Block getBestBlock() {

    Long maxLevel = getMaxNumber();
    if (maxLevel < 0) {
        return null;
    }

    Block bestBlock = getChainBlockByNumber(maxLevel);
    if (bestBlock != null) {
        return bestBlock;
    }

    // That scenario can happen
    // if there is a fork branch that is
    // higher than main branch but has
    // less TD than the main branch TD
    while (bestBlock == null) {
        --maxLevel;
        bestBlock = getChainBlockByNumber(maxLevel);
    }

    return bestBlock;
}
 
Example #9
Source File: BlockQueue.java    From ethereumj with MIT License 6 votes vote down vote up
/**
 * Add a list of blocks to the processing queue.
 * The list is validated by making sure the first block in the received list of blocks
 * is the next expected block number of the queue.
 * 
 * The queue is configured to contain a maximum number of blocks to avoid memory issues
 * If the list exceeds that, the rest of the received blocks in the list are discarded.
 * 
 * @param blockList - the blocks received from a peer to be added to the queue
 */
public void addBlocks(List<Block> blockList) {

	Block lastReceivedBlock = blockList.get(0);
	if (lastReceivedBlock.getNumber() != getLastBlock().getNumber() + 1){
           logger.error("Block download out of sync: lastBlock.index: [{}], receivedBlock.index: [{}]",
                   getLastBlock().getNumber(), lastReceivedBlock.getNumber());
           return;
       }

       blockReceivedQueue.addAll(blockList);
       lastBlock = blockList.get(blockList.size() - 1);

	logger.debug("Blocks waiting to be proceed:  queue.size: [{}] lastBlock.number: [{}]" ,
			blockReceivedQueue.size(),
               lastBlock.getNumber());
}
 
Example #10
Source File: EthListener.java    From tutorials with MIT License 6 votes vote down vote up
private String calcNetHashRate(Block block) {
    String response = "Net hash rate not available";
    if (block.getNumber() > thou) {
        long timeDelta = 0;
        for (int i = 0; i < thou; ++i) {
            Block parent = ethereum
              .getBlockchain()
              .getBlockByHash(block.getParentHash());
            timeDelta += Math.abs(block.getTimestamp() - parent.getTimestamp());
        }
        response = String.valueOf(block
          .getDifficultyBI()
          .divide(BIUtil.toBI(timeDelta / thou))
          .divide(new BigInteger("1000000000"))
          .doubleValue()) + " GH/s";
    }
    return response;
}
 
Example #11
Source File: IndexedBlockStore.java    From nuls with MIT License 6 votes vote down vote up
@Override
public synchronized Block getChainBlockByNumber(long number) {
    if (number >= index.size()) {
        return null;
    }

    List<BlockInfo> blockInfos = index.get((int) number);

    if (blockInfos == null) {
        return null;
    }

    for (BlockInfo blockInfo : blockInfos) {

        if (blockInfo.isMainChain()) {

            byte[] hash = blockInfo.getHash();
            return blocks.get(hash);
        }
    }

    return null;
}
 
Example #12
Source File: EthHandler.java    From ethereumj with MIT License 6 votes vote down vote up
private void processBlocks(BlocksMessage blocksMessage) {
    Blockchain blockchain = WorldManager.getInstance().getBlockchain();
    List<Block> blockList = blocksMessage.getBlocks();

    if (blockList.isEmpty()) return;
    blockchain.getQueue().addBlocks(blockList);
    blockchain.getQueue().logHashQueueSize();

    // If we got less blocks then we could get,
    // it the correct indication that we are in sync we
    // the chain from here there will be NEW_BLOCK only
    // message expectation
    if (blockList.size() < CONFIG.maxBlocksAsk()) {
        logger.info(" *** The chain sync process fully complete ***");
        syncStatus = SyncSatus.SYNC_DONE;
        stopGetBlocksTimer();
    }
}
 
Example #13
Source File: IndexedBlockStore.java    From nuls with MIT License 6 votes vote down vote up
@Override
public synchronized BigInteger getTotalDifficultyForHash(byte[] hash) {
    Block block = this.getBlockByHash(hash);
    if (block == null) {
        return ZERO;
    }

    Long level = block.getNumber();
    List<BlockInfo> blockInfos = index.get(level.intValue());
    for (BlockInfo blockInfo : blockInfos) {
        if (areEqual(blockInfo.getHash(), hash)) {
            return blockInfo.totalDifficulty;
        }
    }

    return ZERO;
}
 
Example #14
Source File: ProgramExecutorImpl.java    From nuls with MIT License 5 votes vote down vote up
@Override
public void commit() {
    checkThread();
    if (!revert) {
        repository.commit();
        if (prevStateRoot == null) {
            if (parent.blockNumber == 0) {
                parent.blockNumber = blockNumber;
            }
            if (parent.blockNumber != blockNumber) {
                throw new RuntimeException("must use the same block number");
            }
        } else {
            if (vmContext != null) {
                BlockHeaderDto blockHeaderDto;
                try {
                    blockHeaderDto = vmContext.getBlockHeader(blockNumber);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                byte[] parentHash = Hex.decode(blockHeaderDto.getPreHash());
                byte[] hash = Hex.decode(blockHeaderDto.getHash());
                Block block = new Block(parentHash, hash, blockNumber);
                DefaultConfig.getDefault().blockStore().saveBlock(block, BigInteger.ONE, true);
                DefaultConfig.getDefault().pruneManager().blockCommitted(block.getHeader());
            }
            CommonConfig.getDefault().dbFlushManager().flush();
        }
        logTime("commit");
    }
}
 
Example #15
Source File: JSONHelper.java    From ethereumj with MIT License 5 votes vote down vote up
public static void dumpBlock(ObjectNode blockNode, Block block,
			long gasUsed, byte[] state, List<ByteArrayWrapper> keys,
			Repository repository) {
    	
    	blockNode.put("coinbase", Hex.toHexString(block.getCoinbase()));
    	blockNode.put("difficulty", new BigInteger(1, block.calcDifficulty()).toString());
    	blockNode.put("extra_data", "0x");
    	blockNode.put("gas_limit", String.valueOf(block.calcGasLimit()));
    	blockNode.put("gas_used", String.valueOf(gasUsed));
    	blockNode.put("min_gas_price", String.valueOf(block.getMinGasPrice()));
    	blockNode.put("nonce", "0x" + Hex.toHexString(block.getNonce()));
    	blockNode.put("number", String.valueOf(block.getNumber()));
    	blockNode.put("prevhash", "0x" + Hex.toHexString(block.getParentHash()));
        
        ObjectNode statesNode = blockNode.objectNode();
        for (ByteArrayWrapper key : keys) {
            byte[] keyBytes = key.getData();
            AccountState    accountState    = repository.getAccountState(keyBytes);
            ContractDetails details  = repository.getContractDetails(keyBytes);
            JSONHelper.dumpState(statesNode, Hex.toHexString(keyBytes), accountState, details);
        }       
        blockNode.put("state", statesNode);
        
        blockNode.put("state_root", Hex.toHexString(state));
        blockNode.put("timestamp", String.valueOf(block.getTimestamp()));
        
        ArrayNode transactionsNode = blockNode.arrayNode();
        blockNode.put("transactions", transactionsNode);
        
        blockNode.put("tx_list_root", ByteUtil.toHexString(block.getTxTrieRoot()));
        blockNode.put("uncles_hash", "0x" + Hex.toHexString(block.getUnclesHash()));
        
//		JSONHelper.dumpTransactions(blockNode,
//				stateRoot, codeHash, code, storage);
    }
 
Example #16
Source File: IndexedBlockStore.java    From nuls-v2 with MIT License 5 votes vote down vote up
private void addInternalBlock(Block block, BigInteger totalDifficulty, boolean mainChain) {

        List<BlockInfo> blockInfos = block.getNumber() >= index.size() ? null : index.get((int) block.getNumber());
        blockInfos = blockInfos == null ? new ArrayList<BlockInfo>() : blockInfos;

        BlockInfo blockInfo = new BlockInfo();
        blockInfo.setTotalDifficulty(totalDifficulty);
        blockInfo.setHash(block.getHash());
        blockInfo.setMainChain(mainChain); // FIXME:maybe here I should force reset main chain for all uncles on that level

        putBlockInfo(blockInfos, blockInfo);
        index.set((int) block.getNumber(), blockInfos);

        blocks.put(block.getHash(), block);
    }
 
Example #17
Source File: PruneManager.java    From nuls-v2 with MIT License 5 votes vote down vote up
private List<byte[]> getAllChainsHashes(long fromBlock, long toBlock) {
    List<byte[]> ret = new ArrayList<>();
    for (long num = fromBlock; num <= toBlock; num++) {
        List<Block> blocks = blockStore.getBlocksByNumber(num);
        List<byte[]> hashes = blocks.stream().map(Block::getHash).collect(Collectors.toList());
        ret.addAll(hashes);
    }
    return ret;
}
 
Example #18
Source File: IndexedBlockStore.java    From nuls with MIT License 5 votes vote down vote up
@Override
public synchronized List<byte[]> getListHashesEndWith(byte[] hash, long number) {

    List<Block> blocks = getListBlocksEndWith(hash, number);
    List<byte[]> hashes = new ArrayList<>(blocks.size());

    for (Block b : blocks) {
        hashes.add(b.getHash());
    }

    return hashes;
}
 
Example #19
Source File: EthListener.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
    if (syncDone) {
        out("Net hash rate: " + calcNetHashRate(block));
        out("Block difficulty: " + block.getDifficultyBI().toString());
        out("Block transactions: " + block.getTransactionsList().toString());
        out("Best block (last block): " + ethereum
          .getBlockchain()
          .getBestBlock().toString());
        out("Total difficulty: " + ethereum
          .getBlockchain()
          .getTotalDifficulty().toString());
    }
}
 
Example #20
Source File: IndexedBlockStore.java    From nuls with MIT License 5 votes vote down vote up
private void addInternalBlock(Block block, BigInteger totalDifficulty, boolean mainChain) {

        List<BlockInfo> blockInfos = block.getNumber() >= index.size() ? null : index.get((int) block.getNumber());
        blockInfos = blockInfos == null ? new ArrayList<BlockInfo>() : blockInfos;

        BlockInfo blockInfo = new BlockInfo();
        blockInfo.setTotalDifficulty(totalDifficulty);
        blockInfo.setHash(block.getHash());
        blockInfo.setMainChain(mainChain); // FIXME:maybe here I should force reset main chain for all uncles on that level

        putBlockInfo(blockInfos, blockInfo);
        index.set((int) block.getNumber(), blockInfos);

        blocks.put(block.getHash(), block);
    }
 
Example #21
Source File: BlockQueue.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Processing the queue adding blocks to the chain.
 */
private void nudgeQueue() {
	if (blockReceivedQueue.isEmpty())
		return;
	
	logger.debug("BlockQueue size: {}", blockReceivedQueue.size());
	Block block = blockReceivedQueue.poll();

       logger.info("Processing block index: {}", block.getNumber());
	WorldManager.getInstance().getBlockchain().add(block);
}
 
Example #22
Source File: EthHandler.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Processing NEW_BLOCK announce message
 * @param newBlockMessage - new block message
 */
private void procesNewBlock(NewBlockMessage newBlockMessage){

    Blockchain blockchain = WorldManager.getInstance().getBlockchain();
    Block newBlock = newBlockMessage.getBlock();

    // If the hashes still being downloaded ignore the NEW_BLOCKs
    // that block hash will be retrieved by the others and letter the block itself
    if (syncStatus == SyncSatus.INIT || syncStatus == SyncSatus.HASH_RETRIEVING) {
        logger.debug("Sync status INIT or HASH_RETREIVING ignore new block.index: [{}]", newBlock.getNumber());
        return;
    }

    // If the GET_BLOCKs stage started add hash to the end of the hash list
    // then the block will be retrieved in it's turn;
    if (syncStatus == SyncSatus.BLOCK_RETRIEVING){
        logger.debug("Sync status BLOCK_RETREIVING add to the end of hash list: block.index: [{}]", newBlock.getNumber());
        blockchain.getQueue().addNewBlockHash(newBlockMessage.getBlock().getHash());
        return;
    }


    // here is post sync process
    logger.info("New block received: block.index [{}]", newBlockMessage.getBlock().getNumber());
    WorldManager.getInstance().clearPendingTransactions(newBlockMessage.getBlock().getTransactionsList());

    long gap = newBlockMessage.getBlock().getNumber() - blockchain.getQueue().getLastBlock().getNumber();
    if (gap > 1){
        logger.error("Gap in the chain, go out of sync");
        this.syncStatus = SyncSatus.HASH_RETRIEVING;
        blockchain.getQueue().addHash(newBlock.getHash());
        sendGetBlockHashes();
    }

    blockchain.getQueue().addBlock(newBlockMessage.getBlock());
    blockchain.getQueue().logHashQueueSize();
}
 
Example #23
Source File: ProgramExecutorImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public void commit() {
    checkThread();
    if (!revert) {
        repository.commit();
        if (prevStateRoot == null) {
            if (parent.blockNumber == 0) {
                parent.blockNumber = blockNumber;
            }
            if (parent.blockNumber != blockNumber) {
                throw new RuntimeException(String.format("must use the same block number, parent blockNumber is [%s], this blockNumber is [%s]", parent.blockNumber, blockNumber));
            }
        } else {
            if (vmContext != null) {
                BlockHeaderDto blockHeaderDto;
                try {
                    blockHeaderDto = vmContext.getBlockHeader(getCurrentChainId(), blockNumber);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                byte[] parentHash = HexUtil.decode(blockHeaderDto.getPreHash());
                byte[] hash = HexUtil.decode(blockHeaderDto.getHash());
                Block block = new Block(parentHash, hash, blockNumber);
                getCurrentChain().getDefaultConfig().blockStore().saveBlock(block, BigInteger.ONE, true);
                getCurrentChain().getDefaultConfig().pruneManager().blockCommitted(block.getHeader());
            }
            getCurrentChain().getCommonConfig().dbFlushManager().flush();
        }
        logTime("commit");
    }
}
 
Example #24
Source File: PruneManager.java    From nuls with MIT License 5 votes vote down vote up
private List<byte[]> getAllChainsHashes(long fromBlock, long toBlock) {
    List<byte[]> ret = new ArrayList<>();
    for (long num = fromBlock; num <= toBlock; num++) {
        List<Block> blocks = blockStore.getBlocksByNumber(num);
        List<byte[]> hashes = blocks.stream().map(Block::getHash).collect(Collectors.toList());
        ret.addAll(hashes);
    }
    return ret;
}
 
Example #25
Source File: IndexedBlockStore.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public synchronized List<BlockHeader> getListHeadersEndWith(byte[] hash, long qty) {

    List<Block> blocks = getListBlocksEndWith(hash, qty);
    List<BlockHeader> headers = new ArrayList<>(blocks.size());

    for (Block b : blocks) {
        headers.add(b.getHeader());
    }

    return headers;
}
 
Example #26
Source File: BlocksMessage.java    From ethereumj with MIT License 5 votes vote down vote up
private void parse() {
	RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);

	blocks = new ArrayList<>();
	for (int i = 1; i < paramsList.size(); ++i) {
		RLPList rlpData = ((RLPList) paramsList.get(i));
		Block blockData = new Block(rlpData.getRLPData());
		blocks.add(blockData);
	}
	parsed = true;
}
 
Example #27
Source File: AbstractBlockstore.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public byte[] getBlockHashByNumber(long blockNumber, byte[] branchBlockHash) {
    Block branchBlock = getBlockByHash(branchBlockHash);
    if (branchBlock.getNumber() < blockNumber) {
        throw new IllegalArgumentException("Requested block number > branch hash number: " + blockNumber + " < " + branchBlock.getNumber());
    }
    while (branchBlock.getNumber() > blockNumber) {
        branchBlock = getBlockByHash(branchBlock.getParentHash());
    }
    return branchBlock.getHash();
}
 
Example #28
Source File: ProgramPlayDialog.java    From ethereumj with MIT License 4 votes vote down vote up
/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
public static void createAndShowGUI(byte[] runCode, final Transaction tx, Block lastBlock) {

    final ProgramPlayDialog ppd;
    if (tx != null)
        ppd = new ProgramPlayDialog(runCode, tx, lastBlock);
    else{
        ppd = new ProgramPlayDialog(runCode);
    }

    //Create and set up the window.
    JFrame frame = new JFrame("Program Draft Play");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    java.net.URL url = ClassLoader.getSystemResource("ethereum-icon.png");
    Toolkit kit = Toolkit.getDefaultToolkit();
    Image img = kit.createImage(url);
    frame.setIconImage(img);

    frame.setPreferredSize(new Dimension(580, 500));
    frame.setLocation(400, 200);

    //Add content to the window.
    frame.add(ppd, BorderLayout.CENTER);
    
    // close event
    frame.addWindowListener(new java.awt.event.WindowAdapter() {
        @Override
        public void windowClosing(java.awt.event.WindowEvent windowEvent) {
        	if (tx == null) {
        		ppd.pi.getRepository().close();
            	ppd.pi = null;
        	}
        }
    });

    //Display the window.
    frame.pack();
    frame.setVisible(true);
    ppd.setFocus();
}
 
Example #29
Source File: EthBean.java    From tutorials with MIT License 4 votes vote down vote up
public Block getBestBlock() {
    return this.ethereum.getBlockchain().getBestBlock();
}
 
Example #30
Source File: RepositoryImpl.java    From nuls-v2 with MIT License 4 votes vote down vote up
@Override
public void dumpState(Block block, long gasUsed, int txNumber, byte[] txHash) {
    throw new RuntimeException("Not supported");
}