-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathRegularSync.scala
More file actions
259 lines (235 loc) · 8.61 KB
/
RegularSync.scala
File metadata and controls
259 lines (235 loc) · 8.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package io.iohk.ethereum.blockchain.sync.regular
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.AllForOneStrategy
import akka.actor.Cancellable
import akka.actor.Props
import akka.actor.Scheduler
import akka.actor.SupervisorStrategy
import akka.actor.typed.scaladsl.adapter._
import akka.actor.typed.{ActorRef => TypedActorRef}
import akka.stream.OverflowStrategy
import akka.stream.scaladsl.Flow
import akka.stream.scaladsl.Sink
import akka.stream.scaladsl.Source
import akka.util.ByteString
import cats.data.NonEmptyList
import scala.annotation.tailrec
import scala.collection.immutable.Queue
import scala.concurrent.ExecutionContext
import io.iohk.ethereum.blockchain.sync.Blacklist
import io.iohk.ethereum.blockchain.sync.SyncProtocol
import io.iohk.ethereum.blockchain.sync.SyncProtocol.Status
import io.iohk.ethereum.blockchain.sync.SyncProtocol.Status.Progress
import io.iohk.ethereum.blockchain.sync.regular.BlockFetcher.InternalLastBlockImport
import io.iohk.ethereum.blockchain.sync.regular.RegularSync.NewCheckpoint
import io.iohk.ethereum.blockchain.sync.regular.RegularSync.ProgressProtocol
import io.iohk.ethereum.blockchain.sync.regular.RegularSync.ProgressState
import io.iohk.ethereum.consensus.ConsensusAdapter
import io.iohk.ethereum.consensus.validators.BlockValidator
import io.iohk.ethereum.db.storage.StateStorage
import io.iohk.ethereum.domain.Block
import io.iohk.ethereum.domain.BlockchainReader
import io.iohk.ethereum.domain.branch.BestBranch
import io.iohk.ethereum.domain.branch.Branch
import io.iohk.ethereum.ledger.BranchResolution
import io.iohk.ethereum.network.EtcPeerManagerActor
import io.iohk.ethereum.network.Peer
import io.iohk.ethereum.network.PeerEventBusActor
import io.iohk.ethereum.network.p2p.messages.Codes
import io.iohk.ethereum.network.p2p.messages.ETH62
import io.iohk.ethereum.nodebuilder.BlockchainConfigBuilder
import io.iohk.ethereum.utils.ByteStringUtils
import io.iohk.ethereum.utils.Config.SyncConfig
class RegularSync(
peersClient: ActorRef,
etcPeerManager: ActorRef,
peerEventBus: ActorRef,
consensus: ConsensusAdapter,
blockchainReader: BlockchainReader,
stateStorage: StateStorage,
branchResolution: BranchResolution,
blockValidator: BlockValidator,
blacklist: Blacklist,
syncConfig: SyncConfig,
ommersPool: ActorRef,
pendingTransactionsManager: ActorRef,
scheduler: Scheduler,
configBuilder: BlockchainConfigBuilder,
newFlow: Boolean
) extends Actor
with ActorLogging {
val fetcher: TypedActorRef[BlockFetcher.FetchCommand] =
context.spawn(
BlockFetcher(peersClient, peerEventBus, self, syncConfig, blockValidator, newFlow),
"block-fetcher"
)
context.watch(fetcher)
val broadcaster: ActorRef = context.actorOf(
BlockBroadcasterActor
.props(new BlockBroadcast(etcPeerManager), peerEventBus, etcPeerManager, blacklist, syncConfig, scheduler),
"block-broadcaster"
)
val importer: ActorRef =
context.actorOf(
BlockImporter.props(
fetcher.toClassic,
consensus,
blockchainReader,
stateStorage,
branchResolution,
syncConfig,
ommersPool,
broadcaster,
pendingTransactionsManager,
self,
configBuilder
),
"block-importer"
)
implicit val system: ActorSystem = context.system
implicit val ec: ExecutionContext = context.dispatcher
val printFetcherSchedule: Cancellable =
scheduler.scheduleWithFixedDelay(
syncConfig.printStatusInterval,
syncConfig.printStatusInterval,
fetcher.toClassic,
BlockFetcher.PrintStatus
)
val (blockSourceQueue, blockSource) = Source.queue[Block](256, OverflowStrategy.fail).preMaterialize()
val fetcherService = new FetcherService(blockchainReader, syncConfig, blockSourceQueue)
override def receive: Receive = running(
ProgressState(startedFetching = false, initialBlock = 0, currentBlock = 0, bestKnownNetworkBlock = 0)
)
private def startTemporaryBlockProducer() = {
import monix.execution.Scheduler.Implicits.global
PeerEventBusActor
.messageSource(
peerEventBus,
PeerEventBusActor.SubscriptionClassifier
.MessageClassifier(
Set(Codes.BlockBodiesCode, Codes.BlockHeadersCode),
PeerEventBusActor.PeerSelector.AllPeers
)
)
.via(FetcherService.tempFlow)
.buffer(256, OverflowStrategy.fail)
.mapConcat(identity)
.runWith(Sink.foreachAsync(1) { block =>
fetcherService
.placeBlockInPeerStream(block)
.runToFuture
.collect { case Right(()) => () }
})
}
private def startNewFlow() =
blockSource
.via(BranchBuffer.flow(blockchainReader))
.runWith(Sink.foreach { blocks =>
importer ! BlockFetcher.PickedBlocks(blocks)
})
.onComplete(res => log.error(res.toString))
def running(progressState: ProgressState): Receive = {
case SyncProtocol.Start =>
log.info("Starting regular sync")
importer ! BlockImporter.Start
if (newFlow) {
startNewFlow()
startTemporaryBlockProducer()
}
case SyncProtocol.MinedBlock(block) =>
log.info(s"Block mined [number = {}, hash = {}]", block.number, block.header.hashAsHexString)
importer ! BlockImporter.MinedBlock(block)
case NewCheckpoint(block) =>
log.info(s"Received new checkpoint for block ${ByteStringUtils.hash2string(block.header.parentHash)}")
importer ! BlockImporter.NewCheckpoint(block)
case SyncProtocol.GetStatus =>
sender() ! progressState.toStatus
case ProgressProtocol.StartedFetching =>
val newState = progressState.copy(startedFetching = true)
context.become(running(newState))
case ProgressProtocol.StartingFrom(blockNumber) =>
val newState = progressState.copy(initialBlock = blockNumber, currentBlock = blockNumber)
context.become(running(newState))
case ProgressProtocol.GotNewBlock(blockNumber) =>
log.info(s"Got information about new block [number = $blockNumber]")
val newState = progressState.copy(bestKnownNetworkBlock = blockNumber)
context.become(running(newState))
case ProgressProtocol.ImportedBlock(blockNumber, internally) =>
log.info(s"Imported new block [number = $blockNumber, internally = $internally]")
val newState = progressState.copy(currentBlock = blockNumber)
if (internally) {
fetcher ! InternalLastBlockImport(blockNumber)
}
context.become(running(newState))
}
override def supervisorStrategy: SupervisorStrategy = AllForOneStrategy()(SupervisorStrategy.defaultDecider)
override def postStop(): Unit = {
log.info("Regular Sync stopped")
printFetcherSchedule.cancel()
}
}
object RegularSync {
// scalastyle:off parameter.number
def props(
peersClient: ActorRef,
etcPeerManager: ActorRef,
peerEventBus: ActorRef,
consensus: ConsensusAdapter,
blockchainReader: BlockchainReader,
stateStorage: StateStorage,
branchResolution: BranchResolution,
blockValidator: BlockValidator,
blacklist: Blacklist,
syncConfig: SyncConfig,
ommersPool: ActorRef,
pendingTransactionsManager: ActorRef,
scheduler: Scheduler,
configBuilder: BlockchainConfigBuilder,
newFlow: Boolean
): Props =
Props(
new RegularSync(
peersClient,
etcPeerManager,
peerEventBus,
consensus,
blockchainReader,
stateStorage,
branchResolution,
blockValidator,
blacklist,
syncConfig,
ommersPool,
pendingTransactionsManager,
scheduler,
configBuilder,
newFlow
)
)
case class NewCheckpoint(block: Block)
case class ProgressState(
startedFetching: Boolean,
initialBlock: BigInt,
currentBlock: BigInt,
bestKnownNetworkBlock: BigInt
) {
def toStatus: SyncProtocol.Status =
if (startedFetching && bestKnownNetworkBlock != 0 && currentBlock < bestKnownNetworkBlock) {
Status.Syncing(initialBlock, Progress(currentBlock, bestKnownNetworkBlock), None)
} else if (startedFetching && currentBlock >= bestKnownNetworkBlock) {
Status.SyncDone
} else {
Status.NotSyncing
}
}
sealed trait ProgressProtocol
object ProgressProtocol {
case object StartedFetching extends ProgressProtocol
case class StartingFrom(blockNumber: BigInt) extends ProgressProtocol
case class GotNewBlock(blockNumber: BigInt) extends ProgressProtocol
case class ImportedBlock(blockNumber: BigInt, internally: Boolean) extends ProgressProtocol
}
}