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.

474 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. 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, ok := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  221. if ok {
  222. conR.SwitchToConsensus(state, blocksSynced)
  223. } else {
  224. // should only happen during testing
  225. }
  226. break FOR_LOOP
  227. }
  228. case <-trySyncTicker.C: // chan time
  229. select {
  230. case didProcessCh <- struct{}{}:
  231. default:
  232. }
  233. case <-didProcessCh:
  234. // NOTE: It is a subtle mistake to process more than a single block
  235. // at a time (e.g. 10) here, because we only TrySend 1 request per
  236. // loop. The ratio mismatch can result in starving of blocks, a
  237. // sudden burst of requests and responses, and repeat.
  238. // Consequently, it is better to split these routines rather than
  239. // coupling them as it's written here. TODO uncouple from request
  240. // routine.
  241. // See if there are any blocks to sync.
  242. first, second := bcR.pool.PeekTwoBlocks()
  243. //bcR.Logger.Info("TrySync peeked", "first", first, "second", second)
  244. if first == nil || second == nil {
  245. // We need both to sync the first block.
  246. continue FOR_LOOP
  247. } else {
  248. // Try again quickly next loop.
  249. didProcessCh <- struct{}{}
  250. }
  251. firstParts := first.MakePartSet(types.BlockPartSizeBytes)
  252. firstPartsHeader := firstParts.Header()
  253. firstID := types.BlockID{Hash: first.Hash(), PartsHeader: firstPartsHeader}
  254. // Finally, verify the first block using the second's commit
  255. // NOTE: we can probably make this more efficient, but note that calling
  256. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  257. // currently necessary.
  258. err := state.Validators.VerifyCommit(
  259. chainID, firstID, first.Height, second.LastCommit)
  260. if err != nil {
  261. bcR.Logger.Error("Error in validation", "err", err)
  262. peerID := bcR.pool.RedoRequest(first.Height)
  263. peer := bcR.Switch.Peers().Get(peerID)
  264. if peer != nil {
  265. // NOTE: we've already removed the peer's request, but we
  266. // still need to clean up the rest.
  267. bcR.Switch.StopPeerForError(peer, fmt.Errorf("BlockchainReactor validation error: %v", err))
  268. }
  269. peerID2 := bcR.pool.RedoRequest(second.Height)
  270. peer2 := bcR.Switch.Peers().Get(peerID2)
  271. if peer2 != nil && peer2 != peer {
  272. // NOTE: we've already removed the peer's request, but we
  273. // still need to clean up the rest.
  274. bcR.Switch.StopPeerForError(peer2, fmt.Errorf("BlockchainReactor validation error: %v", err))
  275. }
  276. continue FOR_LOOP
  277. } else {
  278. bcR.pool.PopRequest()
  279. // TODO: batch saves so we dont persist to disk every block
  280. bcR.store.SaveBlock(first, firstParts, second.LastCommit)
  281. // TODO: same thing for app - but we would need a way to
  282. // get the hash without persisting the state
  283. var err error
  284. state, err = bcR.blockExec.ApplyBlock(state, firstID, first)
  285. if err != nil {
  286. // TODO This is bad, are we zombie?
  287. panic(fmt.Sprintf("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  288. }
  289. blocksSynced++
  290. if blocksSynced%100 == 0 {
  291. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  292. bcR.Logger.Info("Fast Sync Rate", "height", bcR.pool.height,
  293. "max_peer_height", bcR.pool.MaxPeerHeight(), "blocks/s", lastRate)
  294. lastHundred = time.Now()
  295. }
  296. }
  297. continue FOR_LOOP
  298. case <-bcR.Quit():
  299. break FOR_LOOP
  300. }
  301. }
  302. }
  303. // BroadcastStatusRequest broadcasts `BlockStore` height.
  304. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  305. msgBytes := cdc.MustMarshalBinaryBare(&bcStatusRequestMessage{bcR.store.Height()})
  306. bcR.Switch.Broadcast(BlockchainChannel, msgBytes)
  307. return nil
  308. }
  309. //-----------------------------------------------------------------------------
  310. // Messages
  311. // BlockchainMessage is a generic message for this reactor.
  312. type BlockchainMessage interface {
  313. ValidateBasic() error
  314. }
  315. func RegisterBlockchainMessages(cdc *amino.Codec) {
  316. cdc.RegisterInterface((*BlockchainMessage)(nil), nil)
  317. cdc.RegisterConcrete(&bcBlockRequestMessage{}, "tendermint/blockchain/BlockRequest", nil)
  318. cdc.RegisterConcrete(&bcBlockResponseMessage{}, "tendermint/blockchain/BlockResponse", nil)
  319. cdc.RegisterConcrete(&bcNoBlockResponseMessage{}, "tendermint/blockchain/NoBlockResponse", nil)
  320. cdc.RegisterConcrete(&bcStatusResponseMessage{}, "tendermint/blockchain/StatusResponse", nil)
  321. cdc.RegisterConcrete(&bcStatusRequestMessage{}, "tendermint/blockchain/StatusRequest", nil)
  322. }
  323. func decodeMsg(bz []byte) (msg BlockchainMessage, err error) {
  324. if len(bz) > maxMsgSize {
  325. return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize)
  326. }
  327. err = cdc.UnmarshalBinaryBare(bz, &msg)
  328. return
  329. }
  330. //-------------------------------------
  331. type bcBlockRequestMessage struct {
  332. Height int64
  333. }
  334. // ValidateBasic performs basic validation.
  335. func (m *bcBlockRequestMessage) ValidateBasic() error {
  336. if m.Height < 0 {
  337. return errors.New("Negative Height")
  338. }
  339. return nil
  340. }
  341. func (m *bcBlockRequestMessage) String() string {
  342. return fmt.Sprintf("[bcBlockRequestMessage %v]", m.Height)
  343. }
  344. type bcNoBlockResponseMessage struct {
  345. Height int64
  346. }
  347. // ValidateBasic performs basic validation.
  348. func (m *bcNoBlockResponseMessage) ValidateBasic() error {
  349. if m.Height < 0 {
  350. return errors.New("Negative Height")
  351. }
  352. return nil
  353. }
  354. func (brm *bcNoBlockResponseMessage) String() string {
  355. return fmt.Sprintf("[bcNoBlockResponseMessage %d]", brm.Height)
  356. }
  357. //-------------------------------------
  358. type bcBlockResponseMessage struct {
  359. Block *types.Block
  360. }
  361. // ValidateBasic performs basic validation.
  362. func (m *bcBlockResponseMessage) ValidateBasic() error {
  363. return m.Block.ValidateBasic()
  364. }
  365. func (m *bcBlockResponseMessage) String() string {
  366. return fmt.Sprintf("[bcBlockResponseMessage %v]", m.Block.Height)
  367. }
  368. //-------------------------------------
  369. type bcStatusRequestMessage struct {
  370. Height int64
  371. }
  372. // ValidateBasic performs basic validation.
  373. func (m *bcStatusRequestMessage) ValidateBasic() error {
  374. if m.Height < 0 {
  375. return errors.New("Negative Height")
  376. }
  377. return nil
  378. }
  379. func (m *bcStatusRequestMessage) String() string {
  380. return fmt.Sprintf("[bcStatusRequestMessage %v]", m.Height)
  381. }
  382. //-------------------------------------
  383. type bcStatusResponseMessage struct {
  384. Height int64
  385. }
  386. // ValidateBasic performs basic validation.
  387. func (m *bcStatusResponseMessage) ValidateBasic() error {
  388. if m.Height < 0 {
  389. return errors.New("Negative Height")
  390. }
  391. return nil
  392. }
  393. func (m *bcStatusResponseMessage) String() string {
  394. return fmt.Sprintf("[bcStatusResponseMessage %v]", m.Height)
  395. }