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.

563 lines
17 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. dbm "github.com/tendermint/tm-db"
  7. clist "github.com/tendermint/tendermint/libs/clist"
  8. "github.com/tendermint/tendermint/libs/log"
  9. sm "github.com/tendermint/tendermint/state"
  10. "github.com/tendermint/tendermint/store"
  11. "github.com/tendermint/tendermint/types"
  12. )
  13. const (
  14. baseKeyCommitted = byte(0x00)
  15. baseKeyPending = byte(0x01)
  16. baseKeyPOLC = byte(0x02)
  17. )
  18. // Pool maintains a pool of valid evidence to be broadcasted and committed
  19. type Pool struct {
  20. logger log.Logger
  21. evidenceStore dbm.DB
  22. evidenceList *clist.CList // concurrent linked-list of evidence
  23. // needed to load validators to verify evidence
  24. stateDB dbm.DB
  25. // needed to load headers to verify evidence
  26. blockStore *store.BlockStore
  27. mtx sync.Mutex
  28. // latest state
  29. state sm.State
  30. // a map of active validators and respective last heights validator is active
  31. // if it was in validator set after EvidenceParams.MaxAgeNumBlocks or
  32. // currently is (ie. [MaxAgeNumBlocks, CurrentHeight])
  33. // In simple words, it means it's still bonded -> therefore slashable.
  34. valToLastHeight valToLastHeightMap
  35. }
  36. // Validator.Address -> Last height it was in validator set
  37. type valToLastHeightMap map[string]int64
  38. func NewPool(stateDB, evidenceDB dbm.DB, blockStore *store.BlockStore) (*Pool, error) {
  39. var (
  40. state = sm.LoadState(stateDB)
  41. )
  42. valToLastHeight, err := buildValToLastHeightMap(state, stateDB, blockStore)
  43. if err != nil {
  44. return nil, err
  45. }
  46. pool := &Pool{
  47. stateDB: stateDB,
  48. blockStore: blockStore,
  49. state: state,
  50. logger: log.NewNopLogger(),
  51. evidenceStore: evidenceDB,
  52. evidenceList: clist.New(),
  53. valToLastHeight: valToLastHeight,
  54. }
  55. // if pending evidence already in db, in event of prior failure, then load it back to the evidenceList
  56. evList := pool.AllPendingEvidence()
  57. for _, ev := range evList {
  58. if pool.IsEvidenceExpired(ev) {
  59. pool.removePendingEvidence(ev)
  60. continue
  61. }
  62. pool.evidenceList.PushBack(ev)
  63. }
  64. return pool, nil
  65. }
  66. // PendingEvidence is used primarily as part of block proposal and returns up to maxNum of uncommitted evidence.
  67. // If maxNum is -1, all evidence is returned. Pending evidence is prioritised based on time.
  68. func (evpool *Pool) PendingEvidence(maxNum uint32) []types.Evidence {
  69. evidence, err := evpool.listEvidence(baseKeyPending, int64(maxNum))
  70. if err != nil {
  71. evpool.logger.Error("Unable to retrieve pending evidence", "err", err)
  72. }
  73. return evidence
  74. }
  75. func (evpool *Pool) AllPendingEvidence() []types.Evidence {
  76. evidence, err := evpool.listEvidence(baseKeyPending, -1)
  77. if err != nil {
  78. evpool.logger.Error("Unable to retrieve pending evidence", "err", err)
  79. }
  80. return evidence
  81. }
  82. // Update uses the latest block & state to update its copy of the state,
  83. // validator to last height map and calls MarkEvidenceAsCommitted.
  84. func (evpool *Pool) Update(block *types.Block, state sm.State) {
  85. // sanity check
  86. if state.LastBlockHeight != block.Height {
  87. panic(
  88. fmt.Sprintf("Failed EvidencePool.Update sanity check: got state.Height=%d with block.Height=%d",
  89. state.LastBlockHeight,
  90. block.Height,
  91. ),
  92. )
  93. }
  94. // remove evidence from pending and mark committed
  95. evpool.MarkEvidenceAsCommitted(block.Height, block.Time, block.Evidence.Evidence)
  96. // remove expired evidence - this should be done at every height to ensure we don't send expired evidence to peers
  97. evpool.removeExpiredPendingEvidence()
  98. // as it's not vital to remove expired POLCs, we only prune periodically
  99. if block.Height%state.ConsensusParams.Evidence.MaxAgeNumBlocks == 0 {
  100. evpool.pruneExpiredPOLC()
  101. }
  102. // update the state
  103. evpool.mtx.Lock()
  104. defer evpool.mtx.Unlock()
  105. evpool.state = state
  106. evpool.updateValToLastHeight(block.Height, state)
  107. }
  108. // AddPOLC adds a proof of lock change to the evidence database
  109. // that may be needed in the future to verify votes
  110. func (evpool *Pool) AddPOLC(polc types.ProofOfLockChange) error {
  111. key := keyPOLC(polc)
  112. polcBytes := cdc.MustMarshalBinaryBare(polc)
  113. return evpool.evidenceStore.Set(key, polcBytes)
  114. }
  115. // AddEvidence checks the evidence is valid and adds it to the pool. If
  116. // evidence is composite (ConflictingHeadersEvidence), it will be broken up
  117. // into smaller pieces.
  118. func (evpool *Pool) AddEvidence(evidence types.Evidence) error {
  119. var (
  120. state = evpool.State()
  121. evList = []types.Evidence{evidence}
  122. )
  123. valSet, err := sm.LoadValidators(evpool.stateDB, evidence.Height())
  124. if err != nil {
  125. return fmt.Errorf("can't load validators at height #%d: %w", evidence.Height(), err)
  126. }
  127. // Break composite evidence into smaller pieces.
  128. if ce, ok := evidence.(types.CompositeEvidence); ok {
  129. evpool.logger.Info("Breaking up composite evidence", "ev", evidence)
  130. blockMeta := evpool.blockStore.LoadBlockMeta(evidence.Height())
  131. if blockMeta == nil {
  132. return fmt.Errorf("don't have block meta at height #%d", evidence.Height())
  133. }
  134. if err := ce.VerifyComposite(&blockMeta.Header, valSet); err != nil {
  135. return err
  136. }
  137. // XXX: Copy here since this should be a rare case.
  138. evpool.mtx.Lock()
  139. valToLastHeightCopy := make(valToLastHeightMap, len(evpool.valToLastHeight))
  140. for k, v := range evpool.valToLastHeight {
  141. valToLastHeightCopy[k] = v
  142. }
  143. evpool.mtx.Unlock()
  144. evList = ce.Split(&blockMeta.Header, valSet, valToLastHeightCopy)
  145. }
  146. for _, ev := range evList {
  147. if evpool.Has(ev) {
  148. continue
  149. }
  150. // For lunatic validator evidence, a header needs to be fetched.
  151. var header *types.Header
  152. if _, ok := ev.(*types.LunaticValidatorEvidence); ok {
  153. header = evpool.Header(ev.Height())
  154. if header == nil {
  155. return fmt.Errorf("don't have block meta at height #%d", ev.Height())
  156. }
  157. }
  158. // 1) Verify against state.
  159. if err := sm.VerifyEvidence(evpool.stateDB, state, ev, header); err != nil {
  160. return fmt.Errorf("failed to verify %v: %w", ev, err)
  161. }
  162. // 2) Save to store.
  163. if err := evpool.addPendingEvidence(ev); err != nil {
  164. return fmt.Errorf("database error: %v", err)
  165. }
  166. // 3) Add evidence to clist.
  167. evpool.evidenceList.PushBack(ev)
  168. evpool.logger.Info("Verified new evidence of byzantine behaviour", "evidence", ev)
  169. }
  170. return nil
  171. }
  172. // MarkEvidenceAsCommitted marks all the evidence as committed and removes it
  173. // from the queue.
  174. func (evpool *Pool) MarkEvidenceAsCommitted(height int64, lastBlockTime time.Time, evidence []types.Evidence) {
  175. // make a map of committed evidence to remove from the clist
  176. blockEvidenceMap := make(map[string]struct{})
  177. for _, ev := range evidence {
  178. // As the evidence is stored in the block store we only need to record the height that it was saved at.
  179. key := keyCommitted(ev)
  180. evBytes := cdc.MustMarshalBinaryBare(height)
  181. if err := evpool.evidenceStore.Set(key, evBytes); err != nil {
  182. evpool.logger.Error("Unable to add committed evidence", "err", err)
  183. // if we can't move evidence to committed then don't remove the evidence from pending
  184. continue
  185. }
  186. // if pending, remove from that bucket, remember not all evidence has been seen before
  187. if evpool.IsPending(ev) {
  188. evpool.removePendingEvidence(ev)
  189. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  190. }
  191. }
  192. // remove committed evidence from the clist
  193. if len(blockEvidenceMap) != 0 {
  194. evpool.removeEvidenceFromList(blockEvidenceMap)
  195. }
  196. }
  197. // Has checks whether the evidence exists either pending or already committed
  198. func (evpool *Pool) Has(evidence types.Evidence) bool {
  199. return evpool.IsPending(evidence) || evpool.IsCommitted(evidence)
  200. }
  201. // IsEvidenceExpired checks whether evidence is past the maximum age where it can be used
  202. func (evpool *Pool) IsEvidenceExpired(evidence types.Evidence) bool {
  203. return evpool.IsExpired(evidence.Height(), evidence.Time())
  204. }
  205. // IsExpired checks whether evidence or a polc is expired by checking whether a height and time is older
  206. // than set by the evidence consensus parameters
  207. func (evpool *Pool) IsExpired(height int64, time time.Time) bool {
  208. var (
  209. params = evpool.State().ConsensusParams.Evidence
  210. ageDuration = evpool.State().LastBlockTime.Sub(time)
  211. ageNumBlocks = evpool.State().LastBlockHeight - height
  212. )
  213. return ageNumBlocks > params.MaxAgeNumBlocks &&
  214. ageDuration > params.MaxAgeDuration
  215. }
  216. // IsCommitted returns true if we have already seen this exact evidence and it is already marked as committed.
  217. func (evpool *Pool) IsCommitted(evidence types.Evidence) bool {
  218. key := keyCommitted(evidence)
  219. ok, err := evpool.evidenceStore.Has(key)
  220. if err != nil {
  221. evpool.logger.Error("Unable to find committed evidence", "err", err)
  222. }
  223. return ok
  224. }
  225. // IsPending checks whether the evidence is already pending. DB errors are passed to the logger.
  226. func (evpool *Pool) IsPending(evidence types.Evidence) bool {
  227. key := keyPending(evidence)
  228. ok, err := evpool.evidenceStore.Has(key)
  229. if err != nil {
  230. evpool.logger.Error("Unable to find pending evidence", "err", err)
  231. }
  232. return ok
  233. }
  234. // RetrievePOLC attempts to find a polc at the given height and round, if not there it returns an error
  235. func (evpool *Pool) RetrievePOLC(height int64, round int32) (types.ProofOfLockChange, error) {
  236. var polc types.ProofOfLockChange
  237. key := keyPOLCFromHeightAndRound(height, round)
  238. polcBytes, err := evpool.evidenceStore.Get(key)
  239. if err != nil {
  240. return polc, err
  241. }
  242. if polcBytes == nil {
  243. return polc, fmt.Errorf("unable to find polc at height %d and round %d", height, round)
  244. }
  245. err = cdc.UnmarshalBinaryBare(polcBytes, &polc)
  246. return polc, err
  247. }
  248. // EvidenceFront goes to the first evidence in the clist
  249. func (evpool *Pool) EvidenceFront() *clist.CElement {
  250. return evpool.evidenceList.Front()
  251. }
  252. // EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil
  253. func (evpool *Pool) EvidenceWaitChan() <-chan struct{} {
  254. return evpool.evidenceList.WaitChan()
  255. }
  256. // SetLogger sets the Logger.
  257. func (evpool *Pool) SetLogger(l log.Logger) {
  258. evpool.logger = l
  259. }
  260. // Header gets the header from the block store at a specified height.
  261. // Is used for validation of LunaticValidatorEvidence
  262. func (evpool *Pool) Header(height int64) *types.Header {
  263. blockMeta := evpool.blockStore.LoadBlockMeta(height)
  264. if blockMeta == nil {
  265. return nil
  266. }
  267. return &blockMeta.Header
  268. }
  269. // ValidatorLastHeight returns the last height of the validator w/ the
  270. // given address. 0 - if address never was a validator or was such a
  271. // long time ago (> ConsensusParams.Evidence.MaxAgeDuration && >
  272. // ConsensusParams.Evidence.MaxAgeNumBlocks).
  273. func (evpool *Pool) ValidatorLastHeight(address []byte) int64 {
  274. evpool.mtx.Lock()
  275. defer evpool.mtx.Unlock()
  276. h, ok := evpool.valToLastHeight[string(address)]
  277. if !ok {
  278. return 0
  279. }
  280. return h
  281. }
  282. // State returns the current state of the evpool.
  283. func (evpool *Pool) State() sm.State {
  284. evpool.mtx.Lock()
  285. defer evpool.mtx.Unlock()
  286. return evpool.state
  287. }
  288. func (evpool *Pool) addPendingEvidence(evidence types.Evidence) error {
  289. evBytes := cdc.MustMarshalBinaryBare(evidence)
  290. key := keyPending(evidence)
  291. return evpool.evidenceStore.Set(key, evBytes)
  292. }
  293. func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
  294. key := keyPending(evidence)
  295. if err := evpool.evidenceStore.Delete(key); err != nil {
  296. evpool.logger.Error("Unable to delete pending evidence", "err", err)
  297. } else {
  298. evpool.logger.Info("Deleted pending evidence", "evidence", evidence)
  299. }
  300. }
  301. // listEvidence lists up to maxNum pieces of evidence for the given prefix key.
  302. // If maxNum is -1, there's no cap on the size of returned evidence.
  303. func (evpool *Pool) listEvidence(prefixKey byte, maxNum int64) ([]types.Evidence, error) {
  304. var count int64
  305. var evidence []types.Evidence
  306. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{prefixKey})
  307. if err != nil {
  308. return nil, fmt.Errorf("database error: %v", err)
  309. }
  310. defer iter.Close()
  311. for ; iter.Valid(); iter.Next() {
  312. val := iter.Value()
  313. if count == maxNum {
  314. return evidence, nil
  315. }
  316. count++
  317. var ev types.Evidence
  318. err := cdc.UnmarshalBinaryBare(val, &ev)
  319. if err != nil {
  320. return nil, err
  321. }
  322. evidence = append(evidence, ev)
  323. }
  324. return evidence, nil
  325. }
  326. func (evpool *Pool) removeExpiredPendingEvidence() {
  327. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPending})
  328. if err != nil {
  329. evpool.logger.Error("Unable to iterate over pending evidence", "err", err)
  330. return
  331. }
  332. defer iter.Close()
  333. blockEvidenceMap := make(map[string]struct{})
  334. for ; iter.Valid(); iter.Next() {
  335. evBytes := iter.Value()
  336. var ev types.Evidence
  337. err := cdc.UnmarshalBinaryBare(evBytes, &ev)
  338. if err != nil {
  339. evpool.logger.Error("Unable to unmarshal POLC", "err", err)
  340. continue
  341. }
  342. if !evpool.IsExpired(ev.Height()-1, ev.Time()) {
  343. if len(blockEvidenceMap) != 0 {
  344. evpool.removeEvidenceFromList(blockEvidenceMap)
  345. }
  346. return
  347. }
  348. evpool.removePendingEvidence(ev)
  349. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  350. }
  351. }
  352. func (evpool *Pool) removeEvidenceFromList(
  353. blockEvidenceMap map[string]struct{}) {
  354. for e := evpool.evidenceList.Front(); e != nil; e = e.Next() {
  355. // Remove from clist
  356. ev := e.Value.(types.Evidence)
  357. if _, ok := blockEvidenceMap[evMapKey(ev)]; ok {
  358. evpool.evidenceList.Remove(e)
  359. e.DetachPrev()
  360. }
  361. }
  362. }
  363. func (evpool *Pool) pruneExpiredPOLC() {
  364. evpool.logger.Debug("Pruning expired POLC's")
  365. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPOLC})
  366. if err != nil {
  367. evpool.logger.Error("Unable to iterate over POLC's", "err", err)
  368. return
  369. }
  370. defer iter.Close()
  371. for ; iter.Valid(); iter.Next() {
  372. proofBytes := iter.Value()
  373. var proof types.ProofOfLockChange
  374. err := cdc.UnmarshalBinaryBare(proofBytes, &proof)
  375. if err != nil {
  376. evpool.logger.Error("Unable to unmarshal POLC", "err", err)
  377. continue
  378. }
  379. if !evpool.IsExpired(proof.Height()-1, proof.Time()) {
  380. return
  381. }
  382. err = evpool.evidenceStore.Delete(iter.Key())
  383. if err != nil {
  384. evpool.logger.Error("Unable to delete expired POLC", "err", err)
  385. continue
  386. }
  387. evpool.logger.Info("Deleted expired POLC", "polc", proof)
  388. }
  389. }
  390. func evMapKey(ev types.Evidence) string {
  391. return string(ev.Hash())
  392. }
  393. func (evpool *Pool) updateValToLastHeight(blockHeight int64, state sm.State) {
  394. // Update current validators & add new ones.
  395. for _, val := range state.Validators.Validators {
  396. evpool.valToLastHeight[string(val.Address)] = blockHeight
  397. }
  398. // Remove validators outside of MaxAgeNumBlocks & MaxAgeDuration.
  399. removeHeight := blockHeight - state.ConsensusParams.Evidence.MaxAgeNumBlocks
  400. if removeHeight >= 1 {
  401. for val, height := range evpool.valToLastHeight {
  402. if height <= removeHeight {
  403. delete(evpool.valToLastHeight, val)
  404. }
  405. }
  406. }
  407. }
  408. func buildValToLastHeightMap(state sm.State, stateDB dbm.DB, blockStore *store.BlockStore) (valToLastHeightMap, error) {
  409. var (
  410. valToLastHeight = make(map[string]int64)
  411. params = state.ConsensusParams.Evidence
  412. numBlocks = int64(0)
  413. minAgeTime = time.Now().Add(-params.MaxAgeDuration)
  414. height = state.LastBlockHeight
  415. )
  416. if height == 0 {
  417. return valToLastHeight, nil
  418. }
  419. meta := blockStore.LoadBlockMeta(height)
  420. if meta == nil {
  421. return nil, fmt.Errorf("block meta for height %d not found", height)
  422. }
  423. blockTime := meta.Header.Time
  424. // From state.LastBlockHeight, build a map of "active" validators until
  425. // MaxAgeNumBlocks is passed and block time is less than now() -
  426. // MaxAgeDuration.
  427. for height >= 1 && (numBlocks <= params.MaxAgeNumBlocks || !blockTime.Before(minAgeTime)) {
  428. valSet, err := sm.LoadValidators(stateDB, height)
  429. if err != nil {
  430. // last stored height -> return
  431. if _, ok := err.(sm.ErrNoValSetForHeight); ok {
  432. return valToLastHeight, nil
  433. }
  434. return nil, fmt.Errorf("validator set for height %d not found", height)
  435. }
  436. for _, val := range valSet.Validators {
  437. key := string(val.Address)
  438. if _, ok := valToLastHeight[key]; !ok {
  439. valToLastHeight[key] = height
  440. }
  441. }
  442. height--
  443. if height > 0 {
  444. // NOTE: we assume here blockStore and state.Validators are in sync. I.e if
  445. // block N is stored, then validators for height N are also stored in
  446. // state.
  447. meta := blockStore.LoadBlockMeta(height)
  448. if meta == nil {
  449. return nil, fmt.Errorf("block meta for height %d not found", height)
  450. }
  451. blockTime = meta.Header.Time
  452. }
  453. numBlocks++
  454. }
  455. return valToLastHeight, nil
  456. }
  457. // big endian padded hex
  458. func bE(h int64) string {
  459. return fmt.Sprintf("%0.16X", h)
  460. }
  461. func keyCommitted(evidence types.Evidence) []byte {
  462. return append([]byte{baseKeyCommitted}, keySuffix(evidence)...)
  463. }
  464. func keyPending(evidence types.Evidence) []byte {
  465. return append([]byte{baseKeyPending}, keySuffix(evidence)...)
  466. }
  467. func keyPOLC(polc types.ProofOfLockChange) []byte {
  468. return keyPOLCFromHeightAndRound(polc.Height(), polc.Round())
  469. }
  470. func keyPOLCFromHeightAndRound(height int64, round int32) []byte {
  471. return append([]byte{baseKeyPOLC}, []byte(fmt.Sprintf("%s/%s", bE(height), bE(int64(round))))...)
  472. }
  473. func keySuffix(evidence types.Evidence) []byte {
  474. return []byte(fmt.Sprintf("%s/%X", bE(evidence.Height()), evidence.Hash()))
  475. }
  476. // ErrInvalidEvidence returns when evidence failed to validate
  477. type ErrInvalidEvidence struct {
  478. Reason error
  479. }
  480. func (e ErrInvalidEvidence) Error() string {
  481. return fmt.Sprintf("evidence is not valid: %v ", e.Reason)
  482. }