common_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // Copyright 2016 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 storage
  17. import (
  18. "bytes"
  19. "context"
  20. "crypto/rand"
  21. "flag"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "os"
  26. "sync"
  27. "testing"
  28. "time"
  29. "github.com/ethereum/go-ethereum/log"
  30. ch "github.com/ethereum/go-ethereum/swarm/chunk"
  31. colorable "github.com/mattn/go-colorable"
  32. )
  33. var (
  34. loglevel = flag.Int("loglevel", 3, "verbosity of logs")
  35. getTimeout = 30 * time.Second
  36. )
  37. func init() {
  38. flag.Parse()
  39. log.PrintOrigins(true)
  40. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
  41. }
  42. type brokenLimitedReader struct {
  43. lr io.Reader
  44. errAt int
  45. off int
  46. size int
  47. }
  48. func brokenLimitReader(data io.Reader, size int, errAt int) *brokenLimitedReader {
  49. return &brokenLimitedReader{
  50. lr: data,
  51. errAt: errAt,
  52. size: size,
  53. }
  54. }
  55. func newLDBStore(t *testing.T) (*LDBStore, func()) {
  56. dir, err := ioutil.TempDir("", "bzz-storage-test")
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. log.Trace("memstore.tempdir", "dir", dir)
  61. ldbparams := NewLDBStoreParams(NewDefaultStoreParams(), dir)
  62. db, err := NewLDBStore(ldbparams)
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. cleanup := func() {
  67. db.Close()
  68. err := os.RemoveAll(dir)
  69. if err != nil {
  70. t.Fatal(err)
  71. }
  72. }
  73. return db, cleanup
  74. }
  75. func mputRandomChunks(store ChunkStore, n int, chunksize int64) ([]Chunk, error) {
  76. return mput(store, n, GenerateRandomChunk)
  77. }
  78. func mputChunks(store ChunkStore, chunks ...Chunk) error {
  79. i := 0
  80. f := func(n int64) Chunk {
  81. chunk := chunks[i]
  82. i++
  83. return chunk
  84. }
  85. _, err := mput(store, len(chunks), f)
  86. return err
  87. }
  88. func mput(store ChunkStore, n int, f func(i int64) Chunk) (hs []Chunk, err error) {
  89. // put to localstore and wait for stored channel
  90. // does not check delivery error state
  91. errc := make(chan error)
  92. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  93. defer cancel()
  94. for i := int64(0); i < int64(n); i++ {
  95. chunk := f(ch.DefaultSize)
  96. go func() {
  97. select {
  98. case errc <- store.Put(ctx, chunk):
  99. case <-ctx.Done():
  100. }
  101. }()
  102. hs = append(hs, chunk)
  103. }
  104. // wait for all chunks to be stored
  105. for i := 0; i < n; i++ {
  106. err := <-errc
  107. if err != nil {
  108. return nil, err
  109. }
  110. }
  111. return hs, nil
  112. }
  113. func mget(store ChunkStore, hs []Address, f func(h Address, chunk Chunk) error) error {
  114. wg := sync.WaitGroup{}
  115. wg.Add(len(hs))
  116. errc := make(chan error)
  117. for _, k := range hs {
  118. go func(h Address) {
  119. defer wg.Done()
  120. // TODO: write timeout with context
  121. chunk, err := store.Get(context.TODO(), h)
  122. if err != nil {
  123. errc <- err
  124. return
  125. }
  126. if f != nil {
  127. err = f(h, chunk)
  128. if err != nil {
  129. errc <- err
  130. return
  131. }
  132. }
  133. }(k)
  134. }
  135. go func() {
  136. wg.Wait()
  137. close(errc)
  138. }()
  139. var err error
  140. select {
  141. case err = <-errc:
  142. case <-time.NewTimer(5 * time.Second).C:
  143. err = fmt.Errorf("timed out after 5 seconds")
  144. }
  145. return err
  146. }
  147. func testDataReader(l int) (r io.Reader) {
  148. return io.LimitReader(rand.Reader, int64(l))
  149. }
  150. func (r *brokenLimitedReader) Read(buf []byte) (int, error) {
  151. if r.off+len(buf) > r.errAt {
  152. return 0, fmt.Errorf("Broken reader")
  153. }
  154. r.off += len(buf)
  155. return r.lr.Read(buf)
  156. }
  157. func testStoreRandom(m ChunkStore, n int, chunksize int64, t *testing.T) {
  158. chunks, err := mputRandomChunks(m, n, chunksize)
  159. if err != nil {
  160. t.Fatalf("expected no error, got %v", err)
  161. }
  162. err = mget(m, chunkAddresses(chunks), nil)
  163. if err != nil {
  164. t.Fatalf("testStore failed: %v", err)
  165. }
  166. }
  167. func testStoreCorrect(m ChunkStore, n int, chunksize int64, t *testing.T) {
  168. chunks, err := mputRandomChunks(m, n, chunksize)
  169. if err != nil {
  170. t.Fatalf("expected no error, got %v", err)
  171. }
  172. f := func(h Address, chunk Chunk) error {
  173. if !bytes.Equal(h, chunk.Address()) {
  174. return fmt.Errorf("key does not match retrieved chunk Address")
  175. }
  176. hasher := MakeHashFunc(DefaultHash)()
  177. hasher.ResetWithLength(chunk.SpanBytes())
  178. hasher.Write(chunk.Payload())
  179. exp := hasher.Sum(nil)
  180. if !bytes.Equal(h, exp) {
  181. return fmt.Errorf("key is not hash of chunk data")
  182. }
  183. return nil
  184. }
  185. err = mget(m, chunkAddresses(chunks), f)
  186. if err != nil {
  187. t.Fatalf("testStore failed: %v", err)
  188. }
  189. }
  190. func benchmarkStorePut(store ChunkStore, n int, chunksize int64, b *testing.B) {
  191. chunks := make([]Chunk, n)
  192. i := 0
  193. f := func(dataSize int64) Chunk {
  194. chunk := GenerateRandomChunk(dataSize)
  195. chunks[i] = chunk
  196. i++
  197. return chunk
  198. }
  199. mput(store, n, f)
  200. f = func(dataSize int64) Chunk {
  201. chunk := chunks[i]
  202. i++
  203. return chunk
  204. }
  205. b.ReportAllocs()
  206. b.ResetTimer()
  207. for j := 0; j < b.N; j++ {
  208. i = 0
  209. mput(store, n, f)
  210. }
  211. }
  212. func benchmarkStoreGet(store ChunkStore, n int, chunksize int64, b *testing.B) {
  213. chunks, err := mputRandomChunks(store, n, chunksize)
  214. if err != nil {
  215. b.Fatalf("expected no error, got %v", err)
  216. }
  217. b.ReportAllocs()
  218. b.ResetTimer()
  219. addrs := chunkAddresses(chunks)
  220. for i := 0; i < b.N; i++ {
  221. err := mget(store, addrs, nil)
  222. if err != nil {
  223. b.Fatalf("mget failed: %v", err)
  224. }
  225. }
  226. }
  227. // MapChunkStore is a very simple ChunkStore implementation to store chunks in a map in memory.
  228. type MapChunkStore struct {
  229. chunks map[string]Chunk
  230. mu sync.RWMutex
  231. }
  232. func NewMapChunkStore() *MapChunkStore {
  233. return &MapChunkStore{
  234. chunks: make(map[string]Chunk),
  235. }
  236. }
  237. func (m *MapChunkStore) Put(_ context.Context, ch Chunk) error {
  238. m.mu.Lock()
  239. defer m.mu.Unlock()
  240. m.chunks[ch.Address().Hex()] = ch
  241. return nil
  242. }
  243. func (m *MapChunkStore) Get(_ context.Context, ref Address) (Chunk, error) {
  244. m.mu.RLock()
  245. defer m.mu.RUnlock()
  246. chunk := m.chunks[ref.Hex()]
  247. if chunk == nil {
  248. return nil, ErrChunkNotFound
  249. }
  250. return chunk, nil
  251. }
  252. func (m *MapChunkStore) Close() {
  253. }
  254. func chunkAddresses(chunks []Chunk) []Address {
  255. addrs := make([]Address, len(chunks))
  256. for i, ch := range chunks {
  257. addrs[i] = ch.Address()
  258. }
  259. return addrs
  260. }