Skip to content

Fixed concurrency issue that allowed multiple miners instantiation. #909

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 2 commits into from
Jan 29, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package io.iohk.ethereum
package consensus
package ethash

import java.util.concurrent.atomic.AtomicReference
import akka.actor.ActorRef
import akka.util.Timeout
import io.iohk.ethereum.consensus.Protocol._
Expand Down Expand Up @@ -48,34 +47,39 @@ class EthashConsensus private (
blockchainConfig = blockchainConfig
)

private[this] val atomicMiner = new AtomicReference[Option[ActorRef]](None)
@volatile private[this] var minerRef: Option[ActorRef] = None

private implicit val timeout: Timeout = 5.seconds

override def sendMiner(msg: MinerProtocol): Unit = {
atomicMiner
.get()
.foreach(_ ! msg)
}
override def sendMiner(msg: MinerProtocol): Unit =
minerRef.foreach(_ ! msg)

override def askMiner(msg: MinerProtocol): Task[MinerResponse] = {
atomicMiner
.get()
minerRef
.map(_.askFor[MinerResponse](msg))
.getOrElse(Task.now(MinerNotExist))
}

private[this] val mutex = new Object

/*
* guarantees one miner instance
* this should not use a atomic* construct as it has side-effects
*
* TODO further refactors should focus on extracting two types - one with a miner, one without - based on the config
*/
private[this] def startMiningProcess(node: Node): Unit = {
atomicMiner.get() match {
case None =>
val miner = config.generic.protocol match {
case Ethash | RestrictedEthash => EthashMiner(node)
case MockedPow => MockedMiner(node)
if (minerRef.isEmpty) {
mutex.synchronized {
if (minerRef.isEmpty) {
val miner = config.generic.protocol match {
case Ethash | RestrictedEthash => EthashMiner(node)
case MockedPow => MockedMiner(node)
}
minerRef = Some(miner)
sendMiner(MinerProtocol.StartMining)
}
atomicMiner.set(Some(miner))
sendMiner(MinerProtocol.StartMining)

case _ =>
}
}
}

Expand Down