handler.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Handler is the API for Feeds
  17. // It enables creating, updating, syncing and retrieving feed updates and their data
  18. package feeds
  19. import (
  20. "bytes"
  21. "context"
  22. "fmt"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/swarm/storage/feeds/lookup"
  26. "github.com/ethereum/go-ethereum/swarm/log"
  27. "github.com/ethereum/go-ethereum/swarm/storage"
  28. )
  29. type Handler struct {
  30. chunkStore *storage.NetStore
  31. HashSize int
  32. cache map[uint64]*cacheEntry
  33. cacheLock sync.RWMutex
  34. storeTimeout time.Duration
  35. queryMaxPeriods uint32
  36. }
  37. // HandlerParams pass parameters to the Handler constructor NewHandler
  38. // Signer and TimestampProvider are mandatory parameters
  39. type HandlerParams struct {
  40. }
  41. // hashPool contains a pool of ready hashers
  42. var hashPool sync.Pool
  43. // init initializes the package and hashPool
  44. func init() {
  45. hashPool = sync.Pool{
  46. New: func() interface{} {
  47. return storage.MakeHashFunc(feedsHashAlgorithm)()
  48. },
  49. }
  50. }
  51. // NewHandler creates a new Swarm Feeds API
  52. func NewHandler(params *HandlerParams) *Handler {
  53. fh := &Handler{
  54. cache: make(map[uint64]*cacheEntry),
  55. }
  56. for i := 0; i < hasherCount; i++ {
  57. hashfunc := storage.MakeHashFunc(feedsHashAlgorithm)()
  58. if fh.HashSize == 0 {
  59. fh.HashSize = hashfunc.Size()
  60. }
  61. hashPool.Put(hashfunc)
  62. }
  63. return fh
  64. }
  65. // SetStore sets the store backend for the Swarm Feeds API
  66. func (h *Handler) SetStore(store *storage.NetStore) {
  67. h.chunkStore = store
  68. }
  69. // Validate is a chunk validation method
  70. // If it looks like a feed update, the chunk address is checked against the userAddr of the update's signature
  71. // It implements the storage.ChunkValidator interface
  72. func (h *Handler) Validate(chunkAddr storage.Address, data []byte) bool {
  73. dataLength := len(data)
  74. if dataLength < minimumSignedUpdateLength {
  75. return false
  76. }
  77. // check if it is a properly formatted update chunk with
  78. // valid signature and proof of ownership of the feed it is trying
  79. // to update
  80. // First, deserialize the chunk
  81. var r Request
  82. if err := r.fromChunk(chunkAddr, data); err != nil {
  83. log.Debug("Invalid feed update chunk", "addr", chunkAddr.Hex(), "err", err.Error())
  84. return false
  85. }
  86. // Verify signatures and that the signer actually owns the feed
  87. // If it fails, it means either the signature is not valid, data is corrupted
  88. // or someone is trying to update someone else's feed.
  89. if err := r.Verify(); err != nil {
  90. log.Debug("Invalid feed update signature", "err", err)
  91. return false
  92. }
  93. return true
  94. }
  95. // GetContent retrieves the data payload of the last synced update of the Feed
  96. func (h *Handler) GetContent(feed *Feed) (storage.Address, []byte, error) {
  97. if feed == nil {
  98. return nil, nil, NewError(ErrInvalidValue, "feed is nil")
  99. }
  100. feedUpdate := h.get(feed)
  101. if feedUpdate == nil {
  102. return nil, nil, NewError(ErrNotFound, "feed update not cached")
  103. }
  104. return feedUpdate.lastKey, feedUpdate.data, nil
  105. }
  106. // NewRequest prepares a Request structure with all the necessary information to
  107. // just add the desired data and sign it.
  108. // The resulting structure can then be signed and passed to Handler.Update to be verified and sent
  109. func (h *Handler) NewRequest(ctx context.Context, feed *Feed) (request *Request, err error) {
  110. if feed == nil {
  111. return nil, NewError(ErrInvalidValue, "feed cannot be nil")
  112. }
  113. now := TimestampProvider.Now().Time
  114. request = new(Request)
  115. request.Header.Version = ProtocolVersion
  116. query := NewQueryLatest(feed, lookup.NoClue)
  117. feedUpdate, err := h.Lookup(ctx, query)
  118. if err != nil {
  119. if err.(*Error).code != ErrNotFound {
  120. return nil, err
  121. }
  122. // not finding updates means that there is a network error
  123. // or that the feed really does not have updates
  124. }
  125. request.Feed = *feed
  126. // if we already have an update, then find next epoch
  127. if feedUpdate != nil {
  128. request.Epoch = lookup.GetNextEpoch(feedUpdate.Epoch, now)
  129. } else {
  130. request.Epoch = lookup.GetFirstEpoch(now)
  131. }
  132. return request, nil
  133. }
  134. // Lookup retrieves a specific or latest feed update
  135. // Lookup works differently depending on the configuration of `query`
  136. // See the `query` documentation and helper functions:
  137. // `NewQueryLatest` and `NewQuery`
  138. func (h *Handler) Lookup(ctx context.Context, query *Query) (*cacheEntry, error) {
  139. timeLimit := query.TimeLimit
  140. if timeLimit == 0 { // if time limit is set to zero, the user wants to get the latest update
  141. timeLimit = TimestampProvider.Now().Time
  142. }
  143. if query.Hint == lookup.NoClue { // try to use our cache
  144. entry := h.get(&query.Feed)
  145. if entry != nil && entry.Epoch.Time <= timeLimit { // avoid bad hints
  146. query.Hint = entry.Epoch
  147. }
  148. }
  149. // we can't look for anything without a store
  150. if h.chunkStore == nil {
  151. return nil, NewError(ErrInit, "Call Handler.SetStore() before performing lookups")
  152. }
  153. var id ID
  154. id.Feed = query.Feed
  155. var readCount int
  156. // Invoke the lookup engine.
  157. // The callback will be called every time the lookup algorithm needs to guess
  158. requestPtr, err := lookup.Lookup(timeLimit, query.Hint, func(epoch lookup.Epoch, now uint64) (interface{}, error) {
  159. readCount++
  160. id.Epoch = epoch
  161. ctx, cancel := context.WithTimeout(ctx, defaultRetrieveTimeout)
  162. defer cancel()
  163. chunk, err := h.chunkStore.Get(ctx, id.Addr())
  164. if err != nil { // TODO: check for catastrophic errors other than chunk not found
  165. return nil, nil
  166. }
  167. var request Request
  168. if err := request.fromChunk(chunk.Address(), chunk.Data()); err != nil {
  169. return nil, nil
  170. }
  171. if request.Time <= timeLimit {
  172. return &request, nil
  173. }
  174. return nil, nil
  175. })
  176. if err != nil {
  177. return nil, err
  178. }
  179. log.Info(fmt.Sprintf("Feed lookup finished in %d lookups", readCount))
  180. request, _ := requestPtr.(*Request)
  181. if request == nil {
  182. return nil, NewError(ErrNotFound, "no feed updates found")
  183. }
  184. return h.updateCache(request)
  185. }
  186. // update feed updates cache with specified content
  187. func (h *Handler) updateCache(request *Request) (*cacheEntry, error) {
  188. updateAddr := request.Addr()
  189. log.Trace("feed cache update", "topic", request.Topic.Hex(), "updateaddr", updateAddr, "epoch time", request.Epoch.Time, "epoch level", request.Epoch.Level)
  190. feedUpdate := h.get(&request.Feed)
  191. if feedUpdate == nil {
  192. feedUpdate = &cacheEntry{}
  193. h.set(&request.Feed, feedUpdate)
  194. }
  195. // update our rsrcs entry map
  196. feedUpdate.lastKey = updateAddr
  197. feedUpdate.Update = request.Update
  198. feedUpdate.Reader = bytes.NewReader(feedUpdate.data)
  199. return feedUpdate, nil
  200. }
  201. // Update publishes a feed update
  202. // Note that a Feed update cannot span chunks, and thus has a MAX NET LENGTH 4096, INCLUDING update header data and signature.
  203. // This results in a max payload of `maxUpdateDataLength` (check update.go for more details)
  204. // An error will be returned if the total length of the chunk payload will exceed this limit.
  205. // Update can only check if the caller is trying to overwrite the very last known version, otherwise it just puts the update
  206. // on the network.
  207. func (h *Handler) Update(ctx context.Context, r *Request) (updateAddr storage.Address, err error) {
  208. // we can't update anything without a store
  209. if h.chunkStore == nil {
  210. return nil, NewError(ErrInit, "Call Handler.SetStore() before updating")
  211. }
  212. feedUpdate := h.get(&r.Feed)
  213. if feedUpdate != nil && feedUpdate.Epoch.Equals(r.Epoch) { // This is the only cheap check we can do for sure
  214. return nil, NewError(ErrInvalidValue, "A former update in this epoch is already known to exist")
  215. }
  216. chunk, err := r.toChunk() // Serialize the update into a chunk. Fails if data is too big
  217. if err != nil {
  218. return nil, err
  219. }
  220. // send the chunk
  221. h.chunkStore.Put(ctx, chunk)
  222. log.Trace("feed update", "updateAddr", r.idAddr, "epoch time", r.Epoch.Time, "epoch level", r.Epoch.Level, "data", chunk.Data())
  223. // update our feed updates map cache entry if the new update is older than the one we have, if we have it.
  224. if feedUpdate != nil && r.Epoch.After(feedUpdate.Epoch) {
  225. feedUpdate.Epoch = r.Epoch
  226. feedUpdate.data = make([]byte, len(r.data))
  227. feedUpdate.lastKey = r.idAddr
  228. copy(feedUpdate.data, r.data)
  229. feedUpdate.Reader = bytes.NewReader(feedUpdate.data)
  230. }
  231. return r.idAddr, nil
  232. }
  233. // Retrieves the feed update cache value for the given nameHash
  234. func (h *Handler) get(feed *Feed) *cacheEntry {
  235. mapKey := feed.mapKey()
  236. h.cacheLock.RLock()
  237. defer h.cacheLock.RUnlock()
  238. feedUpdate := h.cache[mapKey]
  239. return feedUpdate
  240. }
  241. // Sets the feed update cache value for the given Feed
  242. func (h *Handler) set(feed *Feed, feedUpdate *cacheEntry) {
  243. mapKey := feed.mapKey()
  244. h.cacheLock.Lock()
  245. defer h.cacheLock.Unlock()
  246. h.cache[mapKey] = feedUpdate
  247. }