Skip to content

Commit db17a27

Browse files
pslaskibsuieric
authored andcommitted
etcm-637 BlockImport.removeBlocksUntil is removing blocks from the top now
1 parent 491da0d commit db17a27

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

src/main/scala/io/iohk/ethereum/ledger/BlockImport.scala

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import monix.eval.Task
1010
import monix.execution.Scheduler
1111
import org.bouncycastle.util.encoders.Hex
1212

13+
import scala.annotation.tailrec
1314
import scala.concurrent.ExecutionContext
1415

1516
class BlockImport(
@@ -152,7 +153,7 @@ class BlockImport(
152153
bestNumber,
153154
ByteStringUtils.hash2string(parentHash)
154155
)
155-
val oldBlocksData = removeBlocksUntil(parentHash, bestNumber).reverse
156+
val oldBlocksData = removeBlocksUntil(parentHash, bestNumber)
156157
oldBlocksData.foreach(block => blockQueue.enqueueBlock(block.block))
157158
handleBlockExecResult(newBranch, parentWeight, oldBlocksData)
158159
}
@@ -226,26 +227,31 @@ class BlockImport(
226227
* @return the list of removed blocks along with receipts and total difficulties
227228
*/
228229
private def removeBlocksUntil(parent: ByteString, fromNumber: BigInt): List[BlockData] = {
229-
blockchain.getBlockByNumber(fromNumber) match {
230-
case Some(block) if block.header.hash == parent || fromNumber == 0 =>
231-
Nil
230+
@tailrec
231+
def removeBlocksUntil(parent: ByteString, fromNumber: BigInt, acc: List[BlockData]): List[BlockData] = {
232+
blockchain.getBlockByNumber(fromNumber) match {
233+
case Some(block) if block.header.hash == parent || fromNumber == 0 =>
234+
acc
232235

233-
case Some(block) =>
234-
val hash = block.header.hash
236+
case Some(block) =>
237+
val hash = block.header.hash
235238

236-
val blockList = for {
237-
receipts <- blockchain.getReceiptsByHash(hash)
238-
weight <- blockchain.getChainWeightByHash(hash)
239-
} yield BlockData(block, receipts, weight) :: removeBlocksUntil(parent, fromNumber - 1)
239+
val blockDataOpt = for {
240+
receipts <- blockchain.getReceiptsByHash(hash)
241+
weight <- blockchain.getChainWeightByHash(hash)
242+
} yield BlockData(block, receipts, weight)
240243

241-
blockchain.removeBlock(hash, withState = true)
244+
blockchain.removeBlock(hash, withState = true)
242245

243-
blockList.getOrElse(Nil)
246+
removeBlocksUntil(parent, fromNumber - 1, blockDataOpt.map(_ :: acc).getOrElse(acc))
244247

245-
case None =>
246-
log.error(s"Unexpected missing block number: $fromNumber")
247-
Nil
248+
case None =>
249+
log.error(s"Unexpected missing block number: $fromNumber")
250+
acc
251+
}
248252
}
253+
254+
removeBlocksUntil(parent, fromNumber, Nil)
249255
}
250256
}
251257

0 commit comments

Comments
 (0)