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.

263 lines
7.0 KiB

  1. package statesync
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "math/rand"
  6. "sort"
  7. tmsync "github.com/tendermint/tendermint/libs/sync"
  8. "github.com/tendermint/tendermint/p2p"
  9. )
  10. // snapshotKey is a snapshot key used for lookups.
  11. type snapshotKey [sha256.Size]byte
  12. // snapshot contains data about a snapshot.
  13. type snapshot struct {
  14. Height uint64
  15. Format uint32
  16. Chunks uint32
  17. Hash []byte
  18. Metadata []byte
  19. trustedAppHash []byte // populated by light client
  20. }
  21. // Key generates a snapshot key, used for lookups. It takes into account not only the height and
  22. // format, but also the chunks, hash, and metadata in case peers have generated snapshots in a
  23. // non-deterministic manner. All fields must be equal for the snapshot to be considered the same.
  24. func (s *snapshot) Key() snapshotKey {
  25. // Hash.Write() never returns an error.
  26. hasher := sha256.New()
  27. hasher.Write([]byte(fmt.Sprintf("%v:%v:%v", s.Height, s.Format, s.Chunks)))
  28. hasher.Write(s.Hash)
  29. hasher.Write(s.Metadata)
  30. var key snapshotKey
  31. copy(key[:], hasher.Sum(nil))
  32. return key
  33. }
  34. // snapshotPool discovers and aggregates snapshots across peers.
  35. type snapshotPool struct {
  36. stateProvider StateProvider
  37. tmsync.Mutex
  38. snapshots map[snapshotKey]*snapshot
  39. snapshotPeers map[snapshotKey]map[p2p.ID]p2p.Peer
  40. // indexes for fast searches
  41. formatIndex map[uint32]map[snapshotKey]bool
  42. heightIndex map[uint64]map[snapshotKey]bool
  43. peerIndex map[p2p.ID]map[snapshotKey]bool
  44. // blacklists for rejected items
  45. formatBlacklist map[uint32]bool
  46. peerBlacklist map[p2p.ID]bool
  47. snapshotBlacklist map[snapshotKey]bool
  48. }
  49. // newSnapshotPool creates a new snapshot pool. The state source is used for
  50. func newSnapshotPool(stateProvider StateProvider) *snapshotPool {
  51. return &snapshotPool{
  52. stateProvider: stateProvider,
  53. snapshots: make(map[snapshotKey]*snapshot),
  54. snapshotPeers: make(map[snapshotKey]map[p2p.ID]p2p.Peer),
  55. formatIndex: make(map[uint32]map[snapshotKey]bool),
  56. heightIndex: make(map[uint64]map[snapshotKey]bool),
  57. peerIndex: make(map[p2p.ID]map[snapshotKey]bool),
  58. formatBlacklist: make(map[uint32]bool),
  59. peerBlacklist: make(map[p2p.ID]bool),
  60. snapshotBlacklist: make(map[snapshotKey]bool),
  61. }
  62. }
  63. // Add adds a snapshot to the pool, unless the peer has already sent recentSnapshots snapshots. It
  64. // returns true if this was a new, non-blacklisted snapshot. The snapshot height is verified using
  65. // the light client, and the expected app hash is set for the snapshot.
  66. func (p *snapshotPool) Add(peer p2p.Peer, snapshot *snapshot) (bool, error) {
  67. appHash, err := p.stateProvider.AppHash(snapshot.Height)
  68. if err != nil {
  69. return false, err
  70. }
  71. snapshot.trustedAppHash = appHash
  72. key := snapshot.Key()
  73. p.Lock()
  74. defer p.Unlock()
  75. switch {
  76. case p.formatBlacklist[snapshot.Format]:
  77. return false, nil
  78. case p.peerBlacklist[peer.ID()]:
  79. return false, nil
  80. case p.snapshotBlacklist[key]:
  81. return false, nil
  82. case len(p.peerIndex[peer.ID()]) >= recentSnapshots:
  83. return false, nil
  84. }
  85. if p.snapshotPeers[key] == nil {
  86. p.snapshotPeers[key] = make(map[p2p.ID]p2p.Peer)
  87. }
  88. p.snapshotPeers[key][peer.ID()] = peer
  89. if p.peerIndex[peer.ID()] == nil {
  90. p.peerIndex[peer.ID()] = make(map[snapshotKey]bool)
  91. }
  92. p.peerIndex[peer.ID()][key] = true
  93. if p.snapshots[key] != nil {
  94. return false, nil
  95. }
  96. p.snapshots[key] = snapshot
  97. if p.formatIndex[snapshot.Format] == nil {
  98. p.formatIndex[snapshot.Format] = make(map[snapshotKey]bool)
  99. }
  100. p.formatIndex[snapshot.Format][key] = true
  101. if p.heightIndex[snapshot.Height] == nil {
  102. p.heightIndex[snapshot.Height] = make(map[snapshotKey]bool)
  103. }
  104. p.heightIndex[snapshot.Height][key] = true
  105. return true, nil
  106. }
  107. // Best returns the "best" currently known snapshot, if any.
  108. func (p *snapshotPool) Best() *snapshot {
  109. ranked := p.Ranked()
  110. if len(ranked) == 0 {
  111. return nil
  112. }
  113. return ranked[0]
  114. }
  115. // GetPeer returns a random peer for a snapshot, if any.
  116. func (p *snapshotPool) GetPeer(snapshot *snapshot) p2p.Peer {
  117. peers := p.GetPeers(snapshot)
  118. if len(peers) == 0 {
  119. return nil
  120. }
  121. return peers[rand.Intn(len(peers))]
  122. }
  123. // GetPeers returns the peers for a snapshot.
  124. func (p *snapshotPool) GetPeers(snapshot *snapshot) []p2p.Peer {
  125. key := snapshot.Key()
  126. p.Lock()
  127. defer p.Unlock()
  128. peers := make([]p2p.Peer, 0, len(p.snapshotPeers[key]))
  129. for _, peer := range p.snapshotPeers[key] {
  130. peers = append(peers, peer)
  131. }
  132. // sort results, for testability (otherwise order is random, so tests randomly fail)
  133. sort.Slice(peers, func(a int, b int) bool {
  134. return peers[a].ID() < peers[b].ID()
  135. })
  136. return peers
  137. }
  138. // Ranked returns a list of snapshots ranked by preference. The current heuristic is very naïve,
  139. // preferring the snapshot with the greatest height, then greatest format, then greatest number of
  140. // peers. This can be improved quite a lot.
  141. func (p *snapshotPool) Ranked() []*snapshot {
  142. p.Lock()
  143. defer p.Unlock()
  144. candidates := make([]*snapshot, 0, len(p.snapshots))
  145. for _, snapshot := range p.snapshots {
  146. candidates = append(candidates, snapshot)
  147. }
  148. sort.Slice(candidates, func(i, j int) bool {
  149. a := candidates[i]
  150. b := candidates[j]
  151. switch {
  152. case a.Height > b.Height:
  153. return true
  154. case a.Height < b.Height:
  155. return false
  156. case a.Format > b.Format:
  157. return true
  158. case a.Format < b.Format:
  159. return false
  160. case len(p.snapshotPeers[a.Key()]) > len(p.snapshotPeers[b.Key()]):
  161. return true
  162. default:
  163. return false
  164. }
  165. })
  166. return candidates
  167. }
  168. // Reject rejects a snapshot. Rejected snapshots will never be used again.
  169. func (p *snapshotPool) Reject(snapshot *snapshot) {
  170. key := snapshot.Key()
  171. p.Lock()
  172. defer p.Unlock()
  173. p.snapshotBlacklist[key] = true
  174. p.removeSnapshot(key)
  175. }
  176. // RejectFormat rejects a snapshot format. It will never be used again.
  177. func (p *snapshotPool) RejectFormat(format uint32) {
  178. p.Lock()
  179. defer p.Unlock()
  180. p.formatBlacklist[format] = true
  181. for key := range p.formatIndex[format] {
  182. p.removeSnapshot(key)
  183. }
  184. }
  185. // RejectPeer rejects a peer. It will never be used again.
  186. func (p *snapshotPool) RejectPeer(peerID p2p.ID) {
  187. if peerID == "" {
  188. return
  189. }
  190. p.Lock()
  191. defer p.Unlock()
  192. p.removePeer(peerID)
  193. p.peerBlacklist[peerID] = true
  194. }
  195. // RemovePeer removes a peer from the pool, and any snapshots that no longer have peers.
  196. func (p *snapshotPool) RemovePeer(peerID p2p.ID) {
  197. p.Lock()
  198. defer p.Unlock()
  199. p.removePeer(peerID)
  200. }
  201. // removePeer removes a peer. The caller must hold the mutex lock.
  202. func (p *snapshotPool) removePeer(peerID p2p.ID) {
  203. for key := range p.peerIndex[peerID] {
  204. delete(p.snapshotPeers[key], peerID)
  205. if len(p.snapshotPeers[key]) == 0 {
  206. p.removeSnapshot(key)
  207. }
  208. }
  209. delete(p.peerIndex, peerID)
  210. }
  211. // removeSnapshot removes a snapshot. The caller must hold the mutex lock.
  212. func (p *snapshotPool) removeSnapshot(key snapshotKey) {
  213. snapshot := p.snapshots[key]
  214. if snapshot == nil {
  215. return
  216. }
  217. delete(p.snapshots, key)
  218. delete(p.formatIndex[snapshot.Format], key)
  219. delete(p.heightIndex[snapshot.Height], key)
  220. for peerID := range p.snapshotPeers[key] {
  221. delete(p.peerIndex[peerID], key)
  222. }
  223. delete(p.snapshotPeers, key)
  224. }