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