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.

399 lines
13 KiB

  1. package consensus
  2. import (
  3. "fmt"
  4. tmcon "github.com/tendermint/tendermint/consensus"
  5. cstypes "github.com/tendermint/tendermint/consensus/types"
  6. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  7. "github.com/tendermint/tendermint/types"
  8. )
  9. // MisbehaviorList encompasses a list of all possible behaviors
  10. var MisbehaviorList = map[string]Misbehavior{
  11. "double-prevote": DoublePrevoteMisbehavior(),
  12. }
  13. type Misbehavior struct {
  14. Name string
  15. EnterPropose func(cs *State, height int64, round int32)
  16. EnterPrevote func(cs *State, height int64, round int32)
  17. EnterPrecommit func(cs *State, height int64, round int32)
  18. ReceivePrevote func(cs *State, prevote *types.Vote)
  19. ReceivePrecommit func(cs *State, precommit *types.Vote)
  20. ReceiveProposal func(cs *State, proposal *types.Proposal) error
  21. }
  22. // BEHAVIORS
  23. func DefaultMisbehavior() Misbehavior {
  24. return Misbehavior{
  25. Name: "default",
  26. EnterPropose: defaultEnterPropose,
  27. EnterPrevote: defaultEnterPrevote,
  28. EnterPrecommit: defaultEnterPrecommit,
  29. ReceivePrevote: defaultReceivePrevote,
  30. ReceivePrecommit: defaultReceivePrecommit,
  31. ReceiveProposal: defaultReceiveProposal,
  32. }
  33. }
  34. // DoublePrevoteMisbehavior will make a node prevote both nil and a block in the same
  35. // height and round.
  36. func DoublePrevoteMisbehavior() Misbehavior {
  37. b := DefaultMisbehavior()
  38. b.Name = "double-prevote"
  39. b.EnterPrevote = func(cs *State, height int64, round int32) {
  40. // If a block is locked, prevote that.
  41. if cs.LockedBlock != nil {
  42. cs.Logger.Debug("enterPrevote: already locked on a block, prevoting locked block")
  43. cs.signAddVote(tmproto.PrevoteType, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  44. return
  45. }
  46. // If ProposalBlock is nil, prevote nil.
  47. if cs.ProposalBlock == nil {
  48. cs.Logger.Debug("enterPrevote: ProposalBlock is nil")
  49. cs.signAddVote(tmproto.PrevoteType, nil, types.PartSetHeader{})
  50. return
  51. }
  52. // Validate proposal block
  53. err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock)
  54. if err != nil {
  55. // ProposalBlock is invalid, prevote nil.
  56. cs.Logger.Error("enterPrevote: ProposalBlock is invalid", "err", err)
  57. cs.signAddVote(tmproto.PrevoteType, nil, types.PartSetHeader{})
  58. return
  59. }
  60. if cs.sw == nil {
  61. cs.Logger.Error("nil switch")
  62. return
  63. }
  64. prevote, err := cs.signVote(tmproto.PrevoteType, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  65. if err != nil {
  66. cs.Logger.Error("enterPrevote: Unable to sign block", "err", err)
  67. }
  68. nilPrevote, err := cs.signVote(tmproto.PrevoteType, nil, types.PartSetHeader{})
  69. if err != nil {
  70. cs.Logger.Error("enterPrevote: Unable to sign block", "err", err)
  71. }
  72. // add our own vote
  73. cs.sendInternalMessage(msgInfo{&tmcon.VoteMessage{Vote: prevote}, ""})
  74. cs.Logger.Info("Sending conflicting votes")
  75. peers := cs.sw.Peers().List()
  76. // there has to be at least two other peers connected else this behavior works normally
  77. for idx, peer := range peers {
  78. if idx%2 == 0 { // sign the proposal block
  79. peer.Send(VoteChannel, tmcon.MustEncode(&tmcon.VoteMessage{Vote: prevote}))
  80. } else { // sign a nil block
  81. peer.Send(VoteChannel, tmcon.MustEncode(&tmcon.VoteMessage{Vote: nilPrevote}))
  82. }
  83. }
  84. }
  85. return b
  86. }
  87. // DEFAULTS
  88. func defaultEnterPropose(cs *State, height int64, round int32) {
  89. logger := cs.Logger.With("height", height, "round", round)
  90. // If we don't get the proposal and all block parts quick enough, enterPrevote
  91. cs.scheduleTimeout(cs.config.Propose(round), height, round, cstypes.RoundStepPropose)
  92. // Nothing more to do if we're not a validator
  93. if cs.privValidator == nil {
  94. logger.Debug("This node is not a validator")
  95. return
  96. }
  97. logger.Debug("This node is a validator")
  98. pubKey, err := cs.privValidator.GetPubKey()
  99. if err != nil {
  100. // If this node is a validator & proposer in the currentx round, it will
  101. // miss the opportunity to create a block.
  102. logger.Error("Error on retrival of pubkey", "err", err)
  103. return
  104. }
  105. address := pubKey.Address()
  106. // if not a validator, we're done
  107. if !cs.Validators.HasAddress(address) {
  108. logger.Debug("This node is not a validator", "addr", address, "vals", cs.Validators)
  109. return
  110. }
  111. if cs.isProposer(address) {
  112. logger.Debug("enterPropose: our turn to propose",
  113. "proposer", address,
  114. )
  115. cs.decideProposal(height, round)
  116. } else {
  117. logger.Debug("enterPropose: not our turn to propose",
  118. "proposer", cs.Validators.GetProposer().Address,
  119. )
  120. }
  121. }
  122. func defaultEnterPrevote(cs *State, height int64, round int32) {
  123. logger := cs.Logger.With("height", height, "round", round)
  124. // If a block is locked, prevote that.
  125. if cs.LockedBlock != nil {
  126. logger.Debug("enterPrevote: already locked on a block, prevoting locked block")
  127. cs.signAddVote(tmproto.PrevoteType, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  128. return
  129. }
  130. // If ProposalBlock is nil, prevote nil.
  131. if cs.ProposalBlock == nil {
  132. logger.Debug("enterPrevote: ProposalBlock is nil")
  133. cs.signAddVote(tmproto.PrevoteType, nil, types.PartSetHeader{})
  134. return
  135. }
  136. // Validate proposal block
  137. err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock)
  138. if err != nil {
  139. // ProposalBlock is invalid, prevote nil.
  140. logger.Error("enterPrevote: ProposalBlock is invalid", "err", err)
  141. cs.signAddVote(tmproto.PrevoteType, nil, types.PartSetHeader{})
  142. return
  143. }
  144. // Prevote cs.ProposalBlock
  145. // NOTE: the proposal signature is validated when it is received,
  146. // and the proposal block parts are validated as they are received (against the merkle hash in the proposal)
  147. logger.Debug("enterPrevote: ProposalBlock is valid")
  148. cs.signAddVote(tmproto.PrevoteType, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  149. }
  150. func defaultEnterPrecommit(cs *State, height int64, round int32) {
  151. logger := cs.Logger.With("height", height, "round", round)
  152. // check for a polka
  153. blockID, ok := cs.Votes.Prevotes(round).TwoThirdsMajority()
  154. // If we don't have a polka, we must precommit nil.
  155. if !ok {
  156. if cs.LockedBlock != nil {
  157. logger.Debug("enterPrecommit: no +2/3 prevotes during enterPrecommit while we're locked; precommitting nil")
  158. } else {
  159. logger.Debug("enterPrecommit: no +2/3 prevotes during enterPrecommit; precommitting nil.")
  160. }
  161. cs.signAddVote(tmproto.PrecommitType, nil, types.PartSetHeader{})
  162. return
  163. }
  164. // At this point +2/3 prevoted for a particular block or nil.
  165. _ = cs.eventBus.PublishEventPolka(cs.RoundStateEvent())
  166. // the latest POLRound should be this round.
  167. polRound, _ := cs.Votes.POLInfo()
  168. if polRound < round {
  169. panic(fmt.Sprintf("This POLRound should be %v but got %v", round, polRound))
  170. }
  171. // +2/3 prevoted nil. Unlock and precommit nil.
  172. if len(blockID.Hash) == 0 {
  173. if cs.LockedBlock == nil {
  174. logger.Debug("enterPrecommit: +2/3 prevoted for nil")
  175. } else {
  176. logger.Debug("enterPrecommit: +2/3 prevoted for nil; unlocking")
  177. cs.LockedRound = -1
  178. cs.LockedBlock = nil
  179. cs.LockedBlockParts = nil
  180. _ = cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  181. }
  182. cs.signAddVote(tmproto.PrecommitType, nil, types.PartSetHeader{})
  183. return
  184. }
  185. // At this point, +2/3 prevoted for a particular block.
  186. // If we're already locked on that block, precommit it, and update the LockedRound
  187. if cs.LockedBlock.HashesTo(blockID.Hash) {
  188. logger.Debug("enterPrecommit: +2/3 prevoted locked block; relocking")
  189. cs.LockedRound = round
  190. _ = cs.eventBus.PublishEventRelock(cs.RoundStateEvent())
  191. cs.signAddVote(tmproto.PrecommitType, blockID.Hash, blockID.PartSetHeader)
  192. return
  193. }
  194. // If +2/3 prevoted for proposal block, stage and precommit it
  195. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  196. logger.Debug("enterPrecommit: +2/3 prevoted proposal block; locking", "hash", blockID.Hash)
  197. // Validate the block.
  198. if err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock); err != nil {
  199. panic(fmt.Sprintf("enterPrecommit: +2/3 prevoted for an invalid block: %v", err))
  200. }
  201. cs.LockedRound = round
  202. cs.LockedBlock = cs.ProposalBlock
  203. cs.LockedBlockParts = cs.ProposalBlockParts
  204. _ = cs.eventBus.PublishEventLock(cs.RoundStateEvent())
  205. cs.signAddVote(tmproto.PrecommitType, blockID.Hash, blockID.PartSetHeader)
  206. return
  207. }
  208. // There was a polka in this round for a block we don't have.
  209. // Fetch that block, unlock, and precommit nil.
  210. // The +2/3 prevotes for this round is the POL for our unlock.
  211. logger.Debug("enterPrecommit: +2/3 prevotes for a block we don't have; voting nil", "blockID", blockID)
  212. cs.LockedRound = -1
  213. cs.LockedBlock = nil
  214. cs.LockedBlockParts = nil
  215. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  216. cs.ProposalBlock = nil
  217. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  218. }
  219. _ = cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  220. cs.signAddVote(tmproto.PrecommitType, nil, types.PartSetHeader{})
  221. }
  222. func defaultReceivePrevote(cs *State, vote *types.Vote) {
  223. height := cs.Height
  224. prevotes := cs.Votes.Prevotes(vote.Round)
  225. // If +2/3 prevotes for a block or nil for *any* round:
  226. if blockID, ok := prevotes.TwoThirdsMajority(); ok {
  227. // There was a polka!
  228. // If we're locked but this is a recent polka, unlock.
  229. // If it matches our ProposalBlock, update the ValidBlock
  230. // Unlock if `cs.LockedRound < vote.Round <= cs.Round`
  231. // NOTE: If vote.Round > cs.Round, we'll deal with it when we get to vote.Round
  232. if (cs.LockedBlock != nil) &&
  233. (cs.LockedRound < vote.Round) &&
  234. (vote.Round <= cs.Round) &&
  235. !cs.LockedBlock.HashesTo(blockID.Hash) {
  236. cs.Logger.Info("Unlocking because of POL.", "lockedRound", cs.LockedRound, "POLRound", vote.Round)
  237. cs.LockedRound = -1
  238. cs.LockedBlock = nil
  239. cs.LockedBlockParts = nil
  240. _ = cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  241. }
  242. // Update Valid* if we can.
  243. // NOTE: our proposal block may be nil or not what received a polka..
  244. if len(blockID.Hash) != 0 && (cs.ValidRound < vote.Round) && (vote.Round == cs.Round) {
  245. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  246. cs.Logger.Info(
  247. "Updating ValidBlock because of POL.", "validRound", cs.ValidRound, "POLRound", vote.Round)
  248. cs.ValidRound = vote.Round
  249. cs.ValidBlock = cs.ProposalBlock
  250. cs.ValidBlockParts = cs.ProposalBlockParts
  251. } else {
  252. cs.Logger.Info(
  253. "valid block we do not know about; set ProposalBlock=nil",
  254. "proposal", cs.ProposalBlock.Hash(),
  255. "blockID", blockID.Hash,
  256. )
  257. // We're getting the wrong block.
  258. cs.ProposalBlock = nil
  259. }
  260. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  261. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  262. }
  263. cs.evsw.FireEvent(types.EventValidBlock, &cs.RoundState)
  264. _ = cs.eventBus.PublishEventValidBlock(cs.RoundStateEvent())
  265. }
  266. }
  267. // If +2/3 prevotes for *anything* for future round:
  268. switch {
  269. case cs.Round < vote.Round && prevotes.HasTwoThirdsAny():
  270. // Round-skip if there is any 2/3+ of votes ahead of us
  271. cs.enterNewRound(height, vote.Round)
  272. case cs.Round == vote.Round && cstypes.RoundStepPrevote <= cs.Step: // current round
  273. blockID, ok := prevotes.TwoThirdsMajority()
  274. if ok && (cs.isProposalComplete() || len(blockID.Hash) == 0) {
  275. cs.enterPrecommit(height, vote.Round)
  276. } else if prevotes.HasTwoThirdsAny() {
  277. cs.enterPrevoteWait(height, vote.Round)
  278. }
  279. case cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round:
  280. // If the proposal is now complete, enter prevote of cs.Round.
  281. if cs.isProposalComplete() {
  282. cs.enterPrevote(height, cs.Round)
  283. }
  284. }
  285. }
  286. func defaultReceivePrecommit(cs *State, vote *types.Vote) {
  287. height := cs.Height
  288. precommits := cs.Votes.Precommits(vote.Round)
  289. cs.Logger.Info("Added to precommit", "vote", vote, "precommits", precommits.StringShort())
  290. blockID, ok := precommits.TwoThirdsMajority()
  291. if ok {
  292. // Executed as TwoThirdsMajority could be from a higher round
  293. cs.enterNewRound(height, vote.Round)
  294. cs.enterPrecommit(height, vote.Round)
  295. if len(blockID.Hash) != 0 {
  296. cs.enterCommit(height, vote.Round)
  297. if cs.config.SkipTimeoutCommit && precommits.HasAll() {
  298. cs.enterNewRound(cs.Height, 0)
  299. }
  300. } else {
  301. cs.enterPrecommitWait(height, vote.Round)
  302. }
  303. } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() {
  304. cs.enterNewRound(height, vote.Round)
  305. cs.enterPrecommitWait(height, vote.Round)
  306. }
  307. }
  308. func defaultReceiveProposal(cs *State, proposal *types.Proposal) error {
  309. // Already have one
  310. // TODO: possibly catch double proposals
  311. if cs.Proposal != nil {
  312. return nil
  313. }
  314. // Does not apply
  315. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  316. return nil
  317. }
  318. // Verify POLRound, which must be -1 or in range [0, proposal.Round).
  319. if proposal.POLRound < -1 ||
  320. (proposal.POLRound >= 0 && proposal.POLRound >= proposal.Round) {
  321. return ErrInvalidProposalPOLRound
  322. }
  323. p := proposal.ToProto()
  324. // Verify signature
  325. if !cs.Validators.GetProposer().PubKey.VerifySignature(
  326. types.ProposalSignBytes(cs.state.ChainID, p), proposal.Signature) {
  327. return ErrInvalidProposalSignature
  328. }
  329. proposal.Signature = p.Signature
  330. cs.Proposal = proposal
  331. // We don't update cs.ProposalBlockParts if it is already set.
  332. // This happens if we're already in cstypes.RoundStepCommit or if there is a valid block in the current round.
  333. // TODO: We can check if Proposal is for a different block as this is a sign of misbehavior!
  334. if cs.ProposalBlockParts == nil {
  335. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockID.PartSetHeader)
  336. }
  337. cs.Logger.Info("received proposal", "proposal", proposal)
  338. return nil
  339. }