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

Class Class, % Method, % Line, %
BlockchainBranchComparator 100% (1/1) 100% (2/2) 90.9% (20/22)


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 package co.rsk.core.bc; 19  20 import org.ethereum.core.Block; 21 import org.ethereum.db.BlockStore; 22  23 import java.util.LinkedList; 24 import java.util.List; 25  26 public class BlockchainBranchComparator { 27  private final BlockStore blockStore; 28  29  public BlockchainBranchComparator(BlockStore blockStore) { 30  this.blockStore = blockStore; 31  } 32  33  /** 34  * Returns the branches of both blocks up to a common ancestor 35  */ 36  public BlockFork calculateFork(Block fromBlock, Block toBlock) { 37  List<Block> oldBlocks = new LinkedList<>(); 38  List<Block> newBlocks = new LinkedList<>(); 39  40  Block oldBlock = fromBlock; 41  Block newBlock = toBlock; 42  43  if (oldBlock.isParentOf(newBlock)) { 44  newBlocks.add(newBlock); 45  return new BlockFork(oldBlock, oldBlocks, newBlocks); 46  } 47  48  while (newBlock.getNumber() > oldBlock.getNumber()) { 49  newBlocks.add(0, newBlock); 50  newBlock = blockStore.getBlockByHash(newBlock.getParentHash().getBytes()); 51  } 52  53  while (oldBlock.getNumber() > newBlock.getNumber()) { 54  oldBlocks.add(0, oldBlock); 55  oldBlock = blockStore.getBlockByHash(oldBlock.getParentHash().getBytes()); 56  } 57  58  while (!oldBlock.getHash().equals(newBlock.getHash())) { 59  newBlocks.add(0, newBlock); 60  newBlock = blockStore.getBlockByHash(newBlock.getParentHash().getBytes()); 61  oldBlocks.add(0, oldBlock); 62  oldBlock = blockStore.getBlockByHash(oldBlock.getParentHash().getBytes()); 63  } 64  65  return new BlockFork(oldBlock, oldBlocks, newBlocks); 66  } 67 }