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.

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