Remove BlockHeader.getBlockchainsFrom(), rework type signature for Bl… (#2431)

* Remove BlockHeader.getBlockchainsFrom(), rework type signature for BlockHeader.getBlockchainFrom() to return Future[Option[Blockchain]]

* fix nits
This commit is contained in:
Chris Stewart 2020-12-26 07:17:38 -06:00 committed by GitHub
parent af89c04d15
commit 936d4e4911
2 changed files with 21 additions and 20 deletions

View File

@ -104,14 +104,19 @@ class BitcoinPowTest extends ChainDbUnitTest {
val nestedAssertions: Vector[Future[Assertion]] = {
iterator.map { height =>
val blockF = blockHeaderDAO.getAtHeight(height + 1).map(_.head)
val blockchainF =
val blockchainOptF: Future[Option[Blockchain]] =
blockF.flatMap(b => blockHeaderDAO.getBlockchainFrom(b))
for {
blockchain <- blockchainF
nextTip = blockchain.head
chain = Blockchain.fromHeaders(blockchain.tail.toVector)
nextNBits = Pow.getNetworkWorkRequired(nextTip.blockHeader, chain)
} yield assert(nextNBits == nextTip.nBits)
blockchainOptF.map {
case Some(blockchain) =>
val chain = Blockchain.fromHeaders(blockchain.tail.toVector)
val nextTip = blockchain.tip
val nextNBits =
Pow.getNetworkWorkRequired(nextTip.blockHeader, chain)
assert(nextNBits == nextTip.nBits)
case None =>
fail(s"Chain not found best on header at height=$height")
}
}
}
Future

View File

@ -330,8 +330,8 @@ case class BlockHeaderDAO()(implicit
ec: ExecutionContext): Future[Vector[Blockchain]] = {
val chainTipsF = chainTips
chainTipsF.flatMap { tips =>
val nestedFuture: Vector[Future[Vector[Blockchain]]] = tips.map { tip =>
getBlockchainsFrom(tip)
val nestedFuture: Vector[Future[Option[Blockchain]]] = tips.map { tip =>
getBlockchainFrom(tip)
}
Future.sequence(nestedFuture).map(_.flatten)
}
@ -339,20 +339,16 @@ case class BlockHeaderDAO()(implicit
/** Retrieves a blockchain with the best tip being the given header */
def getBlockchainFrom(header: BlockHeaderDb)(implicit
ec: ExecutionContext): Future[Blockchain] = {
ec: ExecutionContext): Future[Option[Blockchain]] = {
val diffInterval = appConfig.chain.difficultyChangeInterval
val height = Math.max(0, header.height - diffInterval)
val headersF = getBetweenHeights(from = height, to = header.height)
headersF.map(headers =>
Blockchain.fromHeaders(headers.sortBy(_.height)(Ordering.Int.reverse)))
}
def getBlockchainsFrom(header: BlockHeaderDb)(implicit
ec: ExecutionContext): Future[Vector[Blockchain]] = {
val diffInterval = appConfig.chain.difficultyChangeInterval
val height = Math.max(0, header.height - diffInterval)
val blockchainsF =
getBlockchainsBetweenHeights(from = height, to = header.height)
for {
blockchains <- blockchainsF
blockchainOpt = blockchains.find(_.tip == header)
} yield blockchainOpt
}
@tailrec