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.

603 lines
18 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
7 years ago
  1. package evidence
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "reflect"
  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. abci "github.com/tendermint/tendermint/abci/types"
  14. clist "github.com/tendermint/tendermint/libs/clist"
  15. "github.com/tendermint/tendermint/libs/log"
  16. evproto "github.com/tendermint/tendermint/proto/tendermint/evidence"
  17. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  18. sm "github.com/tendermint/tendermint/state"
  19. "github.com/tendermint/tendermint/types"
  20. )
  21. const (
  22. baseKeyCommitted = byte(0x00)
  23. baseKeyPending = byte(0x01)
  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(evidenceDB dbm.DB, stateDB sm.Store, blockStore BlockStore) (*Pool, error) {
  44. state, err := stateDB.Load()
  45. if err != nil {
  46. return nil, fmt.Errorf("cannot load state: %w", err)
  47. }
  48. pool := &Pool{
  49. stateDB: stateDB,
  50. blockStore: blockStore,
  51. state: state,
  52. logger: log.NewNopLogger(),
  53. evidenceStore: evidenceDB,
  54. evidenceList: clist.New(),
  55. }
  56. // if pending evidence already in db, in event of prior failure, then check for expiration,
  57. // update the size and load it back to the evidenceList
  58. pool.pruningHeight, pool.pruningTime = pool.removeExpiredPendingEvidence()
  59. evList, _, err := pool.listEvidence(baseKeyPending, -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 maxNum of uncommitted evidence.
  70. func (evpool *Pool) PendingEvidence(maxBytes int64) ([]types.Evidence, int64) {
  71. if atomic.LoadUint32(&evpool.evidenceSize) == 0 {
  72. return []types.Evidence{}, 0
  73. }
  74. evidence, size, err := evpool.listEvidence(baseKeyPending, maxBytes)
  75. if err != nil {
  76. evpool.logger.Error("Unable to retrieve pending evidence", "err", err)
  77. }
  78. return evidence, size
  79. }
  80. // Update pulls the latest state to be used for expiration and evidence params and then prunes all expired evidence
  81. func (evpool *Pool) Update(state sm.State) {
  82. // sanity check
  83. if state.LastBlockHeight <= evpool.state.LastBlockHeight {
  84. panic(fmt.Sprintf(
  85. "Failed EvidencePool.Update new state height is less than or equal to previous state height: %d <= %d",
  86. state.LastBlockHeight,
  87. evpool.state.LastBlockHeight,
  88. ))
  89. }
  90. evpool.logger.Info("Updating evidence pool", "last_block_height", state.LastBlockHeight,
  91. "last_block_time", state.LastBlockTime)
  92. // update the state
  93. evpool.updateState(state)
  94. // prune pending evidence when it has expired. This also updates when the next evidence will expire
  95. if atomic.LoadUint32(&evpool.evidenceSize) > 0 && state.LastBlockHeight > evpool.pruningHeight &&
  96. state.LastBlockTime.After(evpool.pruningTime) {
  97. evpool.pruningHeight, evpool.pruningTime = evpool.removeExpiredPendingEvidence()
  98. }
  99. }
  100. // AddEvidence checks the evidence is valid and adds it to the pool.
  101. func (evpool *Pool) AddEvidence(ev types.Evidence) error {
  102. evpool.logger.Debug("Attempting to add evidence", "ev", ev)
  103. // We have already verified this piece of evidence - no need to do it again
  104. if evpool.isPending(ev) {
  105. return errors.New("evidence already verified and added")
  106. }
  107. // 1) Verify against state.
  108. evInfo, err := evpool.verify(ev)
  109. if err != nil {
  110. return types.NewErrInvalidEvidence(ev, err)
  111. }
  112. // 2) Save to store.
  113. if err := evpool.addPendingEvidence(evInfo); err != nil {
  114. return fmt.Errorf("can't add evidence to pending list: %w", err)
  115. }
  116. // 3) Add evidence to clist.
  117. evpool.evidenceList.PushBack(ev)
  118. evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
  119. return nil
  120. }
  121. // AddEvidenceFromConsensus should be exposed only to the consensus so it can add evidence to the pool
  122. // directly without the need for verification.
  123. func (evpool *Pool) AddEvidenceFromConsensus(ev types.Evidence, time time.Time, valSet *types.ValidatorSet) error {
  124. var (
  125. vals []*types.Validator
  126. totalPower int64
  127. )
  128. if evpool.isPending(ev) {
  129. return errors.New("evidence already verified and added") // we already have this evidence
  130. }
  131. switch ev := ev.(type) {
  132. case *types.DuplicateVoteEvidence:
  133. _, val := valSet.GetByAddress(ev.VoteA.ValidatorAddress)
  134. vals = append(vals, val)
  135. totalPower = valSet.TotalVotingPower()
  136. default:
  137. return fmt.Errorf("unrecognized evidence type: %T", ev)
  138. }
  139. evInfo := &info{
  140. Evidence: ev,
  141. Time: time,
  142. Validators: vals,
  143. TotalVotingPower: totalPower,
  144. }
  145. if err := evpool.addPendingEvidence(evInfo); err != nil {
  146. return fmt.Errorf("can't add evidence to pending list: %w", err)
  147. }
  148. evpool.evidenceList.PushBack(ev)
  149. evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
  150. return nil
  151. }
  152. // CheckEvidence takes an array of evidence from a block and verifies all the evidence there.
  153. // If it has already verified the evidence then it jumps to the next one. It ensures that no
  154. // evidence has already been committed or is being proposed twice. It also adds any
  155. // evidence that it doesn't currently have so that it can quickly form ABCI Evidence later.
  156. func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error {
  157. hashes := make([][]byte, len(evList))
  158. for idx, ev := range evList {
  159. ok := evpool.fastCheck(ev)
  160. if !ok {
  161. evInfo, err := evpool.verify(ev)
  162. if err != nil {
  163. return &types.ErrInvalidEvidence{Evidence: ev, Reason: err}
  164. }
  165. if err := evpool.addPendingEvidence(evInfo); err != nil {
  166. evpool.logger.Error("Can't add evidence to pending list", "err", err, "evInfo", evInfo)
  167. }
  168. evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
  169. }
  170. // check for duplicate evidence. We cache hashes so we don't have to work them out again.
  171. hashes[idx] = ev.Hash()
  172. for i := idx - 1; i >= 0; i-- {
  173. if bytes.Equal(hashes[i], hashes[idx]) {
  174. return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("duplicate evidence")}
  175. }
  176. }
  177. }
  178. return nil
  179. }
  180. // ABCIEvidence processes all the evidence in the block, marking it as committed and removing it
  181. // from the pending database. It then forms the individual abci evidence that will be passed back to
  182. // the application.
  183. func (evpool *Pool) ABCIEvidence(height int64, evidence []types.Evidence) []abci.Evidence {
  184. // make a map of committed evidence to remove from the clist
  185. blockEvidenceMap := make(map[string]struct{}, len(evidence))
  186. abciEvidence := make([]abci.Evidence, 0)
  187. for _, ev := range evidence {
  188. // get entire evidence info from pending list
  189. infoBytes, err := evpool.evidenceStore.Get(keyPending(ev))
  190. if err != nil {
  191. evpool.logger.Error("Unable to retrieve evidence to pass to ABCI. "+
  192. "Evidence pool should have seen this evidence before",
  193. "evidence", ev, "err", err)
  194. continue
  195. }
  196. var infoProto evproto.Info
  197. err = infoProto.Unmarshal(infoBytes)
  198. if err != nil {
  199. evpool.logger.Error("Decoding evidence info failed", "err", err, "height", ev.Height(), "hash", ev.Hash())
  200. continue
  201. }
  202. evInfo, err := infoFromProto(&infoProto)
  203. if err != nil {
  204. evpool.logger.Error("Converting evidence info from proto failed", "err", err, "height", ev.Height(),
  205. "hash", ev.Hash())
  206. continue
  207. }
  208. var evType abci.EvidenceType
  209. switch ev.(type) {
  210. case *types.DuplicateVoteEvidence:
  211. evType = abci.EvidenceType_DUPLICATE_VOTE
  212. case *types.LightClientAttackEvidence:
  213. evType = abci.EvidenceType_LIGHT_CLIENT_ATTACK
  214. default:
  215. evpool.logger.Error("Unknown evidence type", "T", reflect.TypeOf(ev))
  216. continue
  217. }
  218. for _, val := range evInfo.Validators {
  219. abciEv := abci.Evidence{
  220. Type: evType,
  221. Validator: types.TM2PB.Validator(val),
  222. Height: ev.Height(),
  223. Time: evInfo.Time,
  224. TotalVotingPower: evInfo.TotalVotingPower,
  225. }
  226. abciEvidence = append(abciEvidence, abciEv)
  227. evpool.logger.Info("Created ABCI evidence", "ev", abciEv)
  228. }
  229. // we can now remove the evidence from the pending list and the clist that we use for gossiping
  230. evpool.removePendingEvidence(ev)
  231. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  232. // Add evidence to the committed list
  233. // As the evidence is stored in the block store we only need to record the height that it was saved at.
  234. key := keyCommitted(ev)
  235. h := gogotypes.Int64Value{Value: height}
  236. evBytes, err := proto.Marshal(&h)
  237. if err != nil {
  238. panic(err)
  239. }
  240. if err := evpool.evidenceStore.Set(key, evBytes); err != nil {
  241. evpool.logger.Error("Unable to add committed evidence", "err", err)
  242. }
  243. }
  244. // remove committed evidence from the clist
  245. if len(blockEvidenceMap) != 0 {
  246. evpool.removeEvidenceFromList(blockEvidenceMap)
  247. }
  248. return abciEvidence
  249. }
  250. // EvidenceFront goes to the first evidence in the clist
  251. func (evpool *Pool) EvidenceFront() *clist.CElement {
  252. return evpool.evidenceList.Front()
  253. }
  254. // EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil
  255. func (evpool *Pool) EvidenceWaitChan() <-chan struct{} {
  256. return evpool.evidenceList.WaitChan()
  257. }
  258. // SetLogger sets the Logger.
  259. func (evpool *Pool) SetLogger(l log.Logger) {
  260. evpool.logger = l
  261. }
  262. // State returns the current state of the evpool.
  263. func (evpool *Pool) State() sm.State {
  264. evpool.mtx.Lock()
  265. defer evpool.mtx.Unlock()
  266. return evpool.state
  267. }
  268. //--------------------------------------------------------------------------
  269. // Info is a wrapper around the evidence that the evidence pool receives with extensive
  270. // information of what validators were malicious, the time of the attack and the total voting power
  271. // This is saved as a form of cache so that the evidence pool can easily produce the ABCI Evidence
  272. // needed to be sent to the application.
  273. type info struct {
  274. Evidence types.Evidence
  275. Time time.Time
  276. Validators []*types.Validator
  277. TotalVotingPower int64
  278. ByteSize int64
  279. }
  280. // ToProto encodes into protobuf
  281. func (ei info) ToProto() (*evproto.Info, error) {
  282. evpb, err := types.EvidenceToProto(ei.Evidence)
  283. if err != nil {
  284. return nil, err
  285. }
  286. valsProto := make([]*tmproto.Validator, len(ei.Validators))
  287. for i := 0; i < len(ei.Validators); i++ {
  288. valp, err := ei.Validators[i].ToProto()
  289. if err != nil {
  290. return nil, err
  291. }
  292. valsProto[i] = valp
  293. }
  294. return &evproto.Info{
  295. Evidence: *evpb,
  296. Time: ei.Time,
  297. Validators: valsProto,
  298. TotalVotingPower: ei.TotalVotingPower,
  299. }, nil
  300. }
  301. // InfoFromProto decodes from protobuf into Info
  302. func infoFromProto(proto *evproto.Info) (info, error) {
  303. if proto == nil {
  304. return info{}, errors.New("nil evidence info")
  305. }
  306. ev, err := types.EvidenceFromProto(&proto.Evidence)
  307. if err != nil {
  308. return info{}, err
  309. }
  310. vals := make([]*types.Validator, len(proto.Validators))
  311. for i := 0; i < len(proto.Validators); i++ {
  312. val, err := types.ValidatorFromProto(proto.Validators[i])
  313. if err != nil {
  314. return info{}, err
  315. }
  316. vals[i] = val
  317. }
  318. return info{
  319. Evidence: ev,
  320. Time: proto.Time,
  321. Validators: vals,
  322. TotalVotingPower: proto.TotalVotingPower,
  323. ByteSize: int64(proto.Evidence.Size()),
  324. }, nil
  325. }
  326. //--------------------------------------------------------------------------
  327. // fastCheck leverages the fact that the evidence pool may have already verified the evidence to see if it can
  328. // quickly conclude that the evidence is already valid.
  329. func (evpool *Pool) fastCheck(ev types.Evidence) bool {
  330. key := keyPending(ev)
  331. if lcae, ok := ev.(*types.LightClientAttackEvidence); ok {
  332. evBytes, err := evpool.evidenceStore.Get(key)
  333. if evBytes == nil { // the evidence is not in the nodes pending list
  334. return false
  335. }
  336. if err != nil {
  337. evpool.logger.Error("Failed to load evidence", "err", err, "evidence", lcae)
  338. return false
  339. }
  340. evInfo, err := bytesToInfo(evBytes)
  341. if err != nil {
  342. evpool.logger.Error("Failed to convert evidence from proto", "err", err, "evidence", lcae)
  343. return false
  344. }
  345. // ensure that all the validators that the evidence pool have found to be malicious
  346. // are present in the list of commit signatures in the conflicting block
  347. OUTER:
  348. for _, sig := range lcae.ConflictingBlock.Commit.Signatures {
  349. for _, val := range evInfo.Validators {
  350. if bytes.Equal(val.Address, sig.ValidatorAddress) {
  351. continue OUTER
  352. }
  353. }
  354. // a validator we know is malicious is not included in the commit
  355. evpool.logger.Info("Fast check failed: a validator we know is malicious is not " +
  356. "in the commit sigs. Reverting to full verification")
  357. return false
  358. }
  359. return true
  360. }
  361. // for all other evidence the evidence pool just checks if it is already in the pending db
  362. return evpool.isPending(ev)
  363. }
  364. // IsExpired checks whether evidence or a polc is expired by checking whether a height and time is older
  365. // than set by the evidence consensus parameters
  366. func (evpool *Pool) isExpired(height int64, time time.Time) bool {
  367. var (
  368. params = evpool.State().ConsensusParams.Evidence
  369. ageDuration = evpool.State().LastBlockTime.Sub(time)
  370. ageNumBlocks = evpool.State().LastBlockHeight - height
  371. )
  372. return ageNumBlocks > params.MaxAgeNumBlocks &&
  373. ageDuration > params.MaxAgeDuration
  374. }
  375. // IsCommitted returns true if we have already seen this exact evidence and it is already marked as committed.
  376. func (evpool *Pool) isCommitted(evidence types.Evidence) bool {
  377. key := keyCommitted(evidence)
  378. ok, err := evpool.evidenceStore.Has(key)
  379. if err != nil {
  380. evpool.logger.Error("Unable to find committed evidence", "err", err)
  381. }
  382. return ok
  383. }
  384. // IsPending checks whether the evidence is already pending. DB errors are passed to the logger.
  385. func (evpool *Pool) isPending(evidence types.Evidence) bool {
  386. key := keyPending(evidence)
  387. ok, err := evpool.evidenceStore.Has(key)
  388. if err != nil {
  389. evpool.logger.Error("Unable to find pending evidence", "err", err)
  390. }
  391. return ok
  392. }
  393. func (evpool *Pool) addPendingEvidence(evInfo *info) error {
  394. evpb, err := evInfo.ToProto()
  395. if err != nil {
  396. return fmt.Errorf("unable to convert to proto, err: %w", err)
  397. }
  398. evBytes, err := evpb.Marshal()
  399. if err != nil {
  400. return fmt.Errorf("unable to marshal evidence: %w", err)
  401. }
  402. key := keyPending(evInfo.Evidence)
  403. err = evpool.evidenceStore.Set(key, evBytes)
  404. if err != nil {
  405. return fmt.Errorf("can't persist evidence: %w", err)
  406. }
  407. atomic.AddUint32(&evpool.evidenceSize, 1)
  408. return nil
  409. }
  410. func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
  411. key := keyPending(evidence)
  412. if err := evpool.evidenceStore.Delete(key); err != nil {
  413. evpool.logger.Error("Unable to delete pending evidence", "err", err)
  414. } else {
  415. atomic.AddUint32(&evpool.evidenceSize, ^uint32(0))
  416. evpool.logger.Info("Deleted pending evidence", "evidence", evidence)
  417. }
  418. }
  419. // listEvidence retrieves lists evidence from oldest to newest within maxBytes.
  420. // If maxBytes is -1, there's no cap on the size of returned evidence.
  421. func (evpool *Pool) listEvidence(prefixKey byte, maxBytes int64) ([]types.Evidence, int64, error) {
  422. var totalSize int64
  423. var evidence []types.Evidence
  424. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{prefixKey})
  425. if err != nil {
  426. return nil, totalSize, fmt.Errorf("database error: %v", err)
  427. }
  428. defer iter.Close()
  429. for ; iter.Valid(); iter.Next() {
  430. evInfo, err := bytesToInfo(iter.Value())
  431. if err != nil {
  432. return nil, totalSize, err
  433. }
  434. totalSize += evInfo.ByteSize
  435. if maxBytes != -1 && totalSize > maxBytes {
  436. return evidence, totalSize - evInfo.ByteSize, nil
  437. }
  438. evidence = append(evidence, evInfo.Evidence)
  439. }
  440. return evidence, totalSize, nil
  441. }
  442. func (evpool *Pool) removeExpiredPendingEvidence() (int64, time.Time) {
  443. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPending})
  444. if err != nil {
  445. evpool.logger.Error("Unable to iterate over pending evidence", "err", err)
  446. return evpool.State().LastBlockHeight, evpool.State().LastBlockTime
  447. }
  448. defer iter.Close()
  449. blockEvidenceMap := make(map[string]struct{})
  450. for ; iter.Valid(); iter.Next() {
  451. evInfo, err := bytesToInfo(iter.Value())
  452. if err != nil {
  453. evpool.logger.Error("Error in transition evidence from protobuf", "err", err)
  454. continue
  455. }
  456. if !evpool.isExpired(evInfo.Evidence.Height(), evInfo.Time) {
  457. if len(blockEvidenceMap) != 0 {
  458. evpool.removeEvidenceFromList(blockEvidenceMap)
  459. }
  460. // return the height and time with which this evidence will have expired so we know when to prune next
  461. return evInfo.Evidence.Height() + evpool.State().ConsensusParams.Evidence.MaxAgeNumBlocks + 1,
  462. evInfo.Time.Add(evpool.State().ConsensusParams.Evidence.MaxAgeDuration).Add(time.Second)
  463. }
  464. evpool.removePendingEvidence(evInfo.Evidence)
  465. blockEvidenceMap[evMapKey(evInfo.Evidence)] = struct{}{}
  466. }
  467. // We either have no pending evidence or all evidence has expired
  468. if len(blockEvidenceMap) != 0 {
  469. evpool.removeEvidenceFromList(blockEvidenceMap)
  470. }
  471. return evpool.State().LastBlockHeight, evpool.State().LastBlockTime
  472. }
  473. func (evpool *Pool) removeEvidenceFromList(
  474. blockEvidenceMap map[string]struct{}) {
  475. for e := evpool.evidenceList.Front(); e != nil; e = e.Next() {
  476. // Remove from clist
  477. ev := e.Value.(types.Evidence)
  478. if _, ok := blockEvidenceMap[evMapKey(ev)]; ok {
  479. evpool.evidenceList.Remove(e)
  480. e.DetachPrev()
  481. }
  482. }
  483. }
  484. func (evpool *Pool) updateState(state sm.State) {
  485. evpool.mtx.Lock()
  486. defer evpool.mtx.Unlock()
  487. evpool.state = state
  488. }
  489. func bytesToInfo(evBytes []byte) (info, error) {
  490. var evpb evproto.Info
  491. err := evpb.Unmarshal(evBytes)
  492. if err != nil {
  493. return info{}, err
  494. }
  495. return infoFromProto(&evpb)
  496. }
  497. func evMapKey(ev types.Evidence) string {
  498. return string(ev.Hash())
  499. }
  500. // big endian padded hex
  501. func bE(h int64) string {
  502. return fmt.Sprintf("%0.16X", h)
  503. }
  504. func keyCommitted(evidence types.Evidence) []byte {
  505. return append([]byte{baseKeyCommitted}, keySuffix(evidence)...)
  506. }
  507. func keyPending(evidence types.Evidence) []byte {
  508. return append([]byte{baseKeyPending}, keySuffix(evidence)...)
  509. }
  510. func keySuffix(evidence types.Evidence) []byte {
  511. return []byte(fmt.Sprintf("%s/%X", bE(evidence.Height()), evidence.Hash()))
  512. }