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.

750 lines
23 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/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. baseKeyAwaiting = 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. func NewPool(stateDB, evidenceDB dbm.DB, blockStore *store.BlockStore) (*Pool, error) {
  44. var (
  45. state = sm.LoadState(stateDB)
  46. )
  47. valToLastHeight, err := buildValToLastHeightMap(state, stateDB, blockStore)
  48. if err != nil {
  49. return nil, err
  50. }
  51. pool := &Pool{
  52. stateDB: stateDB,
  53. blockStore: blockStore,
  54. state: state,
  55. logger: log.NewNopLogger(),
  56. evidenceStore: evidenceDB,
  57. evidenceList: clist.New(),
  58. valToLastHeight: valToLastHeight,
  59. nextEvidenceTrialEndedHeight: -1,
  60. }
  61. // if pending evidence already in db, in event of prior failure, then load it back to the evidenceList
  62. evList := pool.AllPendingEvidence()
  63. for _, ev := range evList {
  64. pool.evidenceList.PushBack(ev)
  65. }
  66. return pool, nil
  67. }
  68. // PendingEvidence is used primarily as part of block proposal and returns up to maxNum of uncommitted evidence.
  69. // If maxNum is -1, all evidence is returned. Pending evidence is prioritised based on time.
  70. func (evpool *Pool) PendingEvidence(maxNum uint32) []types.Evidence {
  71. evpool.removeExpiredPendingEvidence()
  72. evidence, err := evpool.listEvidence(baseKeyPending, int64(maxNum))
  73. if err != nil {
  74. evpool.logger.Error("Unable to retrieve pending evidence", "err", err)
  75. }
  76. return evidence
  77. }
  78. func (evpool *Pool) AllPendingEvidence() []types.Evidence {
  79. evpool.removeExpiredPendingEvidence()
  80. evidence, err := evpool.listEvidence(baseKeyPending, -1)
  81. if err != nil {
  82. evpool.logger.Error("Unable to retrieve pending evidence", "err", err)
  83. }
  84. return evidence
  85. }
  86. // Update uses the latest block & state to update its copy of the state,
  87. // validator to last height map and calls MarkEvidenceAsCommitted.
  88. func (evpool *Pool) Update(block *types.Block, state sm.State) {
  89. // sanity check
  90. if state.LastBlockHeight != block.Height {
  91. panic(fmt.Sprintf("Failed EvidencePool.Update sanity check: got state.Height=%d with block.Height=%d",
  92. state.LastBlockHeight,
  93. block.Height,
  94. ),
  95. )
  96. }
  97. // remove evidence from pending and mark committed
  98. evpool.MarkEvidenceAsCommitted(block.Height, block.Evidence.Evidence)
  99. // prune pending, committed and potential evidence and polc's periodically
  100. if block.Height%state.ConsensusParams.Evidence.MaxAgeNumBlocks == 0 {
  101. evpool.pruneExpiredPOLC()
  102. evpool.removeExpiredPendingEvidence()
  103. }
  104. if evpool.nextEvidenceTrialEndedHeight > 0 && block.Height < evpool.nextEvidenceTrialEndedHeight {
  105. evpool.upgradePotentialAmnesiaEvidence()
  106. }
  107. // update the state
  108. evpool.mtx.Lock()
  109. defer evpool.mtx.Unlock()
  110. evpool.state = state
  111. evpool.updateValToLastHeight(block.Height, state)
  112. }
  113. // AddPOLC adds a proof of lock change to the evidence database
  114. // that may be needed in the future to verify votes
  115. func (evpool *Pool) AddPOLC(polc types.ProofOfLockChange) error {
  116. key := keyPOLC(polc)
  117. pbplc, err := polc.ToProto()
  118. if err != nil {
  119. return err
  120. }
  121. polcBytes, err := proto.Marshal(pbplc)
  122. if err != nil {
  123. return fmt.Errorf("addPOLC: unable to marshal ProofOfLockChange: %w", err)
  124. }
  125. return evpool.evidenceStore.Set(key, polcBytes)
  126. }
  127. // AddEvidence checks the evidence is valid and adds it to the pool. If
  128. // evidence is composite (ConflictingHeadersEvidence), it will be broken up
  129. // into smaller pieces.
  130. func (evpool *Pool) AddEvidence(evidence types.Evidence) error {
  131. var (
  132. state = evpool.State()
  133. evList = []types.Evidence{evidence}
  134. )
  135. valSet, err := sm.LoadValidators(evpool.stateDB, evidence.Height())
  136. if err != nil {
  137. return fmt.Errorf("can't load validators at height #%d: %w", evidence.Height(), err)
  138. }
  139. // Break composite evidence into smaller pieces.
  140. if ce, ok := evidence.(types.CompositeEvidence); ok {
  141. evpool.logger.Info("Breaking up composite evidence", "ev", evidence)
  142. blockMeta := evpool.blockStore.LoadBlockMeta(evidence.Height())
  143. if blockMeta == nil {
  144. return fmt.Errorf("don't have block meta at height #%d", evidence.Height())
  145. }
  146. if err := ce.VerifyComposite(&blockMeta.Header, valSet); err != nil {
  147. return err
  148. }
  149. // XXX: Copy here since this should be a rare case.
  150. evpool.mtx.Lock()
  151. valToLastHeightCopy := make(valToLastHeightMap, len(evpool.valToLastHeight))
  152. for k, v := range evpool.valToLastHeight {
  153. valToLastHeightCopy[k] = v
  154. }
  155. evpool.mtx.Unlock()
  156. evList = ce.Split(&blockMeta.Header, valSet, valToLastHeightCopy)
  157. }
  158. for _, ev := range evList {
  159. if evpool.Has(ev) {
  160. continue
  161. }
  162. // For lunatic validator evidence, a header needs to be fetched.
  163. var header *types.Header
  164. if _, ok := ev.(*types.LunaticValidatorEvidence); ok {
  165. header = evpool.Header(ev.Height())
  166. if header == nil {
  167. return fmt.Errorf("don't have block meta at height #%d", ev.Height())
  168. }
  169. }
  170. // 1) Verify against state.
  171. if err := sm.VerifyEvidence(evpool.stateDB, state, ev, header); err != nil {
  172. return fmt.Errorf("failed to verify %v: %w", ev, err)
  173. }
  174. // For potential amnesia evidence, if this node is indicted it shall retrieve a polc
  175. // to form AmensiaEvidence
  176. if pe, ok := ev.(types.PotentialAmnesiaEvidence); ok {
  177. var (
  178. height = pe.Height()
  179. exists = false
  180. polc types.ProofOfLockChange
  181. )
  182. pe.HeightStamp = evpool.State().LastBlockHeight
  183. // a) first try to find a corresponding polc
  184. for round := pe.VoteB.Round; round > pe.VoteA.Round; round-- {
  185. polc, err = evpool.RetrievePOLC(height, round)
  186. if err != nil {
  187. evpool.logger.Error("Failed to retrieve polc for potential amnesia evidence", "err", err, "pae", pe.String())
  188. continue
  189. }
  190. if err == nil && !polc.IsAbsent() {
  191. // we should not need to verify it if both the polc and potential amnesia evidence have already
  192. // been verified. We replace the potential amnesia evidence.
  193. ae := types.MakeAmnesiaEvidence(pe, polc)
  194. err := evpool.AddEvidence(ae)
  195. if err != nil {
  196. evpool.logger.Error("Failed to create amnesia evidence from potential amnesia evidence", "err", err)
  197. // revert back to processing potential amnesia evidence
  198. exists = false
  199. } else {
  200. evpool.logger.Info("Formed amnesia evidence from own polc", "amnesiaEvidence", ae)
  201. }
  202. break
  203. }
  204. }
  205. // b) check if amnesia evidence can be made now or if we need to enact the trial period
  206. if !exists && pe.Primed(1, pe.HeightStamp) {
  207. err := evpool.AddEvidence(types.MakeAmnesiaEvidence(pe, types.EmptyPOLC()))
  208. if err != nil {
  209. return err
  210. }
  211. } else if !exists && evpool.State().LastBlockHeight+evpool.State().ConsensusParams.Evidence.ProofTrialPeriod <
  212. pe.Height()+evpool.State().ConsensusParams.Evidence.MaxAgeNumBlocks {
  213. // if we can't find a proof of lock change and we know that the trial period will finish before the
  214. // evidence has expired, then we commence the trial period by saving it in the awaiting bucket
  215. pbe, err := types.EvidenceToProto(pe)
  216. if err != nil {
  217. return err
  218. }
  219. evBytes, err := pbe.Marshal()
  220. if err != nil {
  221. return err
  222. }
  223. key := keyAwaiting(pe)
  224. err = evpool.evidenceStore.Set(key, evBytes)
  225. if err != nil {
  226. return err
  227. }
  228. // keep track of when the next pe has finished the trial period
  229. if evpool.nextEvidenceTrialEndedHeight == -1 {
  230. evpool.nextEvidenceTrialEndedHeight = ev.Height() + evpool.State().ConsensusParams.Evidence.ProofTrialPeriod
  231. }
  232. }
  233. // we don't need to do anymore processing so we can move on to the next piece of evidence
  234. continue
  235. }
  236. // 2) Save to store.
  237. if err := evpool.addPendingEvidence(ev); err != nil {
  238. return fmt.Errorf("database error when adding evidence: %v", err)
  239. }
  240. // 3) Add evidence to clist.
  241. evpool.evidenceList.PushBack(ev)
  242. evpool.logger.Info("Verified new evidence of byzantine behaviour", "evidence", ev)
  243. }
  244. return nil
  245. }
  246. // MarkEvidenceAsCommitted marks all the evidence as committed and removes it
  247. // from the queue.
  248. func (evpool *Pool) MarkEvidenceAsCommitted(height int64, evidence []types.Evidence) {
  249. // make a map of committed evidence to remove from the clist
  250. blockEvidenceMap := make(map[string]struct{})
  251. for _, ev := range evidence {
  252. // As the evidence is stored in the block store we only need to record the height that it was saved at.
  253. key := keyCommitted(ev)
  254. h := gogotypes.Int64Value{Value: height}
  255. evBytes, err := proto.Marshal(&h)
  256. if err != nil {
  257. panic(err)
  258. }
  259. if err := evpool.evidenceStore.Set(key, evBytes); err != nil {
  260. evpool.logger.Error("Unable to add committed evidence", "err", err)
  261. // if we can't move evidence to committed then don't remove the evidence from pending
  262. continue
  263. }
  264. // if pending, remove from that bucket, remember not all evidence has been seen before
  265. if evpool.IsPending(ev) {
  266. evpool.removePendingEvidence(ev)
  267. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  268. }
  269. }
  270. // remove committed evidence from the clist
  271. if len(blockEvidenceMap) != 0 {
  272. evpool.removeEvidenceFromList(blockEvidenceMap)
  273. }
  274. }
  275. // Has checks whether the evidence exists either pending or already committed
  276. func (evpool *Pool) Has(evidence types.Evidence) bool {
  277. return evpool.IsPending(evidence) || evpool.IsCommitted(evidence)
  278. }
  279. // IsEvidenceExpired checks whether evidence is past the maximum age where it can be used
  280. func (evpool *Pool) IsEvidenceExpired(evidence types.Evidence) bool {
  281. return evpool.IsExpired(evidence.Height(), evidence.Time())
  282. }
  283. // IsExpired checks whether evidence or a polc is expired by checking whether a height and time is older
  284. // than set by the evidence consensus parameters
  285. func (evpool *Pool) IsExpired(height int64, time time.Time) bool {
  286. var (
  287. params = evpool.State().ConsensusParams.Evidence
  288. ageDuration = evpool.State().LastBlockTime.Sub(time)
  289. ageNumBlocks = evpool.State().LastBlockHeight - height
  290. )
  291. return ageNumBlocks > params.MaxAgeNumBlocks &&
  292. ageDuration > params.MaxAgeDuration
  293. }
  294. // IsCommitted returns true if we have already seen this exact evidence and it is already marked as committed.
  295. func (evpool *Pool) IsCommitted(evidence types.Evidence) bool {
  296. key := keyCommitted(evidence)
  297. ok, err := evpool.evidenceStore.Has(key)
  298. if err != nil {
  299. evpool.logger.Error("Unable to find committed evidence", "err", err)
  300. }
  301. return ok
  302. }
  303. // IsPending checks whether the evidence is already pending. DB errors are passed to the logger.
  304. func (evpool *Pool) IsPending(evidence types.Evidence) bool {
  305. key := keyPending(evidence)
  306. ok, err := evpool.evidenceStore.Has(key)
  307. if err != nil {
  308. evpool.logger.Error("Unable to find pending evidence", "err", err)
  309. }
  310. return ok
  311. }
  312. // RetrievePOLC attempts to find a polc at the given height and round, if not there than exist returns false, all
  313. // database errors are automatically logged
  314. func (evpool *Pool) RetrievePOLC(height int64, round int32) (polc types.ProofOfLockChange, err error) {
  315. var pbpolc tmproto.ProofOfLockChange
  316. key := keyPOLCFromHeightAndRound(height, round)
  317. polcBytes, err := evpool.evidenceStore.Get(key)
  318. if err != nil {
  319. evpool.logger.Error("Unable to retrieve polc", "err", err)
  320. return polc, err
  321. }
  322. if polcBytes == nil {
  323. return polc, fmt.Errorf("nil value in database for key: %s", key)
  324. }
  325. err = proto.Unmarshal(polcBytes, &pbpolc)
  326. if err != nil {
  327. return polc, err
  328. }
  329. plc, err := types.ProofOfLockChangeFromProto(&pbpolc)
  330. if err != nil {
  331. return polc, err
  332. }
  333. return *plc, err
  334. }
  335. // EvidenceFront goes to the first evidence in the clist
  336. func (evpool *Pool) EvidenceFront() *clist.CElement {
  337. return evpool.evidenceList.Front()
  338. }
  339. // EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil
  340. func (evpool *Pool) EvidenceWaitChan() <-chan struct{} {
  341. return evpool.evidenceList.WaitChan()
  342. }
  343. // SetLogger sets the Logger.
  344. func (evpool *Pool) SetLogger(l log.Logger) {
  345. evpool.logger = l
  346. }
  347. // Header gets the header from the block store at a specified height.
  348. // Is used for validation of LunaticValidatorEvidence
  349. func (evpool *Pool) Header(height int64) *types.Header {
  350. blockMeta := evpool.blockStore.LoadBlockMeta(height)
  351. if blockMeta == nil {
  352. return nil
  353. }
  354. return &blockMeta.Header
  355. }
  356. // ValidatorLastHeight returns the last height of the validator w/ the
  357. // given address. 0 - if address never was a validator or was such a
  358. // long time ago (> ConsensusParams.Evidence.MaxAgeDuration && >
  359. // ConsensusParams.Evidence.MaxAgeNumBlocks).
  360. func (evpool *Pool) ValidatorLastHeight(address []byte) int64 {
  361. evpool.mtx.Lock()
  362. defer evpool.mtx.Unlock()
  363. h, ok := evpool.valToLastHeight[string(address)]
  364. if !ok {
  365. return 0
  366. }
  367. return h
  368. }
  369. // State returns the current state of the evpool.
  370. func (evpool *Pool) State() sm.State {
  371. evpool.mtx.Lock()
  372. defer evpool.mtx.Unlock()
  373. return evpool.state
  374. }
  375. func (evpool *Pool) addPendingEvidence(evidence types.Evidence) error {
  376. evi, err := types.EvidenceToProto(evidence)
  377. if err != nil {
  378. return fmt.Errorf("unable to convert to proto, err: %w", err)
  379. }
  380. evBytes, err := proto.Marshal(evi)
  381. if err != nil {
  382. return fmt.Errorf("unable to marshal evidence: %w", err)
  383. }
  384. key := keyPending(evidence)
  385. return evpool.evidenceStore.Set(key, evBytes)
  386. }
  387. func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
  388. key := keyPending(evidence)
  389. if err := evpool.evidenceStore.Delete(key); err != nil {
  390. evpool.logger.Error("Unable to delete pending evidence", "err", err)
  391. } else {
  392. evpool.logger.Info("Deleted pending evidence", "evidence", evidence)
  393. }
  394. }
  395. // listEvidence lists up to maxNum pieces of evidence for the given prefix key.
  396. // If maxNum is -1, there's no cap on the size of returned evidence.
  397. func (evpool *Pool) listEvidence(prefixKey byte, maxNum int64) ([]types.Evidence, error) {
  398. var count int64
  399. var evidence []types.Evidence
  400. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{prefixKey})
  401. if err != nil {
  402. return nil, fmt.Errorf("database error: %v", err)
  403. }
  404. defer iter.Close()
  405. for ; iter.Valid(); iter.Next() {
  406. if count == maxNum {
  407. return evidence, nil
  408. }
  409. count++
  410. val := iter.Value()
  411. var (
  412. ev types.Evidence
  413. evpb tmproto.Evidence
  414. )
  415. err := proto.Unmarshal(val, &evpb)
  416. if err != nil {
  417. return nil, err
  418. }
  419. ev, err = types.EvidenceFromProto(&evpb)
  420. if err != nil {
  421. return nil, err
  422. }
  423. evidence = append(evidence, ev)
  424. }
  425. return evidence, nil
  426. }
  427. func (evpool *Pool) removeExpiredPendingEvidence() {
  428. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPending})
  429. if err != nil {
  430. evpool.logger.Error("Unable to iterate over pending evidence", "err", err)
  431. return
  432. }
  433. defer iter.Close()
  434. blockEvidenceMap := make(map[string]struct{})
  435. for ; iter.Valid(); iter.Next() {
  436. evBytes := iter.Value()
  437. var (
  438. ev types.Evidence
  439. evpb tmproto.Evidence
  440. )
  441. err := proto.Unmarshal(evBytes, &evpb)
  442. if err != nil {
  443. evpool.logger.Error("Unable to unmarshal Evidence", "err", err)
  444. continue
  445. }
  446. ev, err = types.EvidenceFromProto(&evpb)
  447. if err != nil {
  448. evpool.logger.Error("Error in transition evidence from protobuf", "err", err)
  449. continue
  450. }
  451. if !evpool.IsExpired(ev.Height()-1, ev.Time()) {
  452. if len(blockEvidenceMap) != 0 {
  453. evpool.removeEvidenceFromList(blockEvidenceMap)
  454. }
  455. return
  456. }
  457. evpool.removePendingEvidence(ev)
  458. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  459. }
  460. }
  461. func (evpool *Pool) removeEvidenceFromList(
  462. blockEvidenceMap map[string]struct{}) {
  463. for e := evpool.evidenceList.Front(); e != nil; e = e.Next() {
  464. // Remove from clist
  465. ev := e.Value.(types.Evidence)
  466. if _, ok := blockEvidenceMap[evMapKey(ev)]; ok {
  467. evpool.evidenceList.Remove(e)
  468. e.DetachPrev()
  469. }
  470. }
  471. }
  472. func (evpool *Pool) pruneExpiredPOLC() {
  473. evpool.logger.Debug("Pruning expired POLC's")
  474. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPOLC})
  475. if err != nil {
  476. evpool.logger.Error("Unable to iterate over POLC's", "err", err)
  477. return
  478. }
  479. defer iter.Close()
  480. for ; iter.Valid(); iter.Next() {
  481. proofBytes := iter.Value()
  482. var (
  483. pbproof tmproto.ProofOfLockChange
  484. )
  485. err := proto.Unmarshal(proofBytes, &pbproof)
  486. if err != nil {
  487. evpool.logger.Error("Unable to unmarshal POLC", "err", err)
  488. continue
  489. }
  490. proof, err := types.ProofOfLockChangeFromProto(&pbproof)
  491. if err != nil {
  492. evpool.logger.Error("Unable to transition POLC from protobuf", "err", err)
  493. continue
  494. }
  495. if !evpool.IsExpired(proof.Height()-1, proof.Time()) {
  496. return
  497. }
  498. err = evpool.evidenceStore.Delete(iter.Key())
  499. if err != nil {
  500. evpool.logger.Error("Unable to delete expired POLC", "err", err)
  501. continue
  502. }
  503. evpool.logger.Info("Deleted expired POLC", "polc", proof)
  504. }
  505. }
  506. // upgrades any potential evidence that has undergone the trial period and is primed to be made into
  507. // amnesia evidence
  508. func (evpool *Pool) upgradePotentialAmnesiaEvidence() int64 {
  509. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyAwaiting})
  510. if err != nil {
  511. evpool.logger.Error("Unable to iterate over POLC's", "err", err)
  512. return -1
  513. }
  514. defer iter.Close()
  515. trialPeriod := evpool.State().ConsensusParams.Evidence.ProofTrialPeriod
  516. // 1) Iterate through all potential amnesia evidence in order of height
  517. for ; iter.Valid(); iter.Next() {
  518. paeBytes := iter.Value()
  519. // 2) Retrieve the evidence
  520. var evpb tmproto.Evidence
  521. err := evpb.Unmarshal(paeBytes)
  522. if err != nil {
  523. evpool.logger.Error("Unable to unmarshal potential amnesia evidence", "err", err)
  524. continue
  525. }
  526. ev, err := types.EvidenceFromProto(&evpb)
  527. if err != nil {
  528. evpool.logger.Error("coverting to evidence from proto", "err", err)
  529. continue
  530. }
  531. // 3) Check if the trial period has lapsed and amnesia evidence can be formed
  532. if pe, ok := ev.(*types.PotentialAmnesiaEvidence); ok {
  533. if pe.Primed(trialPeriod, evpool.State().LastBlockHeight) {
  534. ae := types.MakeAmnesiaEvidence(*pe, types.EmptyPOLC())
  535. err := evpool.AddEvidence(ae)
  536. if err != nil {
  537. evpool.logger.Error("Unable to add amnesia evidence", "err", err)
  538. continue
  539. }
  540. err = evpool.evidenceStore.Delete(iter.Key())
  541. if err != nil {
  542. evpool.logger.Error("Unable to delete potential amnesia evidence", "err", err)
  543. continue
  544. }
  545. } else {
  546. evpool.logger.Debug("Potential amnesia evidence not ready to be upgraded. Ready at height", "height",
  547. pe.HeightStamp+trialPeriod)
  548. // once we reach a piece of evidence that isn't ready send back the height with which it will be ready
  549. return pe.HeightStamp + trialPeriod
  550. }
  551. }
  552. }
  553. // if we have no evidence left to process we want to reset nextEvidenceTrialEndedHeight
  554. return -1
  555. }
  556. func evMapKey(ev types.Evidence) string {
  557. return string(ev.Hash())
  558. }
  559. func (evpool *Pool) updateValToLastHeight(blockHeight int64, state sm.State) {
  560. // Update current validators & add new ones.
  561. for _, val := range state.Validators.Validators {
  562. evpool.valToLastHeight[string(val.Address)] = blockHeight
  563. }
  564. // Remove validators outside of MaxAgeNumBlocks & MaxAgeDuration.
  565. removeHeight := blockHeight - state.ConsensusParams.Evidence.MaxAgeNumBlocks
  566. if removeHeight >= 1 {
  567. for val, height := range evpool.valToLastHeight {
  568. if height <= removeHeight {
  569. delete(evpool.valToLastHeight, val)
  570. }
  571. }
  572. }
  573. }
  574. func buildValToLastHeightMap(state sm.State, stateDB dbm.DB, blockStore *store.BlockStore) (valToLastHeightMap, error) {
  575. var (
  576. valToLastHeight = make(map[string]int64)
  577. params = state.ConsensusParams.Evidence
  578. numBlocks = int64(0)
  579. minAgeTime = time.Now().Add(-params.MaxAgeDuration)
  580. height = state.LastBlockHeight
  581. )
  582. if height == 0 {
  583. return valToLastHeight, nil
  584. }
  585. meta := blockStore.LoadBlockMeta(height)
  586. if meta == nil {
  587. return nil, fmt.Errorf("block meta for height %d not found", height)
  588. }
  589. blockTime := meta.Header.Time
  590. // From state.LastBlockHeight, build a map of "active" validators until
  591. // MaxAgeNumBlocks is passed and block time is less than now() -
  592. // MaxAgeDuration.
  593. for height >= 1 && (numBlocks <= params.MaxAgeNumBlocks || !blockTime.Before(minAgeTime)) {
  594. valSet, err := sm.LoadValidators(stateDB, height)
  595. if err != nil {
  596. // last stored height -> return
  597. if _, ok := err.(sm.ErrNoValSetForHeight); ok {
  598. return valToLastHeight, nil
  599. }
  600. return nil, fmt.Errorf("validator set for height %d not found", height)
  601. }
  602. for _, val := range valSet.Validators {
  603. key := string(val.Address)
  604. if _, ok := valToLastHeight[key]; !ok {
  605. valToLastHeight[key] = height
  606. }
  607. }
  608. height--
  609. if height > 0 {
  610. // NOTE: we assume here blockStore and state.Validators are in sync. I.e if
  611. // block N is stored, then validators for height N are also stored in
  612. // state.
  613. meta := blockStore.LoadBlockMeta(height)
  614. if meta == nil {
  615. return nil, fmt.Errorf("block meta for height %d not found", height)
  616. }
  617. blockTime = meta.Header.Time
  618. }
  619. numBlocks++
  620. }
  621. return valToLastHeight, nil
  622. }
  623. // big endian padded hex
  624. func bE(h int64) string {
  625. return fmt.Sprintf("%0.16X", h)
  626. }
  627. func keyCommitted(evidence types.Evidence) []byte {
  628. return append([]byte{baseKeyCommitted}, keySuffix(evidence)...)
  629. }
  630. func keyPending(evidence types.Evidence) []byte {
  631. return append([]byte{baseKeyPending}, keySuffix(evidence)...)
  632. }
  633. func keyAwaiting(evidence types.Evidence) []byte {
  634. return append([]byte{baseKeyAwaiting}, keySuffix(evidence)...)
  635. }
  636. func keyPOLC(polc types.ProofOfLockChange) []byte {
  637. return keyPOLCFromHeightAndRound(polc.Height(), polc.Round())
  638. }
  639. func keyPOLCFromHeightAndRound(height int64, round int32) []byte {
  640. return append([]byte{baseKeyPOLC}, []byte(fmt.Sprintf("%s/%s", bE(height), bE(int64(round))))...)
  641. }
  642. func keySuffix(evidence types.Evidence) []byte {
  643. return []byte(fmt.Sprintf("%s/%X", bE(evidence.Height()), evidence.Hash()))
  644. }
  645. // ErrInvalidEvidence returns when evidence failed to validate
  646. type ErrInvalidEvidence struct {
  647. Reason error
  648. }
  649. func (e ErrInvalidEvidence) Error() string {
  650. return fmt.Sprintf("evidence is not valid: %v ", e.Reason)
  651. }