Skip to content

Commit 6aed0bb

Browse files
author
Aurélien Richez
committed
move getBestBlockNumber and getBestBlock to blockchainReader
1 parent 50b7763 commit 6aed0bb

26 files changed

+119
-106
lines changed

src/main/scala/io/iohk/ethereum/blockchain/sync/SyncController.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ class SyncController(
120120
peerEventBus,
121121
blockImport,
122122
blockchain,
123+
blockchainReader,
123124
new BranchResolution(blockchain, blockchainReader),
124125
validators.blockValidator,
125126
blacklist,

src/main/scala/io/iohk/ethereum/blockchain/sync/fast/FastSyncBranchResolver.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ trait FastSyncBranchResolver {
1717

1818
// TODO [ETCM-676] move to [[Blockchain]] and make sure it's atomic
1919
def discardBlocksAfter(lastValidBlock: BigInt): Unit =
20-
discardBlocks(lastValidBlock, blockchain.getBestBlockNumber())
20+
discardBlocks(lastValidBlock, blockchainReader.getBestBlockNumber())
2121

2222
// TODO [ETCM-676] move to [[Blockchain]] and make sure it's atomic
2323
private def discardBlocks(fromBlock: BigInt, toBlock: BigInt): Unit = {

src/main/scala/io/iohk/ethereum/blockchain/sync/fast/FastSyncBranchResolverActor.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,9 @@ class FastSyncBranchResolverActor(
5959
log.debug(
6060
"Starting branch resolution now with peer {} and block number {}",
6161
peerWithInfo,
62-
blockchain.getBestBlockNumber()
62+
blockchainReader.getBestBlockNumber()
6363
)
64-
requestRecentBlockHeaders(peer, blockchain.getBestBlockNumber())
64+
requestRecentBlockHeaders(peer, blockchainReader.getBestBlockNumber())
6565
case None =>
6666
log.info("Waiting for peers, rescheduling StartBranchResolver")
6767
timers.startSingleTimer(RestartTimerKey, StartBranchResolver, 1.second)

src/main/scala/io/iohk/ethereum/blockchain/sync/regular/BlockImporter.scala

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ class BlockImporter(
3737
fetcher: ActorRef,
3838
blockImport: BlockImport,
3939
blockchain: Blockchain,
40+
blockchainReader: BlockchainReader,
4041
branchResolution: BranchResolution,
4142
syncConfig: SyncConfig,
4243
ommersPool: ActorRef,
@@ -311,7 +312,7 @@ class BlockImporter(
311312
Right(Nil)
312313
}
313314

314-
private def bestKnownBlockNumber: BigInt = blockchain.getBestBlockNumber()
315+
private def bestKnownBlockNumber: BigInt = blockchainReader.getBestBlockNumber()
315316

316317
private def getBehavior(newBehavior: NewBehavior, blockImportType: BlockImportType): Behavior = newBehavior match {
317318
case Running => running
@@ -326,6 +327,7 @@ object BlockImporter {
326327
fetcher: ActorRef,
327328
blockImport: BlockImport,
328329
blockchain: Blockchain,
330+
blockchainReader: BlockchainReader,
329331
branchResolution: BranchResolution,
330332
syncConfig: SyncConfig,
331333
ommersPool: ActorRef,
@@ -338,6 +340,7 @@ object BlockImporter {
338340
fetcher,
339341
blockImport,
340342
blockchain,
343+
blockchainReader,
341344
branchResolution,
342345
syncConfig,
343346
ommersPool,

src/main/scala/io/iohk/ethereum/blockchain/sync/regular/RegularSync.scala

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import akka.actor.Scheduler
1010
import akka.actor.SupervisorStrategy
1111
import akka.actor.typed.scaladsl.adapter._
1212
import akka.actor.typed.{ActorRef => TypedActorRef}
13-
1413
import io.iohk.ethereum.blockchain.sync.Blacklist
1514
import io.iohk.ethereum.blockchain.sync.SyncProtocol
1615
import io.iohk.ethereum.blockchain.sync.SyncProtocol.Status
@@ -20,10 +19,8 @@ import io.iohk.ethereum.blockchain.sync.regular.RegularSync.NewCheckpoint
2019
import io.iohk.ethereum.blockchain.sync.regular.RegularSync.ProgressProtocol
2120
import io.iohk.ethereum.blockchain.sync.regular.RegularSync.ProgressState
2221
import io.iohk.ethereum.consensus.validators.BlockValidator
23-
import io.iohk.ethereum.domain.Block
24-
import io.iohk.ethereum.domain.Blockchain
25-
import io.iohk.ethereum.ledger.BlockImport
26-
import io.iohk.ethereum.ledger.BranchResolution
22+
import io.iohk.ethereum.domain.{Block, Blockchain, BlockchainReader}
23+
import io.iohk.ethereum.ledger.{BlockImport, BranchResolution}
2724
import io.iohk.ethereum.utils.ByteStringUtils
2825
import io.iohk.ethereum.utils.Config.SyncConfig
2926

@@ -33,6 +30,7 @@ class RegularSync(
3330
peerEventBus: ActorRef,
3431
blockImport: BlockImport,
3532
blockchain: Blockchain,
33+
blockchainReader: BlockchainReader,
3634
branchResolution: BranchResolution,
3735
blockValidator: BlockValidator,
3836
blacklist: Blacklist,
@@ -62,6 +60,7 @@ class RegularSync(
6260
fetcher.toClassic,
6361
blockImport,
6462
blockchain,
63+
blockchainReader,
6564
branchResolution,
6665
syncConfig,
6766
ommersPool,
@@ -133,6 +132,7 @@ object RegularSync {
133132
peerEventBus: ActorRef,
134133
blockImport: BlockImport,
135134
blockchain: Blockchain,
135+
blockchainReader: BlockchainReader,
136136
branchResolution: BranchResolution,
137137
blockValidator: BlockValidator,
138138
blacklist: Blacklist,
@@ -148,6 +148,7 @@ object RegularSync {
148148
peerEventBus,
149149
blockImport,
150150
blockchain,
151+
blockchainReader,
151152
branchResolution,
152153
blockValidator,
153154
blacklist,

src/main/scala/io/iohk/ethereum/consensus/pow/PoWConsensus.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ class PoWConsensus private (
105105
node.syncController,
106106
node.ethMiningService,
107107
blockCreator,
108-
blockchain,
108+
blockchainReader,
109109
blockchainConfig.forkBlockNumbers.ecip1049BlockNumber
110110
),
111111
"PoWMinerCoordinator",

src/main/scala/io/iohk/ethereum/consensus/pow/PoWMiningCoordinator.scala

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,8 @@ import monix.execution.Scheduler
1212
import scala.concurrent.duration.DurationInt
1313

1414
import io.iohk.ethereum.consensus.pow.PoWMiningCoordinator.CoordinatorProtocol
15-
import io.iohk.ethereum.consensus.pow.miners.EthashDAGManager
16-
import io.iohk.ethereum.consensus.pow.miners.EthashMiner
17-
import io.iohk.ethereum.consensus.pow.miners.KeccakMiner
18-
import io.iohk.ethereum.consensus.pow.miners.Miner
19-
import io.iohk.ethereum.domain.Block
20-
import io.iohk.ethereum.domain.Blockchain
15+
import io.iohk.ethereum.consensus.pow.miners.{EthashDAGManager, EthashMiner, KeccakMiner, Miner}
16+
import io.iohk.ethereum.domain.{Block, Blockchain, BlockchainReader}
2117
import io.iohk.ethereum.jsonrpc.EthMiningService
2218

2319
object PoWMiningCoordinator {
@@ -53,7 +49,7 @@ object PoWMiningCoordinator {
5349
syncController: ClassicActorRef,
5450
ethMiningService: EthMiningService,
5551
blockCreator: PoWBlockCreator,
56-
blockchain: Blockchain,
52+
blockchainReader: BlockchainReader,
5753
ecip1049BlockNumber: Option[BigInt]
5854
): Behavior[CoordinatorProtocol] =
5955
Behaviors
@@ -63,7 +59,7 @@ object PoWMiningCoordinator {
6359
syncController,
6460
ethMiningService,
6561
blockCreator,
66-
blockchain,
62+
blockchainReader,
6763
ecip1049BlockNumber
6864
)
6965
)
@@ -74,7 +70,7 @@ class PoWMiningCoordinator private (
7470
syncController: ClassicActorRef,
7571
ethMiningService: EthMiningService,
7672
blockCreator: PoWBlockCreator,
77-
blockchain: Blockchain,
73+
blockchainReader: BlockchainReader,
7874
ecip1049BlockNumber: Option[BigInt]
7975
) extends AbstractBehavior[CoordinatorProtocol](context) {
8076

@@ -98,7 +94,7 @@ class PoWMiningCoordinator private (
9894

9995
case MineNext =>
10096
log.debug("Received message MineNext")
101-
blockchain
97+
blockchainReader
10298
.getBestBlock()
10399
.fold {
104100
log.error("Unable to get block for mining: blockchain.getBestBlock() returned None")

src/main/scala/io/iohk/ethereum/consensus/pow/miners/MockedMiner.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class MockedMiner(
6060
sender() ! MiningError(error)
6161
}
6262
case None =>
63-
val parentBlock = blockchain.getBestBlock()
63+
val parentBlock = blockchainReader.getBestBlock()
6464
startMiningBlocks(mineBlocks, parentBlock.get)
6565
}
6666
}

src/main/scala/io/iohk/ethereum/domain/Blockchain.scala

Lines changed: 3 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,6 @@ trait Blockchain {
7474
*/
7575
def getChainWeightByHash(blockhash: ByteString): Option[ChainWeight]
7676

77-
def getBestBlockNumber(): BigInt
78-
79-
def getBestBlock(): Option[Block]
80-
8177
def getLatestCheckpointBlockNumber(): BigInt
8278

8379
def removeBlock(hash: ByteString, withState: Boolean): Unit
@@ -114,42 +110,15 @@ class BlockchainImpl(
114110

115111
override def isInChain(hash: ByteString): Boolean =
116112
(for {
117-
header <- blockchainReader.getBlockHeaderByHash(hash) if header.number <= getBestBlockNumber()
113+
header <- blockchainReader.getBlockHeaderByHash(hash) if header.number <= blockchainReader.getBestBlockNumber()
118114
hash <- blockchainReader.getHashByBlockNumber(header.number)
119115
} yield header.hash == hash).getOrElse(false)
120116

121117
override def getChainWeightByHash(blockhash: ByteString): Option[ChainWeight] = chainWeightStorage.get(blockhash)
122118

123-
override def getBestBlockNumber(): BigInt = {
124-
val bestSavedBlockNumber = appStateStorage.getBestBlockNumber()
125-
val bestKnownBlockNumber = blockchainMetadata.bestKnownBlockAndLatestCheckpoint.get().bestBlockNumber
126-
log.debug(
127-
"Current best saved block number {}. Current best known block number {}",
128-
bestSavedBlockNumber,
129-
bestKnownBlockNumber
130-
)
131-
132-
// The cached best block number should always be more up-to-date than the one on disk, we are keeping access to disk
133-
// above only for logging purposes
134-
bestKnownBlockNumber
135-
}
136-
137119
override def getLatestCheckpointBlockNumber(): BigInt =
138120
blockchainMetadata.bestKnownBlockAndLatestCheckpoint.get().latestCheckpointNumber
139121

140-
//returns the best known block if it's available in the storage, otherwise the best stored block
141-
override def getBestBlock(): Option[Block] = {
142-
val bestBlockNumber = getBestBlockNumber()
143-
log.debug("Trying to get best block with number {}", bestBlockNumber)
144-
blockchainReader
145-
.getBlockByNumber(bestBlockNumber)
146-
.orElse(
147-
blockchainReader.getBlockByNumber(
148-
appStateStorage.getBestBlockNumber()
149-
)
150-
)
151-
}
152-
153122
override def getAccount(address: Address, blockNumber: BigInt): Option[Account] =
154123
getAccountMpt(blockNumber) >>= (_.get(address))
155124

@@ -207,7 +176,7 @@ class BlockchainImpl(
207176
def getReadOnlyMptStorage(): MptStorage = stateStorage.getReadOnlyStorage
208177

209178
private def persistBestBlocksData(): Unit = {
210-
val currentBestBlockNumber = getBestBlockNumber()
179+
val currentBestBlockNumber = blockchainReader.getBestBlockNumber()
211180
val currentBestCheckpointNumber = getLatestCheckpointBlockNumber()
212181
log.debug(
213182
"Persisting app info data into database. Persisted block number is {}. " +
@@ -265,7 +234,7 @@ class BlockchainImpl(
265234
log.debug(s"Trying to remove block ${block.idTag}")
266235

267236
val txList = block.body.transactionList
268-
val bestBlockNumber = getBestBlockNumber()
237+
val bestBlockNumber = blockchainReader.getBestBlockNumber()
269238
val latestCheckpointNumber = getLatestCheckpointBlockNumber()
270239

271240
val blockNumberMappingUpdates =

src/main/scala/io/iohk/ethereum/domain/BlockchainReader.scala

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
11
package io.iohk.ethereum.domain
22

33
import akka.util.ByteString
4-
5-
import io.iohk.ethereum.db.storage.BlockBodiesStorage
6-
import io.iohk.ethereum.db.storage.BlockHeadersStorage
7-
import io.iohk.ethereum.db.storage.BlockNumberMappingStorage
8-
import io.iohk.ethereum.db.storage.ReceiptStorage
9-
import io.iohk.ethereum.db.storage.StateStorage
4+
import io.iohk.ethereum.db.storage.{
5+
AppStateStorage,
6+
BlockBodiesStorage,
7+
BlockHeadersStorage,
8+
BlockNumberMappingStorage,
9+
ReceiptStorage,
10+
StateStorage
11+
}
1012
import io.iohk.ethereum.mpt.MptNode
13+
import io.iohk.ethereum.utils.Logger
1114

1215
class BlockchainReader(
1316
blockHeadersStorage: BlockHeadersStorage,
1417
blockBodiesStorage: BlockBodiesStorage,
1518
blockNumberMappingStorage: BlockNumberMappingStorage,
1619
stateStorage: StateStorage,
17-
receiptStorage: ReceiptStorage
18-
) {
20+
receiptStorage: ReceiptStorage,
21+
appStateStorage: AppStateStorage,
22+
blockchainMetadata: BlockchainMetadata
23+
) extends Logger {
1924

2025
/** Allows to query a blockHeader by block hash
2126
*
@@ -81,16 +86,46 @@ class BlockchainReader(
8186
* @return Receipts if found
8287
*/
8388
def getReceiptsByHash(blockhash: ByteString): Option[Seq[Receipt]] = receiptStorage.get(blockhash)
89+
90+
def getBestBlockNumber(): BigInt = {
91+
val bestSavedBlockNumber = appStateStorage.getBestBlockNumber()
92+
val bestKnownBlockNumber = blockchainMetadata.bestKnownBlockAndLatestCheckpoint.get().bestBlockNumber
93+
log.debug(
94+
"Current best saved block number {}. Current best known block number {}",
95+
bestSavedBlockNumber,
96+
bestKnownBlockNumber
97+
)
98+
99+
// The cached best block number should always be more up-to-date than the one on disk, we are keeping access to disk
100+
// above only for logging purposes
101+
bestKnownBlockNumber
102+
}
103+
104+
//returns the best known block if it's available in the storage, otherwise the best stored block
105+
def getBestBlock(): Option[Block] = {
106+
val bestBlockNumber = getBestBlockNumber()
107+
log.debug("Trying to get best block with number {}", bestBlockNumber)
108+
getBlockByNumber(bestBlockNumber).orElse(
109+
getBlockByNumber(
110+
appStateStorage.getBestBlockNumber()
111+
)
112+
)
113+
}
84114
}
85115

86116
object BlockchainReader {
87117

88-
def apply(storages: BlockchainStorages): BlockchainReader = new BlockchainReader(
118+
def apply(
119+
storages: BlockchainStorages,
120+
blockchainMetadata: BlockchainMetadata
121+
): BlockchainReader = new BlockchainReader(
89122
storages.blockHeadersStorage,
90123
storages.blockBodiesStorage,
91124
storages.blockNumberMappingStorage,
92125
storages.stateStorage,
93-
storages.receiptStorage
126+
storages.receiptStorage,
127+
storages.appStateStorage,
128+
blockchainMetadata
94129
)
95130

96131
}

src/main/scala/io/iohk/ethereum/jsonrpc/CheckpointingService.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class CheckpointingService(
2727
import CheckpointingService._
2828

2929
def getLatestBlock(req: GetLatestBlockRequest): ServiceResponse[GetLatestBlockResponse] = {
30-
lazy val bestBlockNum = blockchain.getBestBlockNumber()
30+
lazy val bestBlockNum = blockchainReader.getBestBlockNumber()
3131
lazy val blockToReturnNum =
3232
if (req.checkpointingInterval != 0)
3333
bestBlockNum - bestBlockNum % req.checkpointingInterval

src/main/scala/io/iohk/ethereum/jsonrpc/EthBlocksService.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ class EthBlocksService(
5353
* @return Current block number the client is on.
5454
*/
5555
def bestBlockNumber(req: BestBlockNumberRequest): ServiceResponse[BestBlockNumberResponse] = Task {
56-
Right(BestBlockNumberResponse(blockchain.getBestBlockNumber()))
56+
Right(BestBlockNumberResponse(blockchainReader.getBestBlockNumber()))
5757
}
5858

5959
/** Implements the eth_getBlockTransactionCountByHash method that fetches the number of txs that a certain block has.

src/main/scala/io/iohk/ethereum/jsonrpc/EthMiningService.scala

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@ import io.iohk.ethereum.consensus.ConsensusConfig
2020
import io.iohk.ethereum.consensus.blocks.PendingBlockAndState
2121
import io.iohk.ethereum.consensus.pow.EthashUtils
2222
import io.iohk.ethereum.crypto.kec256
23-
import io.iohk.ethereum.domain.Address
24-
import io.iohk.ethereum.domain.BlockHeader
25-
import io.iohk.ethereum.domain.Blockchain
23+
import io.iohk.ethereum.domain.{Address, BlockHeader, BlockchainReader}
2624
import io.iohk.ethereum.jsonrpc.AkkaTaskOps._
2725
import io.iohk.ethereum.jsonrpc.server.controllers.JsonRpcBaseController.JsonRpcConfig
2826
import io.iohk.ethereum.ommers.OmmersPool
@@ -51,7 +49,7 @@ object EthMiningService {
5149
}
5250

5351
class EthMiningService(
54-
blockchain: Blockchain,
52+
blockchainReader: BlockchainReader,
5553
blockchainConfig: BlockchainConfig,
5654
consensus: Consensus,
5755
jsonRpcConfig: JsonRpcConfig,
@@ -83,7 +81,7 @@ class EthMiningService(
8381
def getWork(req: GetWorkRequest): ServiceResponse[GetWorkResponse] =
8482
consensus.ifEthash { ethash =>
8583
reportActive()
86-
blockchain.getBestBlock() match {
84+
blockchainReader.getBestBlock() match {
8785
case Some(block) =>
8886
Task.parZip2(getOmmersFromPool(block.hash), getTransactionsFromPool).map { case (ommers, pendingTxs) =>
8987
val blockGenerator = ethash.blockGenerator
@@ -114,7 +112,7 @@ class EthMiningService(
114112
reportActive()
115113
Task {
116114
ethash.blockGenerator.getPrepared(req.powHeaderHash) match {
117-
case Some(pendingBlock) if blockchain.getBestBlockNumber() <= pendingBlock.block.header.number =>
115+
case Some(pendingBlock) if blockchainReader.getBestBlockNumber() <= pendingBlock.block.header.number =>
118116
import pendingBlock._
119117
syncingController ! SyncProtocol.MinedBlock(
120118
block.copy(header = block.header.copy(nonce = req.nonce, mixHash = req.mixHash))

0 commit comments

Comments
 (0)