common_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. package stream
  17. import (
  18. "context"
  19. "encoding/binary"
  20. "errors"
  21. "flag"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "os"
  26. "sync/atomic"
  27. "testing"
  28. "time"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/node"
  32. "github.com/ethereum/go-ethereum/p2p"
  33. "github.com/ethereum/go-ethereum/p2p/discover"
  34. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  35. p2ptest "github.com/ethereum/go-ethereum/p2p/testing"
  36. "github.com/ethereum/go-ethereum/rpc"
  37. "github.com/ethereum/go-ethereum/swarm/network"
  38. "github.com/ethereum/go-ethereum/swarm/state"
  39. "github.com/ethereum/go-ethereum/swarm/storage"
  40. "github.com/ethereum/go-ethereum/swarm/storage/mock"
  41. "github.com/ethereum/go-ethereum/swarm/storage/mock/db"
  42. colorable "github.com/mattn/go-colorable"
  43. )
  44. var (
  45. deliveries map[discover.NodeID]*Delivery
  46. stores map[discover.NodeID]storage.ChunkStore
  47. toAddr func(discover.NodeID) *network.BzzAddr
  48. peerCount func(discover.NodeID) int
  49. adapter = flag.String("adapter", "sim", "type of simulation: sim|exec|docker")
  50. loglevel = flag.Int("loglevel", 2, "verbosity of logs")
  51. nodes = flag.Int("nodes", 0, "number of nodes")
  52. chunks = flag.Int("chunks", 0, "number of chunks")
  53. useMockStore = flag.Bool("mockstore", false, "disabled mock store (default: enabled)")
  54. )
  55. var (
  56. defaultSkipCheck bool
  57. waitPeerErrC chan error
  58. chunkSize = 4096
  59. registries map[discover.NodeID]*TestRegistry
  60. createStoreFunc func(id discover.NodeID, addr *network.BzzAddr) (storage.ChunkStore, error)
  61. getRetrieveFunc = defaultRetrieveFunc
  62. subscriptionCount = 0
  63. globalStore mock.GlobalStorer
  64. globalStoreDir string
  65. )
  66. var services = adapters.Services{
  67. "streamer": NewStreamerService,
  68. "intervalsStreamer": newIntervalsStreamerService,
  69. }
  70. func init() {
  71. flag.Parse()
  72. // register the Delivery service which will run as a devp2p
  73. // protocol when using the exec adapter
  74. adapters.RegisterServices(services)
  75. log.PrintOrigins(true)
  76. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
  77. }
  78. func createGlobalStore() {
  79. var err error
  80. globalStoreDir, err = ioutil.TempDir("", "global.store")
  81. if err != nil {
  82. log.Error("Error initiating global store temp directory!", "err", err)
  83. return
  84. }
  85. globalStore, err = db.NewGlobalStore(globalStoreDir)
  86. if err != nil {
  87. log.Error("Error initiating global store!", "err", err)
  88. }
  89. }
  90. // NewStreamerService
  91. func NewStreamerService(ctx *adapters.ServiceContext) (node.Service, error) {
  92. var err error
  93. id := ctx.Config.ID
  94. addr := toAddr(id)
  95. kad := network.NewKademlia(addr.Over(), network.NewKadParams())
  96. stores[id], err = createStoreFunc(id, addr)
  97. if err != nil {
  98. return nil, err
  99. }
  100. store := stores[id].(*storage.LocalStore)
  101. db := storage.NewDBAPI(store)
  102. delivery := NewDelivery(kad, db)
  103. deliveries[id] = delivery
  104. r := NewRegistry(addr, delivery, db, state.NewInmemoryStore(), &RegistryOptions{
  105. SkipCheck: defaultSkipCheck,
  106. DoRetrieve: false,
  107. })
  108. RegisterSwarmSyncerServer(r, db)
  109. RegisterSwarmSyncerClient(r, db)
  110. go func() {
  111. waitPeerErrC <- waitForPeers(r, 1*time.Second, peerCount(id))
  112. }()
  113. fileStore := storage.NewFileStore(storage.NewNetStore(store, getRetrieveFunc(id)), storage.NewFileStoreParams())
  114. testRegistry := &TestRegistry{Registry: r, fileStore: fileStore}
  115. registries[id] = testRegistry
  116. return testRegistry, nil
  117. }
  118. func defaultRetrieveFunc(id discover.NodeID) func(ctx context.Context, chunk *storage.Chunk) error {
  119. return nil
  120. }
  121. func datadirsCleanup() {
  122. for _, id := range ids {
  123. os.RemoveAll(datadirs[id])
  124. }
  125. if globalStoreDir != "" {
  126. os.RemoveAll(globalStoreDir)
  127. }
  128. }
  129. //local stores need to be cleaned up after the sim is done
  130. func localStoreCleanup() {
  131. log.Info("Cleaning up...")
  132. for _, id := range ids {
  133. registries[id].Close()
  134. stores[id].Close()
  135. }
  136. log.Info("Local store cleanup done")
  137. }
  138. func newStreamerTester(t *testing.T) (*p2ptest.ProtocolTester, *Registry, *storage.LocalStore, func(), error) {
  139. // setup
  140. addr := network.RandomAddr() // tested peers peer address
  141. to := network.NewKademlia(addr.OAddr, network.NewKadParams())
  142. // temp datadir
  143. datadir, err := ioutil.TempDir("", "streamer")
  144. if err != nil {
  145. return nil, nil, nil, func() {}, err
  146. }
  147. removeDataDir := func() {
  148. os.RemoveAll(datadir)
  149. }
  150. params := storage.NewDefaultLocalStoreParams()
  151. params.Init(datadir)
  152. params.BaseKey = addr.Over()
  153. localStore, err := storage.NewTestLocalStoreForAddr(params)
  154. if err != nil {
  155. return nil, nil, nil, removeDataDir, err
  156. }
  157. db := storage.NewDBAPI(localStore)
  158. delivery := NewDelivery(to, db)
  159. streamer := NewRegistry(addr, delivery, db, state.NewInmemoryStore(), &RegistryOptions{
  160. SkipCheck: defaultSkipCheck,
  161. })
  162. teardown := func() {
  163. streamer.Close()
  164. removeDataDir()
  165. }
  166. protocolTester := p2ptest.NewProtocolTester(t, network.NewNodeIDFromAddr(addr), 1, streamer.runProtocol)
  167. err = waitForPeers(streamer, 1*time.Second, 1)
  168. if err != nil {
  169. return nil, nil, nil, nil, errors.New("timeout: peer is not created")
  170. }
  171. return protocolTester, streamer, localStore, teardown, nil
  172. }
  173. func waitForPeers(streamer *Registry, timeout time.Duration, expectedPeers int) error {
  174. ticker := time.NewTicker(10 * time.Millisecond)
  175. timeoutTimer := time.NewTimer(timeout)
  176. for {
  177. select {
  178. case <-ticker.C:
  179. if streamer.peersCount() >= expectedPeers {
  180. return nil
  181. }
  182. case <-timeoutTimer.C:
  183. return errors.New("timeout")
  184. }
  185. }
  186. }
  187. type roundRobinStore struct {
  188. index uint32
  189. stores []storage.ChunkStore
  190. }
  191. func newRoundRobinStore(stores ...storage.ChunkStore) *roundRobinStore {
  192. return &roundRobinStore{
  193. stores: stores,
  194. }
  195. }
  196. func (rrs *roundRobinStore) Get(ctx context.Context, addr storage.Address) (*storage.Chunk, error) {
  197. return nil, errors.New("get not well defined on round robin store")
  198. }
  199. func (rrs *roundRobinStore) Put(ctx context.Context, chunk *storage.Chunk) {
  200. i := atomic.AddUint32(&rrs.index, 1)
  201. idx := int(i) % len(rrs.stores)
  202. rrs.stores[idx].Put(ctx, chunk)
  203. }
  204. func (rrs *roundRobinStore) Close() {
  205. for _, store := range rrs.stores {
  206. store.Close()
  207. }
  208. }
  209. type TestRegistry struct {
  210. *Registry
  211. fileStore *storage.FileStore
  212. }
  213. func (r *TestRegistry) APIs() []rpc.API {
  214. a := r.Registry.APIs()
  215. a = append(a, rpc.API{
  216. Namespace: "stream",
  217. Version: "3.0",
  218. Service: r,
  219. Public: true,
  220. })
  221. return a
  222. }
  223. func readAll(fileStore *storage.FileStore, hash []byte) (int64, error) {
  224. r, _ := fileStore.Retrieve(context.TODO(), hash)
  225. buf := make([]byte, 1024)
  226. var n int
  227. var total int64
  228. var err error
  229. for (total == 0 || n > 0) && err == nil {
  230. n, err = r.ReadAt(buf, total)
  231. total += int64(n)
  232. }
  233. if err != nil && err != io.EOF {
  234. return total, err
  235. }
  236. return total, nil
  237. }
  238. func (r *TestRegistry) ReadAll(hash common.Hash) (int64, error) {
  239. return readAll(r.fileStore, hash[:])
  240. }
  241. func (r *TestRegistry) Start(server *p2p.Server) error {
  242. return r.Registry.Start(server)
  243. }
  244. func (r *TestRegistry) Stop() error {
  245. return r.Registry.Stop()
  246. }
  247. type TestExternalRegistry struct {
  248. *Registry
  249. }
  250. func (r *TestExternalRegistry) APIs() []rpc.API {
  251. a := r.Registry.APIs()
  252. a = append(a, rpc.API{
  253. Namespace: "stream",
  254. Version: "3.0",
  255. Service: r,
  256. Public: true,
  257. })
  258. return a
  259. }
  260. func (r *TestExternalRegistry) GetHashes(ctx context.Context, peerId discover.NodeID, s Stream) (*rpc.Subscription, error) {
  261. peer := r.getPeer(peerId)
  262. client, err := peer.getClient(ctx, s)
  263. if err != nil {
  264. return nil, err
  265. }
  266. c := client.Client.(*testExternalClient)
  267. notifier, supported := rpc.NotifierFromContext(ctx)
  268. if !supported {
  269. return nil, fmt.Errorf("Subscribe not supported")
  270. }
  271. sub := notifier.CreateSubscription()
  272. go func() {
  273. // if we begin sending event immediately some events
  274. // will probably be dropped since the subscription ID might not be send to
  275. // the client.
  276. // ref: rpc/subscription_test.go#L65
  277. time.Sleep(1 * time.Second)
  278. for {
  279. select {
  280. case h := <-c.hashes:
  281. <-c.enableNotificationsC // wait for notification subscription to complete
  282. if err := notifier.Notify(sub.ID, h); err != nil {
  283. log.Warn(fmt.Sprintf("rpc sub notifier notify stream %s: %v", s, err))
  284. }
  285. case err := <-sub.Err():
  286. if err != nil {
  287. log.Warn(fmt.Sprintf("caught subscription error in stream %s: %v", s, err))
  288. }
  289. case <-notifier.Closed():
  290. log.Trace(fmt.Sprintf("rpc sub notifier closed"))
  291. return
  292. }
  293. }
  294. }()
  295. return sub, nil
  296. }
  297. func (r *TestExternalRegistry) EnableNotifications(peerId discover.NodeID, s Stream) error {
  298. peer := r.getPeer(peerId)
  299. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  300. defer cancel()
  301. client, err := peer.getClient(ctx, s)
  302. if err != nil {
  303. return err
  304. }
  305. close(client.Client.(*testExternalClient).enableNotificationsC)
  306. return nil
  307. }
  308. // TODO: merge functionalities of testExternalClient and testExternalServer
  309. // with testClient and testServer.
  310. type testExternalClient struct {
  311. hashes chan []byte
  312. db *storage.DBAPI
  313. enableNotificationsC chan struct{}
  314. }
  315. func newTestExternalClient(db *storage.DBAPI) *testExternalClient {
  316. return &testExternalClient{
  317. hashes: make(chan []byte),
  318. db: db,
  319. enableNotificationsC: make(chan struct{}),
  320. }
  321. }
  322. func (c *testExternalClient) NeedData(ctx context.Context, hash []byte) func() {
  323. chunk, _ := c.db.GetOrCreateRequest(ctx, hash)
  324. if chunk.ReqC == nil {
  325. return nil
  326. }
  327. c.hashes <- hash
  328. return func() {
  329. chunk.WaitToStore()
  330. }
  331. }
  332. func (c *testExternalClient) BatchDone(Stream, uint64, []byte, []byte) func() (*TakeoverProof, error) {
  333. return nil
  334. }
  335. func (c *testExternalClient) Close() {}
  336. const testExternalServerBatchSize = 10
  337. type testExternalServer struct {
  338. t string
  339. keyFunc func(key []byte, index uint64)
  340. sessionAt uint64
  341. maxKeys uint64
  342. streamer *TestExternalRegistry
  343. }
  344. func newTestExternalServer(t string, sessionAt, maxKeys uint64, keyFunc func(key []byte, index uint64)) *testExternalServer {
  345. if keyFunc == nil {
  346. keyFunc = binary.BigEndian.PutUint64
  347. }
  348. return &testExternalServer{
  349. t: t,
  350. keyFunc: keyFunc,
  351. sessionAt: sessionAt,
  352. maxKeys: maxKeys,
  353. }
  354. }
  355. func (s *testExternalServer) SetNextBatch(from uint64, to uint64) ([]byte, uint64, uint64, *HandoverProof, error) {
  356. if from == 0 && to == 0 {
  357. from = s.sessionAt
  358. to = s.sessionAt + testExternalServerBatchSize
  359. }
  360. if to-from > testExternalServerBatchSize {
  361. to = from + testExternalServerBatchSize - 1
  362. }
  363. if from >= s.maxKeys && to > s.maxKeys {
  364. return nil, 0, 0, nil, io.EOF
  365. }
  366. if to > s.maxKeys {
  367. to = s.maxKeys
  368. }
  369. b := make([]byte, HashSize*(to-from+1))
  370. for i := from; i <= to; i++ {
  371. s.keyFunc(b[(i-from)*HashSize:(i-from+1)*HashSize], i)
  372. }
  373. return b, from, to, nil, nil
  374. }
  375. func (s *testExternalServer) GetData(context.Context, []byte) ([]byte, error) {
  376. return make([]byte, 4096), nil
  377. }
  378. func (s *testExternalServer) Close() {}
  379. // Sets the global value defaultSkipCheck.
  380. // It should be used in test function defer to reset the global value
  381. // to the original value.
  382. //
  383. // defer setDefaultSkipCheck(defaultSkipCheck)
  384. // defaultSkipCheck = skipCheck
  385. //
  386. // This works as defer function arguments evaluations are evaluated as ususal,
  387. // but only the function body invocation is deferred.
  388. func setDefaultSkipCheck(skipCheck bool) {
  389. defaultSkipCheck = skipCheck
  390. }