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.

481 lines
14 KiB

8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
  1. package blockchain
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. "time"
  7. amino "github.com/tendermint/go-amino"
  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 bcR.fastSync {
  90. err := bcR.pool.Start()
  91. if err != nil {
  92. return err
  93. }
  94. go bcR.poolRoutine()
  95. }
  96. return nil
  97. }
  98. // OnStop implements cmn.Service.
  99. func (bcR *BlockchainReactor) OnStop() {
  100. bcR.pool.Stop()
  101. }
  102. // GetChannels implements Reactor
  103. func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
  104. return []*p2p.ChannelDescriptor{
  105. {
  106. ID: BlockchainChannel,
  107. Priority: 10,
  108. SendQueueCapacity: 1000,
  109. RecvBufferCapacity: 50 * 4096,
  110. RecvMessageCapacity: maxMsgSize,
  111. },
  112. }
  113. }
  114. // AddPeer implements Reactor by sending our state to peer.
  115. func (bcR *BlockchainReactor) AddPeer(peer p2p.Peer) {
  116. msgBytes := cdc.MustMarshalBinaryBare(&bcStatusResponseMessage{bcR.store.Height()})
  117. if !peer.Send(BlockchainChannel, msgBytes) {
  118. // doing nothing, will try later in `poolRoutine`
  119. }
  120. // peer is added to the pool once we receive the first
  121. // bcStatusResponseMessage from the peer and call pool.SetPeerHeight
  122. }
  123. // RemovePeer implements Reactor by removing peer from the pool.
  124. func (bcR *BlockchainReactor) RemovePeer(peer p2p.Peer, reason interface{}) {
  125. bcR.pool.RemovePeer(peer.ID())
  126. }
  127. // respondToPeer loads a block and sends it to the requesting peer,
  128. // if we have it. Otherwise, we'll respond saying we don't have it.
  129. // According to the Tendermint spec, if all nodes are honest,
  130. // no node should be requesting for a block that's non-existent.
  131. func (bcR *BlockchainReactor) respondToPeer(msg *bcBlockRequestMessage,
  132. src p2p.Peer) (queued bool) {
  133. block := bcR.store.LoadBlock(msg.Height)
  134. if block != nil {
  135. msgBytes := cdc.MustMarshalBinaryBare(&bcBlockResponseMessage{Block: block})
  136. return src.TrySend(BlockchainChannel, msgBytes)
  137. }
  138. bcR.Logger.Info("Peer asking for a block we don't have", "src", src, "height", msg.Height)
  139. msgBytes := cdc.MustMarshalBinaryBare(&bcNoBlockResponseMessage{Height: msg.Height})
  140. return src.TrySend(BlockchainChannel, msgBytes)
  141. }
  142. // Receive implements Reactor by handling 4 types of messages (look below).
  143. func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) {
  144. msg, err := decodeMsg(msgBytes)
  145. if err != nil {
  146. bcR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes)
  147. bcR.Switch.StopPeerForError(src, err)
  148. return
  149. }
  150. if err = msg.ValidateBasic(); err != nil {
  151. bcR.Logger.Error("Peer sent us invalid msg", "peer", src, "msg", msg, "err", err)
  152. bcR.Switch.StopPeerForError(src, err)
  153. return
  154. }
  155. bcR.Logger.Debug("Receive", "src", src, "chID", chID, "msg", msg)
  156. switch msg := msg.(type) {
  157. case *bcBlockRequestMessage:
  158. if queued := bcR.respondToPeer(msg, src); !queued {
  159. // Unfortunately not queued since the queue is full.
  160. }
  161. case *bcBlockResponseMessage:
  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(fmt.Sprintf("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. go func() {
  190. for {
  191. select {
  192. case <-bcR.Quit():
  193. return
  194. case <-bcR.pool.Quit():
  195. return
  196. case request := <-bcR.requestsCh:
  197. peer := bcR.Switch.Peers().Get(request.PeerID)
  198. if peer == nil {
  199. continue
  200. }
  201. msgBytes := cdc.MustMarshalBinaryBare(&bcBlockRequestMessage{request.Height})
  202. queued := peer.TrySend(BlockchainChannel, msgBytes)
  203. if !queued {
  204. bcR.Logger.Debug("Send queue is full, drop block request", "peer", peer.ID(), "height", request.Height)
  205. }
  206. case err := <-bcR.errorsCh:
  207. peer := bcR.Switch.Peers().Get(err.peerID)
  208. if peer != nil {
  209. bcR.Switch.StopPeerForError(peer, err)
  210. }
  211. case <-statusUpdateTicker.C:
  212. // ask for status updates
  213. go bcR.BroadcastStatusRequest() // nolint: errcheck
  214. }
  215. }
  216. }()
  217. FOR_LOOP:
  218. for {
  219. select {
  220. case <-switchToConsensusTicker.C:
  221. height, numPending, lenRequesters := bcR.pool.GetStatus()
  222. outbound, inbound, _ := bcR.Switch.NumPeers()
  223. bcR.Logger.Debug("Consensus ticker", "numPending", numPending, "total", lenRequesters,
  224. "outbound", outbound, "inbound", inbound)
  225. if bcR.pool.IsCaughtUp() {
  226. bcR.Logger.Info("Time to switch to consensus reactor!", "height", height)
  227. bcR.pool.Stop()
  228. conR, ok := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  229. if ok {
  230. conR.SwitchToConsensus(state, blocksSynced)
  231. } else {
  232. // should only happen during testing
  233. }
  234. break FOR_LOOP
  235. }
  236. case <-trySyncTicker.C: // chan time
  237. select {
  238. case didProcessCh <- struct{}{}:
  239. default:
  240. }
  241. case <-didProcessCh:
  242. // NOTE: It is a subtle mistake to process more than a single block
  243. // at a time (e.g. 10) here, because we only TrySend 1 request per
  244. // loop. The ratio mismatch can result in starving of blocks, a
  245. // sudden burst of requests and responses, and repeat.
  246. // Consequently, it is better to split these routines rather than
  247. // coupling them as it's written here. TODO uncouple from request
  248. // routine.
  249. // See if there are any blocks to sync.
  250. first, second := bcR.pool.PeekTwoBlocks()
  251. //bcR.Logger.Info("TrySync peeked", "first", first, "second", second)
  252. if first == nil || second == nil {
  253. // We need both to sync the first block.
  254. continue FOR_LOOP
  255. } else {
  256. // Try again quickly next loop.
  257. didProcessCh <- struct{}{}
  258. }
  259. firstParts := first.MakePartSet(types.BlockPartSizeBytes)
  260. firstPartsHeader := firstParts.Header()
  261. firstID := types.BlockID{Hash: first.Hash(), PartsHeader: firstPartsHeader}
  262. // Finally, verify the first block using the second's commit
  263. // NOTE: we can probably make this more efficient, but note that calling
  264. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  265. // currently necessary.
  266. err := state.Validators.VerifyCommit(
  267. chainID, firstID, first.Height, second.LastCommit)
  268. if err != nil {
  269. bcR.Logger.Error("Error in validation", "err", err)
  270. peerID := bcR.pool.RedoRequest(first.Height)
  271. peer := bcR.Switch.Peers().Get(peerID)
  272. if peer != nil {
  273. // NOTE: we've already removed the peer's request, but we
  274. // still need to clean up the rest.
  275. bcR.Switch.StopPeerForError(peer, fmt.Errorf("BlockchainReactor validation error: %v", err))
  276. }
  277. peerID2 := bcR.pool.RedoRequest(second.Height)
  278. peer2 := bcR.Switch.Peers().Get(peerID2)
  279. if peer2 != nil && peer2 != peer {
  280. // NOTE: we've already removed the peer's request, but we
  281. // still need to clean up the rest.
  282. bcR.Switch.StopPeerForError(peer2, fmt.Errorf("BlockchainReactor validation error: %v", err))
  283. }
  284. continue FOR_LOOP
  285. } else {
  286. bcR.pool.PopRequest()
  287. // TODO: batch saves so we dont persist to disk every block
  288. bcR.store.SaveBlock(first, firstParts, second.LastCommit)
  289. // TODO: same thing for app - but we would need a way to
  290. // get the hash without persisting the state
  291. var err error
  292. state, err = bcR.blockExec.ApplyBlock(state, firstID, first)
  293. if err != nil {
  294. // TODO This is bad, are we zombie?
  295. panic(fmt.Sprintf("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  296. }
  297. blocksSynced++
  298. if blocksSynced%100 == 0 {
  299. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  300. bcR.Logger.Info("Fast Sync Rate", "height", bcR.pool.height,
  301. "max_peer_height", bcR.pool.MaxPeerHeight(), "blocks/s", lastRate)
  302. lastHundred = time.Now()
  303. }
  304. }
  305. continue FOR_LOOP
  306. case <-bcR.Quit():
  307. break FOR_LOOP
  308. }
  309. }
  310. }
  311. // BroadcastStatusRequest broadcasts `BlockStore` height.
  312. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  313. msgBytes := cdc.MustMarshalBinaryBare(&bcStatusRequestMessage{bcR.store.Height()})
  314. bcR.Switch.Broadcast(BlockchainChannel, msgBytes)
  315. return nil
  316. }
  317. //-----------------------------------------------------------------------------
  318. // Messages
  319. // BlockchainMessage is a generic message for this reactor.
  320. type BlockchainMessage interface {
  321. ValidateBasic() error
  322. }
  323. func RegisterBlockchainMessages(cdc *amino.Codec) {
  324. cdc.RegisterInterface((*BlockchainMessage)(nil), nil)
  325. cdc.RegisterConcrete(&bcBlockRequestMessage{}, "tendermint/blockchain/BlockRequest", nil)
  326. cdc.RegisterConcrete(&bcBlockResponseMessage{}, "tendermint/blockchain/BlockResponse", nil)
  327. cdc.RegisterConcrete(&bcNoBlockResponseMessage{}, "tendermint/blockchain/NoBlockResponse", nil)
  328. cdc.RegisterConcrete(&bcStatusResponseMessage{}, "tendermint/blockchain/StatusResponse", nil)
  329. cdc.RegisterConcrete(&bcStatusRequestMessage{}, "tendermint/blockchain/StatusRequest", nil)
  330. }
  331. func decodeMsg(bz []byte) (msg BlockchainMessage, err error) {
  332. if len(bz) > maxMsgSize {
  333. return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize)
  334. }
  335. err = cdc.UnmarshalBinaryBare(bz, &msg)
  336. return
  337. }
  338. //-------------------------------------
  339. type bcBlockRequestMessage struct {
  340. Height int64
  341. }
  342. // ValidateBasic performs basic validation.
  343. func (m *bcBlockRequestMessage) ValidateBasic() error {
  344. if m.Height < 0 {
  345. return errors.New("Negative Height")
  346. }
  347. return nil
  348. }
  349. func (m *bcBlockRequestMessage) String() string {
  350. return fmt.Sprintf("[bcBlockRequestMessage %v]", m.Height)
  351. }
  352. type bcNoBlockResponseMessage struct {
  353. Height int64
  354. }
  355. // ValidateBasic performs basic validation.
  356. func (m *bcNoBlockResponseMessage) ValidateBasic() error {
  357. if m.Height < 0 {
  358. return errors.New("Negative Height")
  359. }
  360. return nil
  361. }
  362. func (brm *bcNoBlockResponseMessage) String() string {
  363. return fmt.Sprintf("[bcNoBlockResponseMessage %d]", brm.Height)
  364. }
  365. //-------------------------------------
  366. type bcBlockResponseMessage struct {
  367. Block *types.Block
  368. }
  369. // ValidateBasic performs basic validation.
  370. func (m *bcBlockResponseMessage) ValidateBasic() error {
  371. return m.Block.ValidateBasic()
  372. }
  373. func (m *bcBlockResponseMessage) String() string {
  374. return fmt.Sprintf("[bcBlockResponseMessage %v]", m.Block.Height)
  375. }
  376. //-------------------------------------
  377. type bcStatusRequestMessage struct {
  378. Height int64
  379. }
  380. // ValidateBasic performs basic validation.
  381. func (m *bcStatusRequestMessage) ValidateBasic() error {
  382. if m.Height < 0 {
  383. return errors.New("Negative Height")
  384. }
  385. return nil
  386. }
  387. func (m *bcStatusRequestMessage) String() string {
  388. return fmt.Sprintf("[bcStatusRequestMessage %v]", m.Height)
  389. }
  390. //-------------------------------------
  391. type bcStatusResponseMessage struct {
  392. Height int64
  393. }
  394. // ValidateBasic performs basic validation.
  395. func (m *bcStatusResponseMessage) ValidateBasic() error {
  396. if m.Height < 0 {
  397. return errors.New("Negative Height")
  398. }
  399. return nil
  400. }
  401. func (m *bcStatusResponseMessage) String() string {
  402. return fmt.Sprintf("[bcStatusResponseMessage %v]", m.Height)
  403. }