You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

424 lines
13 KiB

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