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.

554 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. blockMeta := evpool.blockStore.LoadBlockMeta(ev.Height())
  154. if blockMeta == nil {
  155. return fmt.Errorf("don't have block meta at height #%d", ev.Height())
  156. }
  157. header = &blockMeta.Header
  158. }
  159. // 1) Verify against state.
  160. if err := sm.VerifyEvidence(evpool.stateDB, state, ev, header); err != nil {
  161. return fmt.Errorf("failed to verify %v: %w", ev, err)
  162. }
  163. // 2) Save to store.
  164. if err := evpool.addPendingEvidence(ev); err != nil {
  165. return fmt.Errorf("database error: %v", err)
  166. }
  167. // 3) Add evidence to clist.
  168. evpool.evidenceList.PushBack(ev)
  169. evpool.logger.Info("Verified new evidence of byzantine behaviour", "evidence", ev)
  170. }
  171. return nil
  172. }
  173. // MarkEvidenceAsCommitted marks all the evidence as committed and removes it
  174. // from the queue.
  175. func (evpool *Pool) MarkEvidenceAsCommitted(height int64, lastBlockTime time.Time, evidence []types.Evidence) {
  176. // make a map of committed evidence to remove from the clist
  177. blockEvidenceMap := make(map[string]struct{})
  178. for _, ev := range evidence {
  179. // As the evidence is stored in the block store we only need to record the height that it was saved at.
  180. key := keyCommitted(ev)
  181. evBytes := cdc.MustMarshalBinaryBare(height)
  182. if err := evpool.evidenceStore.Set(key, evBytes); err != nil {
  183. evpool.logger.Error("Unable to add committed evidence", "err", err)
  184. // if we can't move evidence to committed then don't remove the evidence from pending
  185. continue
  186. }
  187. // if pending, remove from that bucket, remember not all evidence has been seen before
  188. if evpool.IsPending(ev) {
  189. evpool.removePendingEvidence(ev)
  190. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  191. }
  192. }
  193. // remove committed evidence from the clist
  194. if len(blockEvidenceMap) != 0 {
  195. evpool.removeEvidenceFromList(blockEvidenceMap)
  196. }
  197. }
  198. // Has checks whether the evidence exists either pending or already committed
  199. func (evpool *Pool) Has(evidence types.Evidence) bool {
  200. return evpool.IsPending(evidence) || evpool.IsCommitted(evidence)
  201. }
  202. // IsEvidenceExpired checks whether evidence is past the maximum age where it can be used
  203. func (evpool *Pool) IsEvidenceExpired(evidence types.Evidence) bool {
  204. return evpool.IsExpired(evidence.Height(), evidence.Time())
  205. }
  206. // IsExpired checks whether evidence or a polc is expired by checking whether a height and time is older
  207. // than set by the evidence consensus parameters
  208. func (evpool *Pool) IsExpired(height int64, time time.Time) bool {
  209. var (
  210. params = evpool.State().ConsensusParams.Evidence
  211. ageDuration = evpool.State().LastBlockTime.Sub(time)
  212. ageNumBlocks = evpool.State().LastBlockHeight - height
  213. )
  214. return ageNumBlocks > params.MaxAgeNumBlocks &&
  215. ageDuration > params.MaxAgeDuration
  216. }
  217. // IsCommitted returns true if we have already seen this exact evidence and it is already marked as committed.
  218. func (evpool *Pool) IsCommitted(evidence types.Evidence) bool {
  219. key := keyCommitted(evidence)
  220. ok, err := evpool.evidenceStore.Has(key)
  221. if err != nil {
  222. evpool.logger.Error("Unable to find committed evidence", "err", err)
  223. }
  224. return ok
  225. }
  226. // Checks whether the evidence is already pending. DB errors are passed to the logger.
  227. func (evpool *Pool) IsPending(evidence types.Evidence) bool {
  228. key := keyPending(evidence)
  229. ok, err := evpool.evidenceStore.Has(key)
  230. if err != nil {
  231. evpool.logger.Error("Unable to find pending evidence", "err", err)
  232. }
  233. return ok
  234. }
  235. // RetrievePOLC attempts to find a polc at the given height and round, if not there it returns an error
  236. func (evpool *Pool) RetrievePOLC(height int64, round int) (types.ProofOfLockChange, error) {
  237. var polc types.ProofOfLockChange
  238. key := keyPOLCFromHeightAndRound(height, round)
  239. polcBytes, err := evpool.evidenceStore.Get(key)
  240. if err != nil {
  241. return polc, err
  242. }
  243. if polcBytes == nil {
  244. return polc, fmt.Errorf("unable to find polc at height %d and round %d", height, round)
  245. }
  246. err = cdc.UnmarshalBinaryBare(polcBytes, &polc)
  247. return polc, err
  248. }
  249. // EvidenceFront goes to the first evidence in the clist
  250. func (evpool *Pool) EvidenceFront() *clist.CElement {
  251. return evpool.evidenceList.Front()
  252. }
  253. // EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil
  254. func (evpool *Pool) EvidenceWaitChan() <-chan struct{} {
  255. return evpool.evidenceList.WaitChan()
  256. }
  257. // SetLogger sets the Logger.
  258. func (evpool *Pool) SetLogger(l log.Logger) {
  259. evpool.logger = l
  260. }
  261. // ValidatorLastHeight returns the last height of the validator w/ the
  262. // given address. 0 - if address never was a validator or was such a
  263. // long time ago (> ConsensusParams.Evidence.MaxAgeDuration && >
  264. // ConsensusParams.Evidence.MaxAgeNumBlocks).
  265. func (evpool *Pool) ValidatorLastHeight(address []byte) int64 {
  266. evpool.mtx.Lock()
  267. defer evpool.mtx.Unlock()
  268. h, ok := evpool.valToLastHeight[string(address)]
  269. if !ok {
  270. return 0
  271. }
  272. return h
  273. }
  274. // State returns the current state of the evpool.
  275. func (evpool *Pool) State() sm.State {
  276. evpool.mtx.Lock()
  277. defer evpool.mtx.Unlock()
  278. return evpool.state
  279. }
  280. func (evpool *Pool) addPendingEvidence(evidence types.Evidence) error {
  281. evBytes := cdc.MustMarshalBinaryBare(evidence)
  282. key := keyPending(evidence)
  283. return evpool.evidenceStore.Set(key, evBytes)
  284. }
  285. func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
  286. key := keyPending(evidence)
  287. if err := evpool.evidenceStore.Delete(key); err != nil {
  288. evpool.logger.Error("Unable to delete pending evidence", "err", err)
  289. } else {
  290. evpool.logger.Info("Deleted pending evidence", "evidence", evidence)
  291. }
  292. }
  293. // listEvidence lists up to maxNum pieces of evidence for the given prefix key.
  294. // If maxNum is -1, there's no cap on the size of returned evidence.
  295. func (evpool *Pool) listEvidence(prefixKey byte, maxNum int64) ([]types.Evidence, error) {
  296. var count int64
  297. var evidence []types.Evidence
  298. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{prefixKey})
  299. if err != nil {
  300. return nil, fmt.Errorf("database error: %v", err)
  301. }
  302. defer iter.Close()
  303. for ; iter.Valid(); iter.Next() {
  304. val := iter.Value()
  305. if count == maxNum {
  306. return evidence, nil
  307. }
  308. count++
  309. var ev types.Evidence
  310. err := cdc.UnmarshalBinaryBare(val, &ev)
  311. if err != nil {
  312. return nil, err
  313. }
  314. evidence = append(evidence, ev)
  315. }
  316. return evidence, nil
  317. }
  318. func (evpool *Pool) removeExpiredPendingEvidence() {
  319. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPending})
  320. if err != nil {
  321. evpool.logger.Error("Unable to iterate over pending evidence", "err", err)
  322. return
  323. }
  324. defer iter.Close()
  325. blockEvidenceMap := make(map[string]struct{})
  326. for ; iter.Valid(); iter.Next() {
  327. evBytes := iter.Value()
  328. var ev types.Evidence
  329. err := cdc.UnmarshalBinaryBare(evBytes, &ev)
  330. if err != nil {
  331. evpool.logger.Error("Unable to unmarshal POLC", "err", err)
  332. continue
  333. }
  334. if !evpool.IsExpired(ev.Height()-1, ev.Time()) {
  335. if len(blockEvidenceMap) != 0 {
  336. evpool.removeEvidenceFromList(blockEvidenceMap)
  337. }
  338. return
  339. }
  340. evpool.removePendingEvidence(ev)
  341. blockEvidenceMap[evMapKey(ev)] = struct{}{}
  342. }
  343. }
  344. func (evpool *Pool) removeEvidenceFromList(
  345. blockEvidenceMap map[string]struct{}) {
  346. for e := evpool.evidenceList.Front(); e != nil; e = e.Next() {
  347. // Remove from clist
  348. ev := e.Value.(types.Evidence)
  349. if _, ok := blockEvidenceMap[evMapKey(ev)]; ok {
  350. evpool.evidenceList.Remove(e)
  351. e.DetachPrev()
  352. }
  353. }
  354. }
  355. func (evpool *Pool) pruneExpiredPOLC() {
  356. evpool.logger.Debug("Pruning expired POLC's")
  357. iter, err := dbm.IteratePrefix(evpool.evidenceStore, []byte{baseKeyPOLC})
  358. if err != nil {
  359. evpool.logger.Error("Unable to iterate over POLC's", "err", err)
  360. return
  361. }
  362. defer iter.Close()
  363. for ; iter.Valid(); iter.Next() {
  364. proofBytes := iter.Value()
  365. var proof types.ProofOfLockChange
  366. err := cdc.UnmarshalBinaryBare(proofBytes, &proof)
  367. if err != nil {
  368. evpool.logger.Error("Unable to unmarshal POLC", "err", err)
  369. continue
  370. }
  371. if !evpool.IsExpired(proof.Height()-1, proof.Time()) {
  372. return
  373. }
  374. err = evpool.evidenceStore.Delete(iter.Key())
  375. if err != nil {
  376. evpool.logger.Error("Unable to delete expired POLC", "err", err)
  377. continue
  378. }
  379. evpool.logger.Info("Deleted expired POLC", "polc", proof)
  380. }
  381. }
  382. func evMapKey(ev types.Evidence) string {
  383. return string(ev.Hash())
  384. }
  385. func (evpool *Pool) updateValToLastHeight(blockHeight int64, state sm.State) {
  386. // Update current validators & add new ones.
  387. for _, val := range state.Validators.Validators {
  388. evpool.valToLastHeight[string(val.Address)] = blockHeight
  389. }
  390. // Remove validators outside of MaxAgeNumBlocks & MaxAgeDuration.
  391. removeHeight := blockHeight - state.ConsensusParams.Evidence.MaxAgeNumBlocks
  392. if removeHeight >= 1 {
  393. for val, height := range evpool.valToLastHeight {
  394. if height <= removeHeight {
  395. delete(evpool.valToLastHeight, val)
  396. }
  397. }
  398. }
  399. }
  400. func buildValToLastHeightMap(state sm.State, stateDB dbm.DB, blockStore *store.BlockStore) (valToLastHeightMap, error) {
  401. var (
  402. valToLastHeight = make(map[string]int64)
  403. params = state.ConsensusParams.Evidence
  404. numBlocks = int64(0)
  405. minAgeTime = time.Now().Add(-params.MaxAgeDuration)
  406. height = state.LastBlockHeight
  407. )
  408. if height == 0 {
  409. return valToLastHeight, nil
  410. }
  411. meta := blockStore.LoadBlockMeta(height)
  412. if meta == nil {
  413. return nil, fmt.Errorf("block meta for height %d not found", height)
  414. }
  415. blockTime := meta.Header.Time
  416. // From state.LastBlockHeight, build a map of "active" validators until
  417. // MaxAgeNumBlocks is passed and block time is less than now() -
  418. // MaxAgeDuration.
  419. for height >= 1 && (numBlocks <= params.MaxAgeNumBlocks || !blockTime.Before(minAgeTime)) {
  420. valSet, err := sm.LoadValidators(stateDB, height)
  421. if err != nil {
  422. // last stored height -> return
  423. if _, ok := err.(sm.ErrNoValSetForHeight); ok {
  424. return valToLastHeight, nil
  425. }
  426. return nil, fmt.Errorf("validator set for height %d not found", height)
  427. }
  428. for _, val := range valSet.Validators {
  429. key := string(val.Address)
  430. if _, ok := valToLastHeight[key]; !ok {
  431. valToLastHeight[key] = height
  432. }
  433. }
  434. height--
  435. if height > 0 {
  436. // NOTE: we assume here blockStore and state.Validators are in sync. I.e if
  437. // block N is stored, then validators for height N are also stored in
  438. // state.
  439. meta := blockStore.LoadBlockMeta(height)
  440. if meta == nil {
  441. return nil, fmt.Errorf("block meta for height %d not found", height)
  442. }
  443. blockTime = meta.Header.Time
  444. }
  445. numBlocks++
  446. }
  447. return valToLastHeight, nil
  448. }
  449. // big endian padded hex
  450. func bE(h int64) string {
  451. return fmt.Sprintf("%0.16X", h)
  452. }
  453. func keyCommitted(evidence types.Evidence) []byte {
  454. return append([]byte{baseKeyCommitted}, keySuffix(evidence)...)
  455. }
  456. func keyPending(evidence types.Evidence) []byte {
  457. return append([]byte{baseKeyPending}, keySuffix(evidence)...)
  458. }
  459. func keyPOLC(polc types.ProofOfLockChange) []byte {
  460. return keyPOLCFromHeightAndRound(polc.Height(), polc.Round())
  461. }
  462. func keyPOLCFromHeightAndRound(height int64, round int) []byte {
  463. return append([]byte{baseKeyPOLC}, []byte(fmt.Sprintf("%s/%s", bE(height), bE(int64(round))))...)
  464. }
  465. func keySuffix(evidence types.Evidence) []byte {
  466. return []byte(fmt.Sprintf("%s/%X", bE(evidence.Height()), evidence.Hash()))
  467. }
  468. // ErrInvalidEvidence returns when evidence failed to validate
  469. type ErrInvalidEvidence struct {
  470. Reason error
  471. }
  472. func (e ErrInvalidEvidence) Error() string {
  473. return fmt.Sprintf("evidence is not valid: %v ", e.Reason)
  474. }