github.com/line/ostracon@v1.0.10-0.20230328032236-7f20145f065d/blockchain/v0/reactor.go (about) 1 package v0 2 3 import ( 4 "fmt" 5 "reflect" 6 "time" 7 8 bcproto "github.com/tendermint/tendermint/proto/tendermint/blockchain" 9 10 bc "github.com/line/ostracon/blockchain" 11 "github.com/line/ostracon/libs/log" 12 "github.com/line/ostracon/p2p" 13 ocbcproto "github.com/line/ostracon/proto/ostracon/blockchain" 14 sm "github.com/line/ostracon/state" 15 "github.com/line/ostracon/store" 16 "github.com/line/ostracon/types" 17 ) 18 19 const ( 20 // BlockchainChannel is a channel for blocks and status updates (`BlockStore` height) 21 BlockchainChannel = byte(0x40) 22 23 trySyncIntervalMS = 10 24 25 // stop syncing when last block's time is 26 // within this much of the system time. 27 // stopSyncingDurationMinutes = 10 28 29 // ask for best height every 10s 30 statusUpdateIntervalSeconds = 10 31 // check if we should switch to consensus reactor 32 switchToConsensusIntervalSeconds = 1 33 ) 34 35 type consensusReactor interface { 36 // for when we switch from blockchain reactor and fast sync to 37 // the consensus machine 38 SwitchToConsensus(state sm.State, skipWAL bool) 39 } 40 41 type peerError struct { 42 err error 43 peerID p2p.ID 44 } 45 46 func (e peerError) Error() string { 47 return fmt.Sprintf("error with peer %v: %s", e.peerID, e.err.Error()) 48 } 49 50 // BlockchainReactor handles long-term catchup syncing. 51 type BlockchainReactor struct { 52 p2p.BaseReactor 53 54 // immutable 55 initialState sm.State 56 57 blockExec *sm.BlockExecutor 58 store *store.BlockStore 59 pool *BlockPool 60 fastSync bool 61 62 requestsCh <-chan BlockRequest 63 errorsCh <-chan peerError 64 } 65 66 // NewBlockchainReactor returns new reactor instance. 67 func NewBlockchainReactor(state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore, 68 fastSync bool, async bool, recvBufSize int) *BlockchainReactor { 69 70 if state.LastBlockHeight != store.Height() { 71 panic(fmt.Sprintf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, 72 store.Height())) 73 } 74 75 requestsCh := make(chan BlockRequest, maxTotalRequesters) 76 77 const capacity = 1000 // must be bigger than peers count 78 errorsCh := make(chan peerError, capacity) // so we don't block in #Receive#pool.AddBlock 79 80 startHeight := store.Height() + 1 81 if startHeight == 1 { 82 startHeight = state.InitialHeight 83 } 84 pool := NewBlockPool(startHeight, requestsCh, errorsCh) 85 86 bcR := &BlockchainReactor{ 87 initialState: state, 88 blockExec: blockExec, 89 store: store, 90 pool: pool, 91 fastSync: fastSync, 92 requestsCh: requestsCh, 93 errorsCh: errorsCh, 94 } 95 bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR, async, recvBufSize) 96 return bcR 97 } 98 99 // SetLogger implements service.Service by setting the logger on reactor and pool. 100 func (bcR *BlockchainReactor) SetLogger(l log.Logger) { 101 bcR.BaseService.Logger = l 102 bcR.pool.Logger = l 103 } 104 105 // OnStart implements service.Service. 106 func (bcR *BlockchainReactor) OnStart() error { 107 // call BaseReactor's OnStart() 108 err := bcR.BaseReactor.OnStart() 109 if err != nil { 110 return err 111 } 112 113 if bcR.fastSync { 114 err = bcR.pool.Start() 115 if err != nil { 116 return err 117 } 118 go bcR.poolRoutine(false) 119 } 120 return nil 121 } 122 123 // SwitchToFastSync is called by the state sync reactor when switching to fast sync. 124 func (bcR *BlockchainReactor) SwitchToFastSync(state sm.State) error { 125 bcR.fastSync = true 126 bcR.initialState = state 127 128 bcR.pool.height = state.LastBlockHeight + 1 129 err := bcR.pool.Start() 130 if err != nil { 131 return err 132 } 133 go bcR.poolRoutine(true) 134 return nil 135 } 136 137 // OnStop implements service.Service. 138 func (bcR *BlockchainReactor) OnStop() { 139 if bcR.fastSync { 140 if err := bcR.pool.Stop(); err != nil { 141 bcR.Logger.Error("Error stopping pool", "err", err) 142 } 143 } 144 } 145 146 // GetChannels implements Reactor 147 func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor { 148 return []*p2p.ChannelDescriptor{ 149 { 150 ID: BlockchainChannel, 151 Priority: 5, 152 SendQueueCapacity: 1000, 153 RecvBufferCapacity: 50 * 4096, 154 RecvMessageCapacity: bc.MaxMsgSize, 155 }, 156 } 157 } 158 159 // AddPeer implements Reactor by sending our state to peer. 160 func (bcR *BlockchainReactor) AddPeer(peer p2p.Peer) { 161 msgBytes, err := bc.EncodeMsg(&bcproto.StatusResponse{ 162 Base: bcR.store.Base(), 163 Height: bcR.store.Height()}) 164 if err != nil { 165 bcR.Logger.Error("could not convert msg to protobuf", "err", err) 166 return 167 } 168 169 peer.Send(BlockchainChannel, msgBytes) 170 // it's OK if send fails. will try later in poolRoutine 171 172 // peer is added to the pool once we receive the first 173 // bcStatusResponseMessage from the peer and call pool.SetPeerRange 174 } 175 176 // RemovePeer implements Reactor by removing peer from the pool. 177 func (bcR *BlockchainReactor) RemovePeer(peer p2p.Peer, reason interface{}) { 178 bcR.pool.RemovePeer(peer.ID()) 179 } 180 181 // respondToPeer loads a block and sends it to the requesting peer, 182 // if we have it. Otherwise, we'll respond saying we don't have it. 183 func (bcR *BlockchainReactor) respondToPeer(msg *bcproto.BlockRequest, 184 src p2p.Peer) (queued bool) { 185 186 block := bcR.store.LoadBlock(msg.Height) 187 if block != nil { 188 bl, err := block.ToProto() 189 if err != nil { 190 bcR.Logger.Error("could not convert msg to protobuf", "err", err) 191 return false 192 } 193 194 msgBytes, err := bc.EncodeMsg(&ocbcproto.BlockResponse{Block: bl}) 195 if err != nil { 196 bcR.Logger.Error("could not marshal msg", "err", err) 197 return false 198 } 199 200 return src.TrySend(BlockchainChannel, msgBytes) 201 } 202 203 bcR.Logger.Info("Peer asking for a block we don't have", "src", src, "height", msg.Height) 204 205 msgBytes, err := bc.EncodeMsg(&bcproto.NoBlockResponse{Height: msg.Height}) 206 if err != nil { 207 bcR.Logger.Error("could not convert msg to protobuf", "err", err) 208 return false 209 } 210 211 return src.TrySend(BlockchainChannel, msgBytes) 212 } 213 214 // Receive implements Reactor by handling 4 types of messages (look below). 215 func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) { 216 msg, err := bc.DecodeMsg(msgBytes) 217 if err != nil { 218 bcR.Logger.Error("Error decoding message", "src", src, "chId", chID, "err", err) 219 bcR.Switch.StopPeerForError(src, err) 220 return 221 } 222 223 if err = bc.ValidateMsg(msg); err != nil { 224 bcR.Logger.Error("Peer sent us invalid msg", "peer", src, "msg", msg, "err", err) 225 bcR.Switch.StopPeerForError(src, err) 226 return 227 } 228 229 bcR.Logger.Debug("Receive", "src", src, "chID", chID, "msg", msg) 230 231 switch msg := msg.(type) { 232 case *bcproto.BlockRequest: 233 bcR.respondToPeer(msg, src) 234 case *ocbcproto.BlockResponse: 235 bi, err := types.BlockFromProto(msg.Block) 236 if err != nil { 237 bcR.Logger.Error("Block content is invalid", "err", err) 238 return 239 } 240 bcR.pool.AddBlock(src.ID(), bi, len(msgBytes)) 241 case *bcproto.StatusRequest: 242 // Send peer our state. 243 msgBytes, err := bc.EncodeMsg(&bcproto.StatusResponse{ 244 Height: bcR.store.Height(), 245 Base: bcR.store.Base(), 246 }) 247 if err != nil { 248 bcR.Logger.Error("could not convert msg to protobut", "err", err) 249 return 250 } 251 src.TrySend(BlockchainChannel, msgBytes) 252 case *bcproto.StatusResponse: 253 // Got a peer status. Unverified. 254 bcR.pool.SetPeerRange(src.ID(), msg.Base, msg.Height) 255 case *bcproto.NoBlockResponse: 256 bcR.Logger.Debug("Peer does not have requested block", "peer", src, "height", msg.Height) 257 default: 258 bcR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) 259 } 260 } 261 262 // Handle messages from the poolReactor telling the reactor what to do. 263 // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down! 264 func (bcR *BlockchainReactor) poolRoutine(stateSynced bool) { 265 266 trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond) 267 defer trySyncTicker.Stop() 268 269 statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second) 270 defer statusUpdateTicker.Stop() 271 272 switchToConsensusTicker := time.NewTicker(switchToConsensusIntervalSeconds * time.Second) 273 defer switchToConsensusTicker.Stop() 274 275 blocksSynced := uint64(0) 276 277 chainID := bcR.initialState.ChainID 278 state := bcR.initialState 279 280 lastHundred := time.Now() 281 lastRate := 0.0 282 283 didProcessCh := make(chan struct{}, 1) 284 285 go func() { 286 for { 287 select { 288 case <-bcR.Quit(): 289 return 290 case <-bcR.pool.Quit(): 291 return 292 case request := <-bcR.requestsCh: 293 peer := bcR.Switch.Peers().Get(request.PeerID) 294 if peer == nil { 295 continue 296 } 297 msgBytes, err := bc.EncodeMsg(&bcproto.BlockRequest{Height: request.Height}) 298 if err != nil { 299 bcR.Logger.Error("could not convert msg to proto", "err", err) 300 continue 301 } 302 303 queued := peer.TrySend(BlockchainChannel, msgBytes) 304 if !queued { 305 bcR.Logger.Debug("Send queue is full, drop block request", "peer", peer.ID(), "height", request.Height) 306 } 307 case err := <-bcR.errorsCh: 308 peer := bcR.Switch.Peers().Get(err.peerID) 309 if peer != nil { 310 bcR.Switch.StopPeerForError(peer, err) 311 } 312 313 case <-statusUpdateTicker.C: 314 // ask for status updates 315 go bcR.BroadcastStatusRequest() // nolint: errcheck 316 317 } 318 } 319 }() 320 321 FOR_LOOP: 322 for { 323 select { 324 case <-switchToConsensusTicker.C: 325 height, numPending, lenRequesters := bcR.pool.GetStatus() 326 outbound, inbound, _ := bcR.Switch.NumPeers() 327 bcR.Logger.Debug("Consensus ticker", "numPending", numPending, "total", lenRequesters, 328 "outbound", outbound, "inbound", inbound) 329 if bcR.pool.IsCaughtUp() { 330 bcR.Logger.Info("Time to switch to consensus reactor!", "height", height) 331 if err := bcR.pool.Stop(); err != nil { 332 bcR.Logger.Error("Error stopping pool", "err", err) 333 } 334 conR, ok := bcR.Switch.Reactor("CONSENSUS").(consensusReactor) 335 if ok { 336 conR.SwitchToConsensus(state, blocksSynced > 0 || stateSynced) 337 } 338 // else { 339 // should only happen during testing 340 // } 341 342 break FOR_LOOP 343 } 344 345 case <-trySyncTicker.C: // chan time 346 select { 347 case didProcessCh <- struct{}{}: 348 default: 349 } 350 351 case <-didProcessCh: 352 // NOTE: It is a subtle mistake to process more than a single block 353 // at a time (e.g. 10) here, because we only TrySend 1 request per 354 // loop. The ratio mismatch can result in starving of blocks, a 355 // sudden burst of requests and responses, and repeat. 356 // Consequently, it is better to split these routines rather than 357 // coupling them as it's written here. TODO uncouple from request 358 // routine. 359 360 // See if there are any blocks to sync. 361 first, second := bcR.pool.PeekTwoBlocks() 362 // bcR.Logger.Info("TrySync peeked", "first", first, "second", second) 363 if first == nil || second == nil { 364 // We need both to sync the first block. 365 continue FOR_LOOP 366 } else { 367 // Try again quickly next loop. 368 didProcessCh <- struct{}{} 369 } 370 371 firstParts := first.MakePartSet(types.BlockPartSizeBytes) 372 firstPartSetHeader := firstParts.Header() 373 firstID := types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader} 374 // Finally, verify the first block using the second's commit 375 // NOTE: we can probably make this more efficient, but note that calling 376 // first.Hash() doesn't verify the tx contents, so MakePartSet() is 377 // currently necessary. 378 err := state.Validators.VerifyCommitLight(chainID, firstID, first.Height, second.LastCommit) 379 if err == nil { 380 // validate the block before we persist it 381 err = bcR.blockExec.ValidateBlock(state, first.Round, first) 382 } 383 384 // If either of the checks failed we log the error and request for a new block 385 // at that height 386 if err != nil { 387 bcR.Logger.Error("Error in validation", "err", err) 388 peerID := bcR.pool.RedoRequest(first.Height) 389 peer := bcR.Switch.Peers().Get(peerID) 390 if peer != nil { 391 // NOTE: we've already removed the peer's request, but we 392 // still need to clean up the rest. 393 bcR.Switch.StopPeerForError(peer, fmt.Errorf("blockchainReactor validation error: %v", err)) 394 } 395 peerID2 := bcR.pool.RedoRequest(second.Height) 396 peer2 := bcR.Switch.Peers().Get(peerID2) 397 if peer2 != nil && peer2 != peer { 398 // NOTE: we've already removed the peer's request, but we 399 // still need to clean up the rest. 400 bcR.Switch.StopPeerForError(peer2, fmt.Errorf("blockchainReactor validation error: %v", err)) 401 } 402 continue FOR_LOOP 403 } else { 404 bcR.pool.PopRequest() 405 406 // TODO: batch saves so we dont persist to disk every block 407 bcR.store.SaveBlock(first, firstParts, second.LastCommit) 408 409 // TODO: same thing for app - but we would need a way to 410 // get the hash without persisting the state 411 var err error 412 state, _, err = bcR.blockExec.ApplyBlock(state, firstID, first, nil) 413 if err != nil { 414 // TODO This is bad, are we zombie? 415 panic(fmt.Sprintf("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err)) 416 } 417 blocksSynced++ 418 419 if blocksSynced%100 == 0 { 420 lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds()) 421 bcR.Logger.Info("Fast Sync Rate", "height", bcR.pool.height, 422 "max_peer_height", bcR.pool.MaxPeerHeight(), "blocks/s", lastRate) 423 lastHundred = time.Now() 424 } 425 } 426 continue FOR_LOOP 427 428 case <-bcR.Quit(): 429 break FOR_LOOP 430 } 431 } 432 } 433 434 // BroadcastStatusRequest broadcasts `BlockStore` base and height. 435 func (bcR *BlockchainReactor) BroadcastStatusRequest() error { 436 bm, err := bc.EncodeMsg(&bcproto.StatusRequest{}) 437 if err != nil { 438 bcR.Logger.Error("could not convert msg to proto", "err", err) 439 return fmt.Errorf("could not convert msg to proto: %w", err) 440 } 441 442 bcR.Switch.Broadcast(BlockchainChannel, bm) 443 444 return nil 445 }