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.

826 lines
26 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
5 years ago
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
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
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
  1. package evidence
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. "github.com/gogo/protobuf/proto"
  7. gogotypes "github.com/gogo/protobuf/types"
  8. dbm "github.com/tendermint/tm-db"
  9. clist "github.com/tendermint/tendermint/libs/clist"
  10. "github.com/tendermint/tendermint/libs/log"
  11. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  12. sm "github.com/tendermint/tendermint/state"
  13. "github.com/tendermint/tendermint/store"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. const (
  17. baseKeyCommitted = byte(0x00)
  18. baseKeyPending = byte(0x01)
  19. baseKeyPOLC = byte(0x02)
  20. baseKeyAwaitingTrial = byte(0x03)
  21. )
  22. // Pool maintains a pool of valid evidence to be broadcasted and committed
  23. type Pool struct {
  24. logger log.Logger
  25. evidenceStore dbm.DB
  26. evidenceList *clist.CList // concurrent linked-list of evidence
  27. // needed to load validators to verify evidence
  28. stateDB dbm.DB
  29. // needed to load headers to verify evidence
  30. blockStore *store.BlockStore
  31. mtx sync.Mutex
  32. // latest state
  33. state sm.State
  34. // a map of active validators and respective last heights validator is active
  35. // if it was in validator set after EvidenceParams.MaxAgeNumBlocks or
  36. // currently is (ie. [MaxAgeNumBlocks, CurrentHeight])
  37. // In simple words, it means it's still bonded -> therefore slashable.
  38. valToLastHeight valToLastHeightMap
  39. nextEvidenceTrialEndedHeight int64
  40. }
  41. // Validator.Address -> Last height it was in validator set
  42. type valToLastHeightMap map[string]int64
  43. // Creates a new pool. If using an existing evidence store, it will add all pending evidence
  44. // to the concurrent list.
  45. func NewPool(stateDB, evidenceDB dbm.DB, blockStore *store.BlockStore) (*Pool, error) {
  46. var (
  47. state = sm.LoadState(stateDB)
  48. )
  49. valToLastHeight, err := buildValToLastHeightMap(state, stateDB, blockStore)
  50. if err != nil {
  51. return nil, err
  52. }
  53. pool := &Pool{
  54. stateDB: stateDB,
  55. blockStore: blockStore,
  56. state: state,
  57. logger: log.NewNopLogger(),
  58. evidenceStore: evidenceDB,
  59. evidenceList: clist.New(),
  60. valToLastHeight: valToLastHeight,
  61. nextEvidenceTrialEndedHeight: -1,
  62. }
  63. // if pending evidence already in db, in event of prior failure, then load it back to the evidenceList
  64. evList := pool.AllPendingEvidence()
  65. for _, ev := range evList {
  66. pool.evidenceList.PushBack(ev)
  67. }
  68. return pool, nil
  69. }
  70. // PendingEvidence is used primarily as part of block proposal and returns up to maxNum of uncommitted evidence.
  71. // If maxNum is -1, all evidence is returned. Pending evidence is prioritized based on time.
  72. func (evpool *Pool) PendingEvidence(maxNum uint32) []types.Evidence {
  73. evpool.removeExpiredPendingEvidence()
  74. evidence, err := evpool.listEvidence(baseKeyPending, int64(maxNum))
  75. if err != nil {
  76. evpool.logger.Error("Unable to retrieve pending evidence", "err", err)
  77. }
  78. return evidence
  79. }
  80. // AllPendingEvidence returns all evidence ready to be proposed and committed.
  81. func (evpool *Pool) AllPendingEvidence() []types.Evidence {
  82. evpool.removeExpiredPendingEvidence()
  83. evidence, err := evpool.listEvidence(baseKeyPending, -1)
  84. if err != nil {
  85. evpool.logger.Error("Unable to retrieve pending evidence", "err", err)
  86. }
  87. return evidence
  88. }
  89. // Update uses the latest block & state to update its copy of the state,
  90. // validator to last height map and calls MarkEvidenceAsCommitted.
  91. func (evpool *Pool) Update(block *types.Block, state sm.State) {
  92. // sanity check
  93. if state.LastBlockHeight != block.Height {
  94. panic(fmt.Sprintf("Failed EvidencePool.Update sanity check: got state.Height=%d with block.Height=%d",
  95. state.LastBlockHeight,
  96. block.Height,
  97. ),
  98. )
  99. }
  100. // update the state
  101. evpool.updateState(state)
  102. // remove evidence from pending and mark committed
  103. evpool.MarkEvidenceAsCommitted(block.Height, block.Evidence.Evidence)
  104. // prune pending, committed and potential evidence and polc's periodically
  105. if block.Height%state.ConsensusParams.Evidence.MaxAgeNumBlocks == 0 {
  106. evpool.logger.Debug("Pruning no longer necessary evidence")
  107. evpool.pruneExpiredPOLC()
  108. evpool.removeExpiredPendingEvidence()
  109. }
  110. evpool.updateValToLastHeight(block.Height, state)
  111. if evpool.nextEvidenceTrialEndedHeight > 0 && block.Height > evpool.nextEvidenceTrialEndedHeight {
  112. evpool.logger.Debug("Upgrading all potential evidence that have served the trial period")
  113. evpool.nextEvidenceTrialEndedHeight = evpool.upgradePotentialAmnesiaEvidence()
  114. }
  115. }
  116. // AddPOLC adds a proof of lock change to the evidence database
  117. // that may be needed in the future to verify votes
  118. func (evpool *Pool) AddPOLC(polc *types.ProofOfLockChange) error {
  119. key := keyPOLC(polc)
  120. pbplc, err := polc.ToProto()
  121. if err != nil {
  122. return err
  123. }
  124. polcBytes, err := proto.Marshal(pbplc)
  125. if err != nil {
  126. return fmt.Errorf("addPOLC: unable to marshal ProofOfLockChange: %w", err)
  127. }
  128. return evpool.evidenceStore.Set(key, polcBytes)
  129. }
  130. // AddEvidence checks the evidence is valid and adds it to the pool. If
  131. // evidence is composite (ConflictingHeadersEvidence), it will be broken up
  132. // into smaller pieces.
  133. func (evpool *Pool) AddEvidence(evidence types.Evidence) error {
  134. var (
  135. state = evpool.State()
  136. evList = []types.Evidence{evidence}
  137. )
  138. evpool.logger.Debug("Attempting to add evidence", "ev", evidence)
  139. valSet, err := sm.LoadValidators(evpool.stateDB, evidence.Height())
  140. if err != nil {
  141. return fmt.Errorf("can't load validators at height #%d: %w", evidence.Height(), err)
  142. }
  143. // Break composite evidence into smaller pieces.
  144. if ce, ok := evidence.(types.CompositeEvidence); ok {
  145. evpool.logger.Info("Breaking up composite evidence", "ev", evidence)
  146. blockMeta := evpool.blockStore.LoadBlockMeta(evidence.Height())
  147. if blockMeta == nil {
  148. return fmt.Errorf("don't have block meta at height #%d", evidence.Height())
  149. }
  150. if err := ce.VerifyComposite(&blockMeta.Header, valSet); err != nil {
  151. return err
  152. }
  153. // XXX: Copy here since this should be a rare case.
  154. evpool.mtx.Lock()
  155. valToLastHeightCopy := make(valToLastHeightMap, len(evpool.valToLastHeight))
  156. for k, v := range evpool.valToLastHeight {
  157. valToLastHeightCopy[k] = v
  158. }
  159. evpool.mtx.Unlock()
  160. evList = ce.Split(&blockMeta.Header, valSet, valToLastHeightCopy)
  161. }
  162. for _, ev := range evList {
  163. if evpool.Has(ev) {
  164. // if it is an amnesia evidence we have but POLC is not absent then
  165. // we should still process it
  166. if ae, ok := ev.(*types.AmnesiaEvidence); !ok || ae.Polc.IsAbsent() {
  167. continue
  168. }
  169. }
  170. // For lunatic validator evidence, a header needs to be fetched.
  171. var header *types.Header
  172. if _, ok := ev.(*types.LunaticValidatorEvidence); ok {
  173. header = evpool.Header(ev.Height())
  174. if header == nil {
  175. return fmt.Errorf("don't have block meta at height #%d", ev.Height())
  176. }
  177. }
  178. // 1) Verify against state.
  179. if err := sm.VerifyEvidence(evpool.stateDB, state, ev, header); err != nil {
  180. return fmt.Errorf("failed to verify %v: %w", ev, err)
  181. }
  182. // For potential amnesia evidence, if this node is indicted it shall retrieve a polc
  183. // to form AmensiaEvidence else start the trial period for the piece of evidence
  184. if pe, ok := ev.(*types.PotentialAmnesiaEvidence); ok {
  185. if err := evpool.handleInboundPotentialAmnesiaEvidence(pe); err != nil {
  186. return err
  187. }
  188. continue
  189. } else if ae, ok := ev.(*types.AmnesiaEvidence); ok {
  190. if ae.Polc.IsAbsent() && ae.PotentialAmnesiaEvidence.VoteA.Round <
  191. ae.PotentialAmnesiaEvidence.VoteB.Round {
  192. if err := evpool.handleInboundPotentialAmnesiaEvidence(ae.PotentialAmnesiaEvidence); err != nil {
  193. return fmt.Errorf("failed to handle amnesia evidence, err: %w", err)
  194. }
  195. continue
  196. } else {
  197. // we are going to add this amnesia evidence and check if we already have an amnesia evidence or potential
  198. // amnesia evidence that addesses the same case
  199. aeWithoutPolc := types.NewAmnesiaEvidence(ae.PotentialAmnesiaEvidence, types.NewEmptyPOLC())
  200. if evpool.IsPending(aeWithoutPolc) {
  201. evpool.removePendingEvidence(aeWithoutPolc)
  202. } else if evpool.IsOnTrial(ae.PotentialAmnesiaEvidence) {
  203. key := keyAwaitingTrial(ae.PotentialAmnesiaEvidence)
  204. if err := evpool.evidenceStore.Delete(key); err != nil {
  205. evpool.logger.Error("Failed to remove potential amnesia evidence from database", "err", err)
  206. }
  207. }
  208. }
  209. }
  210. // 2) Save to store.
  211. if err := evpool.addPendingEvidence(ev); err != nil {
  212. return fmt.Errorf("database error when adding evidence: %v", err)
  213. }
  214. // 3) Add evidence to clist.
  215. evpool.evidenceList.PushBack(ev)
  216. evpool.logger.Info("Verified new evidence of byzantine behaviour", "evidence", ev)
  217. }
  218. return nil
  219. }
  220. // MarkEvidenceAsCommitted marks all the evidence as committed and removes it
  221. // from the queue.
  222. func (evpool *Pool) MarkEvidenceAsCommitted(height int64, evidence []types.Evidence) {
  223. // make a map of committed evidence to remove from the clist
  224. blockEvidenceMap := make(map[string]struct{})
  225. for _, ev := range evidence {
  226. // As the evidence is stored in the block store we only need to record the height that it was saved at.
  227. key := keyCommitted(ev)
  228. h := gogotypes.Int64Value{Value: height}
  229. evBytes, err := proto.Marshal(&h)
  230. if err != nil {
  231. panic(err)
  232. }
  233. if err := evpool.evidenceStore.Set(key, evBytes); err != nil {
  234. evpool.logger.Error("Unable to add committed evidence", "err", err)
  235. // if we can't move evidence to committed then don't remove the evidence from pending
  236. continue
  237. }
  238. // if pending, remove from that bucket, remember not all evidence has been seen before
  239. if evpool.IsPending(ev) {
  240. evpool.removePendingEvidence(ev)
  241. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  242. }
  243. }
  244. // remove committed evidence from the clist
  245. if len(blockEvidenceMap) != 0 {
  246. evpool.removeEvidenceFromList(blockEvidenceMap)
  247. }
  248. }
  249. // Has checks whether the evidence exists either pending or already committed
  250. func (evpool *Pool) Has(evidence types.Evidence) bool {
  251. return evpool.IsPending(evidence) || evpool.IsCommitted(evidence) || evpool.IsOnTrial(evidence)
  252. }
  253. // IsEvidenceExpired checks whether evidence is past the maximum age where it can be used
  254. func (evpool *Pool) IsEvidenceExpired(evidence types.Evidence) bool {
  255. return evpool.IsExpired(evidence.Height(), evidence.Time())
  256. }
  257. // IsExpired checks whether evidence or a polc is expired by checking whether a height and time is older
  258. // than set by the evidence consensus parameters
  259. func (evpool *Pool) IsExpired(height int64, time time.Time) bool {
  260. var (
  261. params = evpool.State().ConsensusParams.Evidence
  262. ageDuration = evpool.State().LastBlockTime.Sub(time)
  263. ageNumBlocks = evpool.State().LastBlockHeight - height
  264. )
  265. return ageNumBlocks > params.MaxAgeNumBlocks &&
  266. ageDuration > params.MaxAgeDuration
  267. }
  268. // IsCommitted returns true if we have already seen this exact evidence and it is already marked as committed.
  269. func (evpool *Pool) IsCommitted(evidence types.Evidence) bool {
  270. key := keyCommitted(evidence)
  271. ok, err := evpool.evidenceStore.Has(key)
  272. if err != nil {
  273. evpool.logger.Error("Unable to find committed evidence", "err", err)
  274. }
  275. return ok
  276. }
  277. // IsPending checks whether the evidence is already pending. DB errors are passed to the logger.
  278. func (evpool *Pool) IsPending(evidence types.Evidence) bool {
  279. key := keyPending(evidence)
  280. ok, err := evpool.evidenceStore.Has(key)
  281. if err != nil {
  282. evpool.logger.Error("Unable to find pending evidence", "err", err)
  283. }
  284. return ok
  285. }
  286. // IsOnTrial checks whether a piece of evidence is in the awaiting bucket.
  287. // Only Potential Amnesia Evidence is stored here.
  288. func (evpool *Pool) IsOnTrial(evidence types.Evidence) bool {
  289. pe, ok := evidence.(*types.PotentialAmnesiaEvidence)
  290. if !ok {
  291. return false
  292. }
  293. key := keyAwaitingTrial(pe)
  294. ok, err := evpool.evidenceStore.Has(key)
  295. if err != nil {
  296. evpool.logger.Error("Unable to find evidence on trial", "err", err)
  297. }
  298. return ok
  299. }
  300. // RetrievePOLC attempts to find a polc at the given height and round, if not there than exist returns false, all
  301. // database errors are automatically logged
  302. func (evpool *Pool) RetrievePOLC(height int64, round int32) (*types.ProofOfLockChange, error) {
  303. var pbpolc tmproto.ProofOfLockChange
  304. key := keyPOLCFromHeightAndRound(height, round)
  305. polcBytes, err := evpool.evidenceStore.Get(key)
  306. if err != nil {
  307. evpool.logger.Error("Unable to retrieve polc", "err", err)
  308. return nil, err
  309. }
  310. // polc doesn't exist
  311. if polcBytes == nil {
  312. return nil, nil
  313. }
  314. err = proto.Unmarshal(polcBytes, &pbpolc)
  315. if err != nil {
  316. return nil, err
  317. }
  318. polc, err := types.ProofOfLockChangeFromProto(&pbpolc)
  319. if err != nil {
  320. return nil, err
  321. }
  322. return polc, err
  323. }
  324. // EvidenceFront goes to the first evidence in the clist
  325. func (evpool *Pool) EvidenceFront() *clist.CElement {
  326. return evpool.evidenceList.Front()
  327. }
  328. // EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil
  329. func (evpool *Pool) EvidenceWaitChan() <-chan struct{} {
  330. return evpool.evidenceList.WaitChan()
  331. }
  332. // SetLogger sets the Logger.
  333. func (evpool *Pool) SetLogger(l log.Logger) {
  334. evpool.logger = l
  335. }
  336. // Header gets the header from the block store at a specified height.
  337. // Is used for validation of LunaticValidatorEvidence
  338. func (evpool *Pool) Header(height int64) *types.Header {
  339. blockMeta := evpool.blockStore.LoadBlockMeta(height)
  340. if blockMeta == nil {
  341. return nil
  342. }
  343. return &blockMeta.Header
  344. }
  345. // ValidatorLastHeight returns the last height of the validator w/ the
  346. // given address. 0 - if address never was a validator or was such a
  347. // long time ago (> ConsensusParams.Evidence.MaxAgeDuration && >
  348. // ConsensusParams.Evidence.MaxAgeNumBlocks).
  349. func (evpool *Pool) ValidatorLastHeight(address []byte) int64 {
  350. evpool.mtx.Lock()
  351. defer evpool.mtx.Unlock()
  352. h, ok := evpool.valToLastHeight[string(address)]
  353. if !ok {
  354. return 0
  355. }
  356. return h
  357. }
  358. // State returns the current state of the evpool.
  359. func (evpool *Pool) State() sm.State {
  360. evpool.mtx.Lock()
  361. defer evpool.mtx.Unlock()
  362. return evpool.state
  363. }
  364. func (evpool *Pool) addPendingEvidence(evidence types.Evidence) error {
  365. evi, err := types.EvidenceToProto(evidence)
  366. if err != nil {
  367. return fmt.Errorf("unable to convert to proto, err: %w", err)
  368. }
  369. evBytes, err := proto.Marshal(evi)
  370. if err != nil {
  371. return fmt.Errorf("unable to marshal evidence: %w", err)
  372. }
  373. key := keyPending(evidence)
  374. return evpool.evidenceStore.Set(key, evBytes)
  375. }
  376. func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
  377. key := keyPending(evidence)
  378. if err := evpool.evidenceStore.Delete(key); err != nil {
  379. evpool.logger.Error("Unable to delete pending evidence", "err", err)
  380. } else {
  381. evpool.logger.Info("Deleted pending evidence", "evidence", evidence)
  382. }
  383. }
  384. // listEvidence lists up to maxNum pieces of evidence for the given prefix key.
  385. // If maxNum is -1, there's no cap on the size of returned evidence.
  386. func (evpool *Pool) listEvidence(prefixKey byte, maxNum int64) ([]types.Evidence, error) {
  387. var count int64
  388. var evidence []types.Evidence
  389. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{prefixKey})
  390. if err != nil {
  391. return nil, fmt.Errorf("database error: %v", err)
  392. }
  393. defer iter.Close()
  394. for ; iter.Valid(); iter.Next() {
  395. if count == maxNum {
  396. return evidence, nil
  397. }
  398. count++
  399. val := iter.Value()
  400. var (
  401. ev types.Evidence
  402. evpb tmproto.Evidence
  403. )
  404. err := proto.Unmarshal(val, &evpb)
  405. if err != nil {
  406. return nil, err
  407. }
  408. ev, err = types.EvidenceFromProto(&evpb)
  409. if err != nil {
  410. return nil, err
  411. }
  412. evidence = append(evidence, ev)
  413. }
  414. return evidence, nil
  415. }
  416. func (evpool *Pool) removeExpiredPendingEvidence() {
  417. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPending})
  418. if err != nil {
  419. evpool.logger.Error("Unable to iterate over pending evidence", "err", err)
  420. return
  421. }
  422. defer iter.Close()
  423. blockEvidenceMap := make(map[string]struct{})
  424. for ; iter.Valid(); iter.Next() {
  425. evBytes := iter.Value()
  426. var (
  427. ev types.Evidence
  428. evpb tmproto.Evidence
  429. )
  430. err := proto.Unmarshal(evBytes, &evpb)
  431. if err != nil {
  432. evpool.logger.Error("Unable to unmarshal Evidence", "err", err)
  433. continue
  434. }
  435. ev, err = types.EvidenceFromProto(&evpb)
  436. if err != nil {
  437. evpool.logger.Error("Error in transition evidence from protobuf", "err", err)
  438. continue
  439. }
  440. if !evpool.IsExpired(ev.Height()-1, ev.Time()) {
  441. if len(blockEvidenceMap) != 0 {
  442. evpool.removeEvidenceFromList(blockEvidenceMap)
  443. }
  444. return
  445. }
  446. evpool.removePendingEvidence(ev)
  447. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  448. }
  449. }
  450. func (evpool *Pool) removeEvidenceFromList(
  451. blockEvidenceMap map[string]struct{}) {
  452. for e := evpool.evidenceList.Front(); e != nil; e = e.Next() {
  453. // Remove from clist
  454. ev := e.Value.(types.Evidence)
  455. if _, ok := blockEvidenceMap[evMapKey(ev)]; ok {
  456. evpool.evidenceList.Remove(e)
  457. e.DetachPrev()
  458. }
  459. }
  460. }
  461. func (evpool *Pool) pruneExpiredPOLC() {
  462. evpool.logger.Debug("Pruning expired POLC's")
  463. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPOLC})
  464. if err != nil {
  465. evpool.logger.Error("Unable to iterate over POLC's", "err", err)
  466. return
  467. }
  468. defer iter.Close()
  469. for ; iter.Valid(); iter.Next() {
  470. proofBytes := iter.Value()
  471. var (
  472. pbproof tmproto.ProofOfLockChange
  473. )
  474. err := proto.Unmarshal(proofBytes, &pbproof)
  475. if err != nil {
  476. evpool.logger.Error("Unable to unmarshal POLC", "err", err)
  477. continue
  478. }
  479. proof, err := types.ProofOfLockChangeFromProto(&pbproof)
  480. if err != nil {
  481. evpool.logger.Error("Unable to transition POLC from protobuf", "err", err)
  482. continue
  483. }
  484. if !evpool.IsExpired(proof.Height()-1, proof.Time()) {
  485. return
  486. }
  487. err = evpool.evidenceStore.Delete(iter.Key())
  488. if err != nil {
  489. evpool.logger.Error("Unable to delete expired POLC", "err", err)
  490. continue
  491. }
  492. evpool.logger.Info("Deleted expired POLC", "polc", proof)
  493. }
  494. }
  495. func (evpool *Pool) updateState(state sm.State) {
  496. evpool.mtx.Lock()
  497. defer evpool.mtx.Unlock()
  498. evpool.state = state
  499. }
  500. // upgrades any potential evidence that has undergone the trial period and is primed to be made into
  501. // amnesia evidence
  502. func (evpool *Pool) upgradePotentialAmnesiaEvidence() int64 {
  503. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyAwaitingTrial})
  504. if err != nil {
  505. evpool.logger.Error("Unable to iterate over POLC's", "err", err)
  506. return -1
  507. }
  508. defer iter.Close()
  509. trialPeriod := evpool.State().ConsensusParams.Evidence.ProofTrialPeriod
  510. currentHeight := evpool.State().LastBlockHeight
  511. // 1) Iterate through all potential amnesia evidence in order of height
  512. for ; iter.Valid(); iter.Next() {
  513. paeBytes := iter.Value()
  514. // 2) Retrieve the evidence
  515. var evpb tmproto.Evidence
  516. err := evpb.Unmarshal(paeBytes)
  517. if err != nil {
  518. evpool.logger.Error("Unable to unmarshal potential amnesia evidence", "err", err)
  519. continue
  520. }
  521. ev, err := types.EvidenceFromProto(&evpb)
  522. if err != nil {
  523. evpool.logger.Error("Converting from proto to evidence", "err", err)
  524. continue
  525. }
  526. // 3) Check if the trial period has lapsed and amnesia evidence can be formed
  527. if pe, ok := ev.(*types.PotentialAmnesiaEvidence); ok {
  528. if pe.Primed(trialPeriod, currentHeight) {
  529. ae := types.NewAmnesiaEvidence(pe, types.NewEmptyPOLC())
  530. err := evpool.addPendingEvidence(ae)
  531. if err != nil {
  532. evpool.logger.Error("Unable to add amnesia evidence", "err", err)
  533. continue
  534. }
  535. evpool.logger.Info("Upgraded to amnesia evidence", "amnesiaEvidence", ae)
  536. err = evpool.evidenceStore.Delete(iter.Key())
  537. if err != nil {
  538. evpool.logger.Error("Unable to delete potential amnesia evidence", "err", err)
  539. continue
  540. }
  541. } else {
  542. evpool.logger.Debug("Potential amnesia evidence is not ready to be upgraded. Ready at", "height",
  543. pe.HeightStamp+trialPeriod, "currentHeight", currentHeight)
  544. // once we reach a piece of evidence that isn't ready send back the height with which it will be ready
  545. return pe.HeightStamp + trialPeriod
  546. }
  547. }
  548. }
  549. // if we have no evidence left to process we want to reset nextEvidenceTrialEndedHeight
  550. return -1
  551. }
  552. func (evpool *Pool) handleInboundPotentialAmnesiaEvidence(pe *types.PotentialAmnesiaEvidence) error {
  553. var (
  554. height = pe.Height()
  555. exists = false
  556. polc *types.ProofOfLockChange
  557. err error
  558. )
  559. evpool.logger.Debug("Received Potential Amnesia Evidence", "pe", pe)
  560. // a) first try to find a corresponding polc
  561. for round := pe.VoteB.Round; round > pe.VoteA.Round; round-- {
  562. polc, err = evpool.RetrievePOLC(height, round)
  563. if err != nil {
  564. evpool.logger.Error("Failed to retrieve polc for potential amnesia evidence", "err", err, "pae", pe.String())
  565. continue
  566. }
  567. if polc != nil && !polc.IsAbsent() {
  568. evpool.logger.Debug("Found polc for potential amnesia evidence", "polc", polc)
  569. // we should not need to verify it if both the polc and potential amnesia evidence have already
  570. // been verified. We replace the potential amnesia evidence.
  571. ae := types.NewAmnesiaEvidence(pe, polc)
  572. err := evpool.AddEvidence(ae)
  573. if err != nil {
  574. evpool.logger.Error("Failed to create amnesia evidence from potential amnesia evidence", "err", err)
  575. // revert back to processing potential amnesia evidence
  576. exists = false
  577. } else {
  578. evpool.logger.Info("Formed amnesia evidence from own polc", "amnesiaEvidence", ae)
  579. }
  580. break
  581. }
  582. }
  583. // stamp height that the evidence was received
  584. pe.HeightStamp = evpool.State().LastBlockHeight
  585. // b) check if amnesia evidence can be made now or if we need to enact the trial period
  586. if !exists && pe.Primed(1, pe.HeightStamp) {
  587. evpool.logger.Debug("PotentialAmnesiaEvidence can be instantly upgraded")
  588. err := evpool.AddEvidence(types.NewAmnesiaEvidence(pe, types.NewEmptyPOLC()))
  589. if err != nil {
  590. return err
  591. }
  592. } else if !exists && evpool.State().LastBlockHeight+evpool.State().ConsensusParams.Evidence.ProofTrialPeriod <
  593. pe.Height()+evpool.State().ConsensusParams.Evidence.MaxAgeNumBlocks {
  594. // if we can't find a proof of lock change and we know that the trial period will finish before the
  595. // evidence has expired, then we commence the trial period by saving it in the awaiting bucket
  596. pbe, err := types.EvidenceToProto(pe)
  597. if err != nil {
  598. return err
  599. }
  600. evBytes, err := pbe.Marshal()
  601. if err != nil {
  602. return err
  603. }
  604. key := keyAwaitingTrial(pe)
  605. err = evpool.evidenceStore.Set(key, evBytes)
  606. if err != nil {
  607. return err
  608. }
  609. evpool.logger.Debug("Valid potential amnesia evidence has been added. Starting trial period",
  610. "ev", pe)
  611. // keep track of when the next pe has finished the trial period
  612. if evpool.nextEvidenceTrialEndedHeight == -1 {
  613. evpool.nextEvidenceTrialEndedHeight = pe.Height() + evpool.State().ConsensusParams.Evidence.ProofTrialPeriod
  614. }
  615. // add to the broadcast list so it can continue to be gossiped
  616. evpool.evidenceList.PushBack(pe)
  617. }
  618. return nil
  619. }
  620. func evMapKey(ev types.Evidence) string {
  621. return string(ev.Hash())
  622. }
  623. func (evpool *Pool) updateValToLastHeight(blockHeight int64, state sm.State) {
  624. // Update current validators & add new ones.
  625. for _, val := range state.Validators.Validators {
  626. evpool.valToLastHeight[string(val.Address)] = blockHeight
  627. }
  628. // Remove validators outside of MaxAgeNumBlocks & MaxAgeDuration.
  629. removeHeight := blockHeight - state.ConsensusParams.Evidence.MaxAgeNumBlocks
  630. if removeHeight >= 1 {
  631. for val, height := range evpool.valToLastHeight {
  632. if height <= removeHeight {
  633. delete(evpool.valToLastHeight, val)
  634. }
  635. }
  636. }
  637. }
  638. func buildValToLastHeightMap(state sm.State, stateDB dbm.DB, blockStore *store.BlockStore) (valToLastHeightMap, error) {
  639. var (
  640. valToLastHeight = make(map[string]int64)
  641. params = state.ConsensusParams.Evidence
  642. numBlocks = int64(0)
  643. minAgeTime = time.Now().Add(-params.MaxAgeDuration)
  644. height = state.LastBlockHeight
  645. )
  646. if height == 0 {
  647. return valToLastHeight, nil
  648. }
  649. meta := blockStore.LoadBlockMeta(height)
  650. if meta == nil {
  651. return nil, fmt.Errorf("block meta for height %d not found", height)
  652. }
  653. blockTime := meta.Header.Time
  654. // From state.LastBlockHeight, build a map of "active" validators until
  655. // MaxAgeNumBlocks is passed and block time is less than now() -
  656. // MaxAgeDuration.
  657. for height >= 1 && (numBlocks <= params.MaxAgeNumBlocks || !blockTime.Before(minAgeTime)) {
  658. valSet, err := sm.LoadValidators(stateDB, height)
  659. if err != nil {
  660. // last stored height -> return
  661. if _, ok := err.(sm.ErrNoValSetForHeight); ok {
  662. return valToLastHeight, nil
  663. }
  664. return nil, fmt.Errorf("validator set for height %d not found", height)
  665. }
  666. for _, val := range valSet.Validators {
  667. key := string(val.Address)
  668. if _, ok := valToLastHeight[key]; !ok {
  669. valToLastHeight[key] = height
  670. }
  671. }
  672. height--
  673. if height > 0 {
  674. // NOTE: we assume here blockStore and state.Validators are in sync. I.e if
  675. // block N is stored, then validators for height N are also stored in
  676. // state.
  677. meta := blockStore.LoadBlockMeta(height)
  678. if meta == nil {
  679. return nil, fmt.Errorf("block meta for height %d not found", height)
  680. }
  681. blockTime = meta.Header.Time
  682. }
  683. numBlocks++
  684. }
  685. return valToLastHeight, nil
  686. }
  687. // big endian padded hex
  688. func bE(h int64) string {
  689. return fmt.Sprintf("%0.16X", h)
  690. }
  691. func keyCommitted(evidence types.Evidence) []byte {
  692. return append([]byte{baseKeyCommitted}, keySuffix(evidence)...)
  693. }
  694. func keyPending(evidence types.Evidence) []byte {
  695. return append([]byte{baseKeyPending}, keySuffix(evidence)...)
  696. }
  697. func keyAwaitingTrial(evidence types.Evidence) []byte {
  698. return append([]byte{baseKeyAwaitingTrial}, keySuffix(evidence)...)
  699. }
  700. func keyPOLC(polc *types.ProofOfLockChange) []byte {
  701. return keyPOLCFromHeightAndRound(polc.Height(), polc.Round())
  702. }
  703. func keyPOLCFromHeightAndRound(height int64, round int32) []byte {
  704. return append([]byte{baseKeyPOLC}, []byte(fmt.Sprintf("%s/%s", bE(height), bE(int64(round))))...)
  705. }
  706. func keySuffix(evidence types.Evidence) []byte {
  707. return []byte(fmt.Sprintf("%s/%X", bE(evidence.Height()), evidence.Hash()))
  708. }
  709. // ErrInvalidEvidence returns when evidence failed to validate
  710. type ErrInvalidEvidence struct {
  711. Reason error
  712. }
  713. func (e ErrInvalidEvidence) Error() string {
  714. return fmt.Sprintf("evidence is not valid: %v ", e.Reason)
  715. }