Coverage Summary for Class: ConsensusValidationMainchainViewImpl (co.rsk.core.bc)

Class Class, % Method, % Line, %
ConsensusValidationMainchainViewImpl 0% (0/1) 0% (0/4) 0% (0/19)


1 /* 2  * This file is part of RskJ 3  * Copyright (C) 2019 RSK Labs Ltd. 4  * 5  * This program is free software: you can redistribute it and/or modify 6  * it under the terms of the GNU Lesser General Public License as published by 7  * the Free Software Foundation, either version 3 of the License, or 8  * (at your option) any later version. 9  * 10  * This program is distributed in the hope that it will be useful, 11  * but WITHOUT ANY WARRANTY; without even the implied warranty of 12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13  * GNU Lesser General Public License for more details. 14  * 15  * You should have received a copy of the GNU Lesser General Public License 16  * along with this program. If not, see <http://www.gnu.org/licenses/>. 17  */ 18  19 package co.rsk.core.bc; 20  21 import co.rsk.crypto.Keccak256; 22 import org.ethereum.core.Block; 23 import org.ethereum.core.BlockHeader; 24 import org.ethereum.db.BlockStore; 25 import org.slf4j.Logger; 26 import org.slf4j.LoggerFactory; 27  28 import java.util.ArrayList; 29 import java.util.List; 30 import java.util.Map; 31  32 public class ConsensusValidationMainchainViewImpl implements ConsensusValidationMainchainView { 33  34  private static final Logger logger = LoggerFactory.getLogger("consensusmainchainview"); 35  36  private final BlockStore blockStore; 37  38  private Map<Keccak256, BlockHeader> pendingHeadersByHash; 39  40  public ConsensusValidationMainchainViewImpl(BlockStore blockStore) { 41  this.blockStore = blockStore; 42  } 43  44  /** 45  * Design decision note. headers for blocks not yet added to the blockchain are not in the BlockStore. 46  * These headers are in a collection used by the SyncProcessor and friends. 47  * Sync process creates a new version of this collection periodically and that is why a setter is needed. 48  */ 49  public void setPendingHeaders(Map<Keccak256, BlockHeader> pendingHeadersByHash) { 50  this.pendingHeadersByHash = pendingHeadersByHash; 51  } 52  53  @Override 54  public synchronized List<BlockHeader> get(Keccak256 startingHashToGetMainchainFrom, int height) { 55  List<BlockHeader> headers = new ArrayList<>(); 56  57  Keccak256 currentHash = startingHashToGetMainchainFrom; 58  for(int i = 0; i < height; i++) { 59  Block block = blockStore.getBlockByHash(currentHash.getBytes()); 60  BlockHeader header; 61  if (block != null) { 62  header = block.getHeader(); 63  } else { 64  if(pendingHeadersByHash == null) { 65  logger.error("Pending headers by hash has not been set."); 66  return new ArrayList<>(); 67  } 68  header = pendingHeadersByHash.get(currentHash); 69  } 70  71  if(header == null) { 72  return new ArrayList<>(); 73  } 74  75  headers.add(header); 76  currentHash = header.getParentHash(); 77  } 78  79  return headers; 80  } 81 }