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.

417 lines
12 KiB

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