github.com/shyftnetwork/go-empyrean@v1.8.3-0.20191127201940-fbfca9338f04/swarm/network/stream/syncer_test.go (about) 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 17 package stream 18 19 import ( 20 "context" 21 "errors" 22 "fmt" 23 "io/ioutil" 24 "math" 25 "os" 26 "sync" 27 "sync/atomic" 28 "testing" 29 "time" 30 31 "github.com/ShyftNetwork/go-empyrean/common" 32 "github.com/ShyftNetwork/go-empyrean/node" 33 "github.com/ShyftNetwork/go-empyrean/p2p/enode" 34 "github.com/ShyftNetwork/go-empyrean/p2p/simulations/adapters" 35 "github.com/ShyftNetwork/go-empyrean/swarm/log" 36 "github.com/ShyftNetwork/go-empyrean/swarm/network" 37 "github.com/ShyftNetwork/go-empyrean/swarm/network/simulation" 38 "github.com/ShyftNetwork/go-empyrean/swarm/state" 39 "github.com/ShyftNetwork/go-empyrean/swarm/storage" 40 "github.com/ShyftNetwork/go-empyrean/swarm/storage/mock" 41 mockmem "github.com/ShyftNetwork/go-empyrean/swarm/storage/mock/mem" 42 "github.com/ShyftNetwork/go-empyrean/swarm/testutil" 43 ) 44 45 const dataChunkCount = 200 46 47 func TestSyncerSimulation(t *testing.T) { 48 testSyncBetweenNodes(t, 2, dataChunkCount, true, 1) 49 testSyncBetweenNodes(t, 4, dataChunkCount, true, 1) 50 testSyncBetweenNodes(t, 8, dataChunkCount, true, 1) 51 testSyncBetweenNodes(t, 16, dataChunkCount, true, 1) 52 } 53 54 func createMockStore(globalStore mock.GlobalStorer, id enode.ID, addr *network.BzzAddr) (lstore storage.ChunkStore, datadir string, err error) { 55 address := common.BytesToAddress(id.Bytes()) 56 mockStore := globalStore.NewNodeStore(address) 57 params := storage.NewDefaultLocalStoreParams() 58 59 datadir, err = ioutil.TempDir("", "localMockStore-"+id.TerminalString()) 60 if err != nil { 61 return nil, "", err 62 } 63 params.Init(datadir) 64 params.BaseKey = addr.Over() 65 lstore, err = storage.NewLocalStore(params, mockStore) 66 if err != nil { 67 return nil, "", err 68 } 69 return lstore, datadir, nil 70 } 71 72 func testSyncBetweenNodes(t *testing.T, nodes, chunkCount int, skipCheck bool, po uint8) { 73 74 sim := simulation.New(map[string]simulation.ServiceFunc{ 75 "streamer": func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error) { 76 var store storage.ChunkStore 77 var datadir string 78 79 node := ctx.Config.Node() 80 addr := network.NewAddr(node) 81 //hack to put addresses in same space 82 addr.OAddr[0] = byte(0) 83 84 if *useMockStore { 85 store, datadir, err = createMockStore(mockmem.NewGlobalStore(), node.ID(), addr) 86 } else { 87 store, datadir, err = createTestLocalStorageForID(node.ID(), addr) 88 } 89 if err != nil { 90 return nil, nil, err 91 } 92 bucket.Store(bucketKeyStore, store) 93 cleanup = func() { 94 store.Close() 95 os.RemoveAll(datadir) 96 } 97 localStore := store.(*storage.LocalStore) 98 netStore, err := storage.NewNetStore(localStore, nil) 99 if err != nil { 100 return nil, nil, err 101 } 102 bucket.Store(bucketKeyDB, netStore) 103 kad := network.NewKademlia(addr.Over(), network.NewKadParams()) 104 delivery := NewDelivery(kad, netStore) 105 netStore.NewNetFetcherFunc = network.NewFetcherFactory(delivery.RequestFromPeers, true).New 106 107 bucket.Store(bucketKeyDelivery, delivery) 108 109 r := NewRegistry(addr.ID(), delivery, netStore, state.NewInmemoryStore(), &RegistryOptions{ 110 Retrieval: RetrievalDisabled, 111 Syncing: SyncingAutoSubscribe, 112 SkipCheck: skipCheck, 113 }, nil) 114 115 fileStore := storage.NewFileStore(netStore, storage.NewFileStoreParams()) 116 bucket.Store(bucketKeyFileStore, fileStore) 117 118 return r, cleanup, nil 119 120 }, 121 }) 122 defer sim.Close() 123 124 // create context for simulation run 125 timeout := 30 * time.Second 126 ctx, cancel := context.WithTimeout(context.Background(), timeout) 127 // defer cancel should come before defer simulation teardown 128 defer cancel() 129 130 _, err := sim.AddNodesAndConnectChain(nodes) 131 if err != nil { 132 t.Fatal(err) 133 } 134 result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) (err error) { 135 nodeIDs := sim.UpNodeIDs() 136 137 nodeIndex := make(map[enode.ID]int) 138 for i, id := range nodeIDs { 139 nodeIndex[id] = i 140 } 141 142 disconnections := sim.PeerEvents( 143 context.Background(), 144 sim.NodeIDs(), 145 simulation.NewPeerEventsFilter().Drop(), 146 ) 147 148 var disconnected atomic.Value 149 go func() { 150 for d := range disconnections { 151 if d.Error != nil { 152 log.Error("peer drop", "node", d.NodeID, "peer", d.PeerID) 153 disconnected.Store(true) 154 } 155 } 156 }() 157 defer func() { 158 if err != nil { 159 if yes, ok := disconnected.Load().(bool); ok && yes { 160 err = errors.New("disconnect events received") 161 } 162 } 163 }() 164 165 // each node Subscribes to each other's swarmChunkServerStreamName 166 for j := 0; j < nodes-1; j++ { 167 id := nodeIDs[j] 168 client, err := sim.Net.GetNode(id).Client() 169 if err != nil { 170 t.Fatal(err) 171 } 172 sid := nodeIDs[j+1] 173 client.CallContext(ctx, nil, "stream_subscribeStream", sid, NewStream("SYNC", FormatSyncBinKey(1), false), NewRange(0, 0), Top) 174 if err != nil { 175 return err 176 } 177 if j > 0 || nodes == 2 { 178 item, ok := sim.NodeItem(nodeIDs[j], bucketKeyFileStore) 179 if !ok { 180 return fmt.Errorf("No filestore") 181 } 182 fileStore := item.(*storage.FileStore) 183 size := chunkCount * chunkSize 184 _, wait, err := fileStore.Store(ctx, testutil.RandomReader(j, size), int64(size), false) 185 if err != nil { 186 t.Fatal(err.Error()) 187 } 188 wait(ctx) 189 } 190 } 191 // here we distribute chunks of a random file into stores 1...nodes 192 if _, err := sim.WaitTillHealthy(ctx); err != nil { 193 return err 194 } 195 196 // collect hashes in po 1 bin for each node 197 hashes := make([][]storage.Address, nodes) 198 totalHashes := 0 199 hashCounts := make([]int, nodes) 200 for i := nodes - 1; i >= 0; i-- { 201 if i < nodes-1 { 202 hashCounts[i] = hashCounts[i+1] 203 } 204 item, ok := sim.NodeItem(nodeIDs[i], bucketKeyDB) 205 if !ok { 206 return fmt.Errorf("No DB") 207 } 208 netStore := item.(*storage.NetStore) 209 netStore.Iterator(0, math.MaxUint64, po, func(addr storage.Address, index uint64) bool { 210 hashes[i] = append(hashes[i], addr) 211 totalHashes++ 212 hashCounts[i]++ 213 return true 214 }) 215 } 216 var total, found int 217 for _, node := range nodeIDs { 218 i := nodeIndex[node] 219 220 for j := i; j < nodes; j++ { 221 total += len(hashes[j]) 222 for _, key := range hashes[j] { 223 item, ok := sim.NodeItem(nodeIDs[j], bucketKeyDB) 224 if !ok { 225 return fmt.Errorf("No DB") 226 } 227 db := item.(*storage.NetStore) 228 _, err := db.Get(ctx, key) 229 if err == nil { 230 found++ 231 } 232 } 233 } 234 log.Debug("sync check", "node", node, "index", i, "bin", po, "found", found, "total", total) 235 } 236 if total == found && total > 0 { 237 return nil 238 } 239 return fmt.Errorf("Total not equallying found: total is %d", total) 240 }) 241 242 if result.Error != nil { 243 t.Fatal(result.Error) 244 } 245 } 246 247 //TestSameVersionID just checks that if the version is not changed, 248 //then streamer peers see each other 249 func TestSameVersionID(t *testing.T) { 250 //test version ID 251 v := uint(1) 252 sim := simulation.New(map[string]simulation.ServiceFunc{ 253 "streamer": func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error) { 254 var store storage.ChunkStore 255 var datadir string 256 257 node := ctx.Config.Node() 258 addr := network.NewAddr(node) 259 260 store, datadir, err = createTestLocalStorageForID(node.ID(), addr) 261 if err != nil { 262 return nil, nil, err 263 } 264 bucket.Store(bucketKeyStore, store) 265 cleanup = func() { 266 store.Close() 267 os.RemoveAll(datadir) 268 } 269 localStore := store.(*storage.LocalStore) 270 netStore, err := storage.NewNetStore(localStore, nil) 271 if err != nil { 272 return nil, nil, err 273 } 274 bucket.Store(bucketKeyDB, netStore) 275 kad := network.NewKademlia(addr.Over(), network.NewKadParams()) 276 delivery := NewDelivery(kad, netStore) 277 netStore.NewNetFetcherFunc = network.NewFetcherFactory(delivery.RequestFromPeers, true).New 278 279 bucket.Store(bucketKeyDelivery, delivery) 280 281 r := NewRegistry(addr.ID(), delivery, netStore, state.NewInmemoryStore(), &RegistryOptions{ 282 Retrieval: RetrievalDisabled, 283 Syncing: SyncingAutoSubscribe, 284 }, nil) 285 //assign to each node the same version ID 286 r.spec.Version = v 287 288 bucket.Store(bucketKeyRegistry, r) 289 290 return r, cleanup, nil 291 292 }, 293 }) 294 defer sim.Close() 295 296 //connect just two nodes 297 log.Info("Adding nodes to simulation") 298 _, err := sim.AddNodesAndConnectChain(2) 299 if err != nil { 300 t.Fatal(err) 301 } 302 303 log.Info("Starting simulation") 304 ctx := context.Background() 305 //make sure they have time to connect 306 time.Sleep(200 * time.Millisecond) 307 result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) error { 308 //get the pivot node's filestore 309 nodes := sim.UpNodeIDs() 310 311 item, ok := sim.NodeItem(nodes[0], bucketKeyRegistry) 312 if !ok { 313 return fmt.Errorf("No filestore") 314 } 315 registry := item.(*Registry) 316 317 //the peers should connect, thus getting the peer should not return nil 318 if registry.getPeer(nodes[1]) == nil { 319 t.Fatal("Expected the peer to not be nil, but it is") 320 } 321 return nil 322 }) 323 if result.Error != nil { 324 t.Fatal(result.Error) 325 } 326 log.Info("Simulation ended") 327 } 328 329 //TestDifferentVersionID proves that if the streamer protocol version doesn't match, 330 //then the peers are not connected at streamer level 331 func TestDifferentVersionID(t *testing.T) { 332 //create a variable to hold the version ID 333 v := uint(0) 334 sim := simulation.New(map[string]simulation.ServiceFunc{ 335 "streamer": func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error) { 336 var store storage.ChunkStore 337 var datadir string 338 339 node := ctx.Config.Node() 340 addr := network.NewAddr(node) 341 342 store, datadir, err = createTestLocalStorageForID(node.ID(), addr) 343 if err != nil { 344 return nil, nil, err 345 } 346 bucket.Store(bucketKeyStore, store) 347 cleanup = func() { 348 store.Close() 349 os.RemoveAll(datadir) 350 } 351 localStore := store.(*storage.LocalStore) 352 netStore, err := storage.NewNetStore(localStore, nil) 353 if err != nil { 354 return nil, nil, err 355 } 356 bucket.Store(bucketKeyDB, netStore) 357 kad := network.NewKademlia(addr.Over(), network.NewKadParams()) 358 delivery := NewDelivery(kad, netStore) 359 netStore.NewNetFetcherFunc = network.NewFetcherFactory(delivery.RequestFromPeers, true).New 360 361 bucket.Store(bucketKeyDelivery, delivery) 362 363 r := NewRegistry(addr.ID(), delivery, netStore, state.NewInmemoryStore(), &RegistryOptions{ 364 Retrieval: RetrievalDisabled, 365 Syncing: SyncingAutoSubscribe, 366 }, nil) 367 368 //increase the version ID for each node 369 v++ 370 r.spec.Version = v 371 372 bucket.Store(bucketKeyRegistry, r) 373 374 return r, cleanup, nil 375 376 }, 377 }) 378 defer sim.Close() 379 380 //connect the nodes 381 log.Info("Adding nodes to simulation") 382 _, err := sim.AddNodesAndConnectChain(2) 383 if err != nil { 384 t.Fatal(err) 385 } 386 387 log.Info("Starting simulation") 388 ctx := context.Background() 389 //make sure they have time to connect 390 time.Sleep(200 * time.Millisecond) 391 result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) error { 392 //get the pivot node's filestore 393 nodes := sim.UpNodeIDs() 394 395 item, ok := sim.NodeItem(nodes[0], bucketKeyRegistry) 396 if !ok { 397 return fmt.Errorf("No filestore") 398 } 399 registry := item.(*Registry) 400 401 //getting the other peer should fail due to the different version numbers 402 if registry.getPeer(nodes[1]) != nil { 403 t.Fatal("Expected the peer to be nil, but it is not") 404 } 405 return nil 406 }) 407 if result.Error != nil { 408 t.Fatal(result.Error) 409 } 410 log.Info("Simulation ended") 411 412 }