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.

529 lines
16 KiB

7 years ago
7 years ago
7 years ago
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package evidence
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/gogo/protobuf/proto"
  11. gogotypes "github.com/gogo/protobuf/types"
  12. dbm "github.com/tendermint/tm-db"
  13. clist "github.com/tendermint/tendermint/libs/clist"
  14. "github.com/tendermint/tendermint/libs/log"
  15. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  16. sm "github.com/tendermint/tendermint/state"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. const (
  20. baseKeyCommitted = byte(0x00)
  21. baseKeyPending = byte(0x01)
  22. )
  23. // Pool maintains a pool of valid evidence to be broadcasted and committed
  24. type Pool struct {
  25. logger log.Logger
  26. evidenceStore dbm.DB
  27. evidenceList *clist.CList // concurrent linked-list of evidence
  28. evidenceSize uint32 // amount of pending evidence
  29. // needed to load validators to verify evidence
  30. stateDB sm.Store
  31. // needed to load headers and commits to verify evidence
  32. blockStore BlockStore
  33. mtx sync.Mutex
  34. // latest state
  35. state sm.State
  36. pruningHeight int64
  37. pruningTime time.Time
  38. }
  39. // NewPool creates an evidence pool. If using an existing evidence store,
  40. // it will add all pending evidence to the concurrent list.
  41. func NewPool(evidenceDB dbm.DB, stateDB sm.Store, blockStore BlockStore) (*Pool, error) {
  42. state, err := stateDB.Load()
  43. if err != nil {
  44. return nil, fmt.Errorf("cannot load state: %w", err)
  45. }
  46. pool := &Pool{
  47. stateDB: stateDB,
  48. blockStore: blockStore,
  49. state: state,
  50. logger: log.NewNopLogger(),
  51. evidenceStore: evidenceDB,
  52. evidenceList: clist.New(),
  53. }
  54. // if pending evidence already in db, in event of prior failure, then check for expiration,
  55. // update the size and load it back to the evidenceList
  56. pool.pruningHeight, pool.pruningTime = pool.removeExpiredPendingEvidence()
  57. evList, _, err := pool.listEvidence(baseKeyPending, -1)
  58. if err != nil {
  59. return nil, err
  60. }
  61. atomic.StoreUint32(&pool.evidenceSize, uint32(len(evList)))
  62. for _, ev := range evList {
  63. pool.evidenceList.PushBack(ev)
  64. }
  65. return pool, nil
  66. }
  67. // PendingEvidence is used primarily as part of block proposal and returns up to maxNum of uncommitted evidence.
  68. func (evpool *Pool) PendingEvidence(maxBytes int64) ([]types.Evidence, int64) {
  69. if evpool.Size() == 0 {
  70. return []types.Evidence{}, 0
  71. }
  72. evidence, size, err := evpool.listEvidence(baseKeyPending, maxBytes)
  73. if err != nil {
  74. evpool.logger.Error("Unable to retrieve pending evidence", "err", err)
  75. }
  76. return evidence, size
  77. }
  78. // Update pulls the latest state to be used for expiration and evidence params and then prunes all expired evidence
  79. func (evpool *Pool) Update(state sm.State, ev types.EvidenceList) {
  80. // sanity check
  81. if state.LastBlockHeight <= evpool.state.LastBlockHeight {
  82. panic(fmt.Sprintf(
  83. "Failed EvidencePool.Update new state height is less than or equal to previous state height: %d <= %d",
  84. state.LastBlockHeight,
  85. evpool.state.LastBlockHeight,
  86. ))
  87. }
  88. evpool.logger.Info("Updating evidence pool", "last_block_height", state.LastBlockHeight,
  89. "last_block_time", state.LastBlockTime)
  90. // update the state
  91. evpool.updateState(state)
  92. evpool.markEvidenceAsCommitted(ev)
  93. // prune pending evidence when it has expired. This also updates when the next evidence will expire
  94. if evpool.Size() > 0 && state.LastBlockHeight > evpool.pruningHeight &&
  95. state.LastBlockTime.After(evpool.pruningTime) {
  96. evpool.pruningHeight, evpool.pruningTime = evpool.removeExpiredPendingEvidence()
  97. }
  98. }
  99. // AddEvidence checks the evidence is valid and adds it to the pool.
  100. func (evpool *Pool) AddEvidence(ev types.Evidence) error {
  101. evpool.logger.Debug("Attempting to add evidence", "ev", ev)
  102. // We have already verified this piece of evidence - no need to do it again
  103. if evpool.isPending(ev) {
  104. evpool.logger.Info("Evidence already pending, ignoring this one", "ev", ev)
  105. return nil
  106. }
  107. // check that the evidence isn't already committed
  108. if evpool.isCommitted(ev) {
  109. // this can happen if the peer that sent us the evidence is behind so we shouldn't
  110. // punish the peer.
  111. evpool.logger.Debug("Evidence was already committed, ignoring this one", "ev", ev)
  112. return nil
  113. }
  114. // 1) Verify against state.
  115. err := evpool.verify(ev)
  116. if err != nil {
  117. return types.NewErrInvalidEvidence(ev, err)
  118. }
  119. // 2) Save to store.
  120. if err := evpool.addPendingEvidence(ev); err != nil {
  121. return fmt.Errorf("can't add evidence to pending list: %w", err)
  122. }
  123. // 3) Add evidence to clist.
  124. evpool.evidenceList.PushBack(ev)
  125. evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
  126. return nil
  127. }
  128. // AddEvidenceFromConsensus should be exposed only to the consensus reactor so it can add evidence
  129. // to the pool directly without the need for verification.
  130. func (evpool *Pool) AddEvidenceFromConsensus(ev types.Evidence) error {
  131. // we already have this evidence, log this but don't return an error.
  132. if evpool.isPending(ev) {
  133. evpool.logger.Info("Evidence already pending, ignoring this one", "ev", ev)
  134. return nil
  135. }
  136. if err := evpool.addPendingEvidence(ev); err != nil {
  137. return fmt.Errorf("can't add evidence to pending list: %w", err)
  138. }
  139. // add evidence to be gossiped with peers
  140. evpool.evidenceList.PushBack(ev)
  141. evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
  142. return nil
  143. }
  144. // CheckEvidence takes an array of evidence from a block and verifies all the evidence there.
  145. // If it has already verified the evidence then it jumps to the next one. It ensures that no
  146. // evidence has already been committed or is being proposed twice. It also adds any
  147. // evidence that it doesn't currently have so that it can quickly form ABCI Evidence later.
  148. func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error {
  149. hashes := make([][]byte, len(evList))
  150. for idx, ev := range evList {
  151. ok := evpool.fastCheck(ev)
  152. if !ok {
  153. // check that the evidence isn't already committed
  154. if evpool.isCommitted(ev) {
  155. return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("evidence was already committed")}
  156. }
  157. err := evpool.verify(ev)
  158. if err != nil {
  159. return &types.ErrInvalidEvidence{Evidence: ev, Reason: err}
  160. }
  161. if err := evpool.addPendingEvidence(ev); err != nil {
  162. // Something went wrong with adding the evidence but we already know it is valid
  163. // hence we log an error and continue
  164. evpool.logger.Error("Can't add evidence to pending list", "err", err, "ev", ev)
  165. }
  166. evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
  167. }
  168. // check for duplicate evidence. We cache hashes so we don't have to work them out again.
  169. hashes[idx] = ev.Hash()
  170. for i := idx - 1; i >= 0; i-- {
  171. if bytes.Equal(hashes[i], hashes[idx]) {
  172. return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("duplicate evidence")}
  173. }
  174. }
  175. }
  176. return nil
  177. }
  178. // EvidenceFront goes to the first evidence in the clist
  179. func (evpool *Pool) EvidenceFront() *clist.CElement {
  180. return evpool.evidenceList.Front()
  181. }
  182. // EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil
  183. func (evpool *Pool) EvidenceWaitChan() <-chan struct{} {
  184. return evpool.evidenceList.WaitChan()
  185. }
  186. // SetLogger sets the Logger.
  187. func (evpool *Pool) SetLogger(l log.Logger) {
  188. evpool.logger = l
  189. }
  190. // Size returns the number of evidence in the pool.
  191. func (evpool *Pool) Size() uint32 {
  192. return atomic.LoadUint32(&evpool.evidenceSize)
  193. }
  194. // State returns the current state of the evpool.
  195. func (evpool *Pool) State() sm.State {
  196. evpool.mtx.Lock()
  197. defer evpool.mtx.Unlock()
  198. return evpool.state
  199. }
  200. //--------------------------------------------------------------------------
  201. // fastCheck leverages the fact that the evidence pool may have already verified the evidence to see if it can
  202. // quickly conclude that the evidence is already valid.
  203. func (evpool *Pool) fastCheck(ev types.Evidence) bool {
  204. if lcae, ok := ev.(*types.LightClientAttackEvidence); ok {
  205. key := keyPending(ev)
  206. evBytes, err := evpool.evidenceStore.Get(key)
  207. if evBytes == nil { // the evidence is not in the nodes pending list
  208. return false
  209. }
  210. if err != nil {
  211. evpool.logger.Error("Failed to load light client attack evidence", "err", err, "key(height/hash)", key)
  212. return false
  213. }
  214. var trustedPb tmproto.LightClientAttackEvidence
  215. err = trustedPb.Unmarshal(evBytes)
  216. if err != nil {
  217. evpool.logger.Error("Failed to convert light client attack evidence from bytes",
  218. "err", err, "key(height/hash)", key)
  219. return false
  220. }
  221. trustedEv, err := types.LightClientAttackEvidenceFromProto(&trustedPb)
  222. if err != nil {
  223. evpool.logger.Error("Failed to convert light client attack evidence from protobuf",
  224. "err", err, "key(height/hash)", key)
  225. return false
  226. }
  227. // ensure that all the byzantine validators that the evidence pool has match the byzantine validators
  228. // in this evidence
  229. if trustedEv.ByzantineValidators == nil && lcae.ByzantineValidators != nil {
  230. return false
  231. }
  232. if len(trustedEv.ByzantineValidators) != len(lcae.ByzantineValidators) {
  233. return false
  234. }
  235. byzValsCopy := make([]*types.Validator, len(lcae.ByzantineValidators))
  236. for i, v := range lcae.ByzantineValidators {
  237. byzValsCopy[i] = v.Copy()
  238. }
  239. // ensure that both validator arrays are in the same order
  240. sort.Sort(types.ValidatorsByVotingPower(byzValsCopy))
  241. for idx, val := range trustedEv.ByzantineValidators {
  242. if !bytes.Equal(byzValsCopy[idx].Address, val.Address) {
  243. return false
  244. }
  245. if byzValsCopy[idx].VotingPower != val.VotingPower {
  246. return false
  247. }
  248. }
  249. return true
  250. }
  251. // for all other evidence the evidence pool just checks if it is already in the pending db
  252. return evpool.isPending(ev)
  253. }
  254. // IsExpired checks whether evidence or a polc is expired by checking whether a height and time is older
  255. // than set by the evidence consensus parameters
  256. func (evpool *Pool) isExpired(height int64, time time.Time) bool {
  257. var (
  258. params = evpool.State().ConsensusParams.Evidence
  259. ageDuration = evpool.State().LastBlockTime.Sub(time)
  260. ageNumBlocks = evpool.State().LastBlockHeight - height
  261. )
  262. return ageNumBlocks > params.MaxAgeNumBlocks &&
  263. ageDuration > params.MaxAgeDuration
  264. }
  265. // IsCommitted returns true if we have already seen this exact evidence and it is already marked as committed.
  266. func (evpool *Pool) isCommitted(evidence types.Evidence) bool {
  267. key := keyCommitted(evidence)
  268. ok, err := evpool.evidenceStore.Has(key)
  269. if err != nil {
  270. evpool.logger.Error("Unable to find committed evidence", "err", err)
  271. }
  272. return ok
  273. }
  274. // IsPending checks whether the evidence is already pending. DB errors are passed to the logger.
  275. func (evpool *Pool) isPending(evidence types.Evidence) bool {
  276. key := keyPending(evidence)
  277. ok, err := evpool.evidenceStore.Has(key)
  278. if err != nil {
  279. evpool.logger.Error("Unable to find pending evidence", "err", err)
  280. }
  281. return ok
  282. }
  283. func (evpool *Pool) addPendingEvidence(ev types.Evidence) error {
  284. evpb, err := types.EvidenceToProto(ev)
  285. if err != nil {
  286. return fmt.Errorf("unable to convert to proto, err: %w", err)
  287. }
  288. evBytes, err := evpb.Marshal()
  289. if err != nil {
  290. return fmt.Errorf("unable to marshal evidence: %w", err)
  291. }
  292. key := keyPending(ev)
  293. err = evpool.evidenceStore.Set(key, evBytes)
  294. if err != nil {
  295. return fmt.Errorf("can't persist evidence: %w", err)
  296. }
  297. atomic.AddUint32(&evpool.evidenceSize, 1)
  298. return nil
  299. }
  300. func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
  301. key := keyPending(evidence)
  302. if err := evpool.evidenceStore.Delete(key); err != nil {
  303. evpool.logger.Error("Unable to delete pending evidence", "err", err)
  304. } else {
  305. atomic.AddUint32(&evpool.evidenceSize, ^uint32(0))
  306. evpool.logger.Info("Deleted pending evidence", "evidence", evidence)
  307. }
  308. }
  309. // markEvidenceAsCommitted processes all the evidence in the block, marking it as
  310. // committed and removing it from the pending database.
  311. func (evpool *Pool) markEvidenceAsCommitted(evidence types.EvidenceList) {
  312. blockEvidenceMap := make(map[string]struct{}, len(evidence))
  313. for _, ev := range evidence {
  314. if evpool.isPending(ev) {
  315. evpool.removePendingEvidence(ev)
  316. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  317. }
  318. // Add evidence to the committed list. As the evidence is stored in the block store
  319. // we only need to record the height that it was saved at.
  320. key := keyCommitted(ev)
  321. h := gogotypes.Int64Value{Value: ev.Height()}
  322. evBytes, err := proto.Marshal(&h)
  323. if err != nil {
  324. evpool.logger.Error("failed to marshal committed evidence", "err", err, "key(height/hash)", key)
  325. continue
  326. }
  327. if err := evpool.evidenceStore.Set(key, evBytes); err != nil {
  328. evpool.logger.Error("Unable to save committed evidence", "err", err, "key(height/hash)", key)
  329. }
  330. }
  331. // remove committed evidence from the clist
  332. if len(blockEvidenceMap) != 0 {
  333. evpool.removeEvidenceFromList(blockEvidenceMap)
  334. }
  335. }
  336. // listEvidence retrieves lists evidence from oldest to newest within maxBytes.
  337. // If maxBytes is -1, there's no cap on the size of returned evidence.
  338. func (evpool *Pool) listEvidence(prefixKey byte, maxBytes int64) ([]types.Evidence, int64, error) {
  339. var (
  340. evSize int64
  341. totalSize int64
  342. evidence []types.Evidence
  343. evList tmproto.EvidenceList // used for calculating the bytes size
  344. )
  345. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{prefixKey})
  346. if err != nil {
  347. return nil, totalSize, fmt.Errorf("database error: %v", err)
  348. }
  349. defer iter.Close()
  350. for ; iter.Valid(); iter.Next() {
  351. var evpb tmproto.Evidence
  352. err := evpb.Unmarshal(iter.Value())
  353. if err != nil {
  354. return evidence, totalSize, err
  355. }
  356. evList.Evidence = append(evList.Evidence, evpb)
  357. evSize = int64(evList.Size())
  358. if maxBytes != -1 && evSize > maxBytes {
  359. if err := iter.Error(); err != nil {
  360. return evidence, totalSize, err
  361. }
  362. return evidence, totalSize, nil
  363. }
  364. ev, err := types.EvidenceFromProto(&evpb)
  365. if err != nil {
  366. return nil, totalSize, err
  367. }
  368. totalSize = evSize
  369. evidence = append(evidence, ev)
  370. }
  371. if err := iter.Error(); err != nil {
  372. return evidence, totalSize, err
  373. }
  374. return evidence, totalSize, nil
  375. }
  376. func (evpool *Pool) removeExpiredPendingEvidence() (int64, time.Time) {
  377. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPending})
  378. if err != nil {
  379. evpool.logger.Error("Unable to iterate over pending evidence", "err", err)
  380. return evpool.State().LastBlockHeight, evpool.State().LastBlockTime
  381. }
  382. defer iter.Close()
  383. blockEvidenceMap := make(map[string]struct{})
  384. for ; iter.Valid(); iter.Next() {
  385. ev, err := bytesToEv(iter.Value())
  386. if err != nil {
  387. evpool.logger.Error("Error in transition evidence from protobuf", "err", err)
  388. continue
  389. }
  390. if !evpool.isExpired(ev.Height(), ev.Time()) {
  391. if len(blockEvidenceMap) != 0 {
  392. evpool.removeEvidenceFromList(blockEvidenceMap)
  393. }
  394. // return the height and time with which this evidence will have expired so we know when to prune next
  395. return ev.Height() + evpool.State().ConsensusParams.Evidence.MaxAgeNumBlocks + 1,
  396. ev.Time().Add(evpool.State().ConsensusParams.Evidence.MaxAgeDuration).Add(time.Second)
  397. }
  398. evpool.removePendingEvidence(ev)
  399. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  400. }
  401. // We either have no pending evidence or all evidence has expired
  402. if len(blockEvidenceMap) != 0 {
  403. evpool.removeEvidenceFromList(blockEvidenceMap)
  404. }
  405. return evpool.State().LastBlockHeight, evpool.State().LastBlockTime
  406. }
  407. func (evpool *Pool) removeEvidenceFromList(
  408. blockEvidenceMap map[string]struct{}) {
  409. for e := evpool.evidenceList.Front(); e != nil; e = e.Next() {
  410. // Remove from clist
  411. ev := e.Value.(types.Evidence)
  412. if _, ok := blockEvidenceMap[evMapKey(ev)]; ok {
  413. evpool.evidenceList.Remove(e)
  414. e.DetachPrev()
  415. }
  416. }
  417. }
  418. func (evpool *Pool) updateState(state sm.State) {
  419. evpool.mtx.Lock()
  420. defer evpool.mtx.Unlock()
  421. evpool.state = state
  422. }
  423. func bytesToEv(evBytes []byte) (types.Evidence, error) {
  424. var evpb tmproto.Evidence
  425. err := evpb.Unmarshal(evBytes)
  426. if err != nil {
  427. return &types.DuplicateVoteEvidence{}, err
  428. }
  429. return types.EvidenceFromProto(&evpb)
  430. }
  431. func evMapKey(ev types.Evidence) string {
  432. return string(ev.Hash())
  433. }
  434. // big endian padded hex
  435. func bE(h int64) string {
  436. return fmt.Sprintf("%0.16X", h)
  437. }
  438. func keyCommitted(evidence types.Evidence) []byte {
  439. return append([]byte{baseKeyCommitted}, keySuffix(evidence)...)
  440. }
  441. func keyPending(evidence types.Evidence) []byte {
  442. return append([]byte{baseKeyPending}, keySuffix(evidence)...)
  443. }
  444. func keySuffix(evidence types.Evidence) []byte {
  445. return []byte(fmt.Sprintf("%s/%X", bE(evidence.Height()), evidence.Hash()))
  446. }