github.com/gobitfly/go-ethereum@v1.8.12/whisper/whisperv6/peer_test.go (about) 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 17 package whisperv6 18 19 import ( 20 "bytes" 21 "crypto/ecdsa" 22 "fmt" 23 mrand "math/rand" 24 "sync" 25 "sync/atomic" 26 "testing" 27 "time" 28 29 "net" 30 31 "github.com/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/common/hexutil" 33 "github.com/ethereum/go-ethereum/crypto" 34 "github.com/ethereum/go-ethereum/p2p" 35 "github.com/ethereum/go-ethereum/p2p/discover" 36 "github.com/ethereum/go-ethereum/p2p/nat" 37 ) 38 39 var keys = []string{ 40 "d49dcf37238dc8a7aac57dc61b9fee68f0a97f062968978b9fafa7d1033d03a9", 41 "73fd6143c48e80ed3c56ea159fe7494a0b6b393a392227b422f4c3e8f1b54f98", 42 "119dd32adb1daa7a4c7bf77f847fb28730785aa92947edf42fdd997b54de40dc", 43 "deeda8709dea935bb772248a3144dea449ffcc13e8e5a1fd4ef20ce4e9c87837", 44 "5bd208a079633befa349441bdfdc4d85ba9bd56081525008380a63ac38a407cf", 45 "1d27fb4912002d58a2a42a50c97edb05c1b3dffc665dbaa42df1fe8d3d95c9b5", 46 "15def52800c9d6b8ca6f3066b7767a76afc7b611786c1276165fbc61636afb68", 47 "51be6ab4b2dc89f251ff2ace10f3c1cc65d6855f3e083f91f6ff8efdfd28b48c", 48 "ef1ef7441bf3c6419b162f05da6037474664f198b58db7315a6f4de52414b4a0", 49 "09bdf6985aabc696dc1fbeb5381aebd7a6421727343872eb2fadfc6d82486fd9", 50 "15d811bf2e01f99a224cdc91d0cf76cea08e8c67905c16fee9725c9be71185c4", 51 "2f83e45cf1baaea779789f755b7da72d8857aeebff19362dd9af31d3c9d14620", 52 "73f04e34ac6532b19c2aae8f8e52f38df1ac8f5cd10369f92325b9b0494b0590", 53 "1e2e07b69e5025537fb73770f483dc8d64f84ae3403775ef61cd36e3faf162c1", 54 "8963d9bbb3911aac6d30388c786756b1c423c4fbbc95d1f96ddbddf39809e43a", 55 "0422da85abc48249270b45d8de38a4cc3c02032ede1fcf0864a51092d58a2f1f", 56 "8ae5c15b0e8c7cade201fdc149831aa9b11ff626a7ffd27188886cc108ad0fa8", 57 "acd8f5a71d4aecfcb9ad00d32aa4bcf2a602939b6a9dd071bab443154184f805", 58 "a285a922125a7481600782ad69debfbcdb0316c1e97c267aff29ef50001ec045", 59 "28fd4eee78c6cd4bf78f39f8ab30c32c67c24a6223baa40e6f9c9a0e1de7cef5", 60 "c5cca0c9e6f043b288c6f1aef448ab59132dab3e453671af5d0752961f013fc7", 61 "46df99b051838cb6f8d1b73f232af516886bd8c4d0ee07af9a0a033c391380fd", 62 "c6a06a53cbaadbb432884f36155c8f3244e244881b5ee3e92e974cfa166d793f", 63 "783b90c75c63dc72e2f8d11b6f1b4de54d63825330ec76ee8db34f06b38ea211", 64 "9450038f10ca2c097a8013e5121b36b422b95b04892232f930a29292d9935611", 65 "e215e6246ed1cfdcf7310d4d8cdbe370f0d6a8371e4eb1089e2ae05c0e1bc10f", 66 "487110939ed9d64ebbc1f300adeab358bc58875faf4ca64990fbd7fe03b78f2b", 67 "824a70ea76ac81366da1d4f4ac39de851c8ac49dca456bb3f0a186ceefa269a5", 68 "ba8f34fa40945560d1006a328fe70c42e35cc3d1017e72d26864cd0d1b150f15", 69 "30a5dfcfd144997f428901ea88a43c8d176b19c79dde54cc58eea001aa3d246c", 70 "de59f7183aca39aa245ce66a05245fecfc7e2c75884184b52b27734a4a58efa2", 71 "92629e2ff5f0cb4f5f08fffe0f64492024d36f045b901efb271674b801095c5a", 72 "7184c1701569e3a4c4d2ddce691edd983b81e42e09196d332e1ae2f1e062cff4", 73 } 74 75 type TestData struct { 76 started int64 77 counter [NumNodes]int 78 mutex sync.RWMutex 79 } 80 81 type TestNode struct { 82 shh *Whisper 83 id *ecdsa.PrivateKey 84 server *p2p.Server 85 filerID string 86 } 87 88 const NumNodes = 8 // must not exceed the number of keys (32) 89 90 var result TestData 91 var nodes [NumNodes]*TestNode 92 var sharedKey = hexutil.MustDecode("0x03ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31") 93 var wrongKey = hexutil.MustDecode("0xf91156714d7ec88d3edc1c652c2181dbb3044e8771c683f3b30d33c12b986b11") 94 var sharedTopic = TopicType{0xF, 0x1, 0x2, 0} 95 var wrongTopic = TopicType{0, 0, 0, 0} 96 var expectedMessage = []byte("per aspera ad astra") 97 var unexpectedMessage = []byte("per rectum ad astra") 98 var masterBloomFilter []byte 99 var masterPow = 0.00000001 100 var round = 1 101 var debugMode = false 102 var prevTime time.Time 103 var cntPrev int 104 105 func TestSimulation(t *testing.T) { 106 // create a chain of whisper nodes, 107 // installs the filters with shared (predefined) parameters 108 initialize(t) 109 110 // each node sends one random (not decryptable) message 111 for i := 0; i < NumNodes; i++ { 112 sendMsg(t, false, i) 113 } 114 115 // node #0 sends one expected (decryptable) message 116 sendMsg(t, true, 0) 117 118 // check if each node have received and decrypted exactly one message 119 checkPropagation(t, true) 120 121 // check if Status message was correctly decoded 122 checkBloomFilterExchange(t) 123 checkPowExchange(t) 124 125 // send new pow and bloom exchange messages 126 resetParams(t) 127 128 // node #1 sends one expected (decryptable) message 129 sendMsg(t, true, 1) 130 131 // check if each node (except node #0) have received and decrypted exactly one message 132 checkPropagation(t, false) 133 134 // check if corresponding protocol-level messages were correctly decoded 135 checkPowExchangeForNodeZero(t) 136 checkBloomFilterExchange(t) 137 138 stopServers() 139 } 140 141 func resetParams(t *testing.T) { 142 // change pow only for node zero 143 masterPow = 7777777.0 144 nodes[0].shh.SetMinimumPoW(masterPow) 145 146 // change bloom for all nodes 147 masterBloomFilter = TopicToBloom(sharedTopic) 148 for i := 0; i < NumNodes; i++ { 149 nodes[i].shh.SetBloomFilter(masterBloomFilter) 150 } 151 152 round++ 153 } 154 155 func initBloom(t *testing.T) { 156 masterBloomFilter = make([]byte, BloomFilterSize) 157 _, err := mrand.Read(masterBloomFilter) 158 if err != nil { 159 t.Fatalf("rand failed: %s.", err) 160 } 161 162 msgBloom := TopicToBloom(sharedTopic) 163 masterBloomFilter = addBloom(masterBloomFilter, msgBloom) 164 for i := 0; i < 32; i++ { 165 masterBloomFilter[i] = 0xFF 166 } 167 168 if !BloomFilterMatch(masterBloomFilter, msgBloom) { 169 t.Fatalf("bloom mismatch on initBloom.") 170 } 171 } 172 173 func initialize(t *testing.T) { 174 initBloom(t) 175 176 var err error 177 178 for i := 0; i < NumNodes; i++ { 179 var node TestNode 180 b := make([]byte, BloomFilterSize) 181 copy(b, masterBloomFilter) 182 node.shh = New(&DefaultConfig) 183 node.shh.SetMinimumPoW(masterPow) 184 node.shh.SetBloomFilter(b) 185 if !bytes.Equal(node.shh.BloomFilter(), masterBloomFilter) { 186 t.Fatalf("bloom mismatch on init.") 187 } 188 node.shh.Start(nil) 189 topics := make([]TopicType, 0) 190 topics = append(topics, sharedTopic) 191 f := Filter{KeySym: sharedKey} 192 f.Topics = [][]byte{topics[0][:]} 193 node.filerID, err = node.shh.Subscribe(&f) 194 if err != nil { 195 t.Fatalf("failed to install the filter: %s.", err) 196 } 197 node.id, err = crypto.HexToECDSA(keys[i]) 198 if err != nil { 199 t.Fatalf("failed convert the key: %s.", keys[i]) 200 } 201 name := common.MakeName("whisper-go", "2.0") 202 203 node.server = &p2p.Server{ 204 Config: p2p.Config{ 205 PrivateKey: node.id, 206 MaxPeers: NumNodes/2 + 1, 207 Name: name, 208 Protocols: node.shh.Protocols(), 209 ListenAddr: "127.0.0.1:0", 210 NAT: nat.Any(), 211 }, 212 } 213 214 go startServer(t, node.server) 215 216 nodes[i] = &node 217 } 218 219 waitForServersToStart(t) 220 221 for i := 0; i < NumNodes; i++ { 222 for j := 0; j < i; j++ { 223 peerNodeId := nodes[j].id 224 address, _ := net.ResolveTCPAddr("tcp", nodes[j].server.ListenAddr) 225 peerPort := uint16(address.Port) 226 peerNode := discover.PubkeyID(&peerNodeId.PublicKey) 227 peer := discover.NewNode(peerNode, address.IP, peerPort, peerPort) 228 nodes[i].server.AddPeer(peer) 229 } 230 } 231 } 232 233 func startServer(t *testing.T, s *p2p.Server) { 234 err := s.Start() 235 if err != nil { 236 t.Fatalf("failed to start the fisrt server.") 237 } 238 239 atomic.AddInt64(&result.started, 1) 240 } 241 242 func stopServers() { 243 for i := 0; i < NumNodes; i++ { 244 n := nodes[i] 245 if n != nil { 246 n.shh.Unsubscribe(n.filerID) 247 n.shh.Stop() 248 n.server.Stop() 249 } 250 } 251 } 252 253 func checkPropagation(t *testing.T, includingNodeZero bool) { 254 if t.Failed() { 255 return 256 } 257 258 prevTime = time.Now() 259 // (cycle * iterations) should not exceed 50 seconds, since TTL=50 260 const cycle = 200 // time in milliseconds 261 const iterations = 250 262 263 first := 0 264 if !includingNodeZero { 265 first = 1 266 } 267 268 for j := 0; j < iterations; j++ { 269 for i := first; i < NumNodes; i++ { 270 f := nodes[i].shh.GetFilter(nodes[i].filerID) 271 if f == nil { 272 t.Fatalf("failed to get filterId %s from node %d, round %d.", nodes[i].filerID, i, round) 273 } 274 275 mail := f.Retrieve() 276 validateMail(t, i, mail) 277 278 if isTestComplete() { 279 checkTestStatus() 280 return 281 } 282 } 283 284 checkTestStatus() 285 time.Sleep(cycle * time.Millisecond) 286 } 287 288 if !includingNodeZero { 289 f := nodes[0].shh.GetFilter(nodes[0].filerID) 290 if f != nil { 291 t.Fatalf("node zero received a message with low PoW.") 292 } 293 } 294 295 t.Fatalf("Test was not complete (%d round): timeout %d seconds. nodes=%v", round, iterations*cycle/1000, nodes) 296 } 297 298 func validateMail(t *testing.T, index int, mail []*ReceivedMessage) { 299 var cnt int 300 for _, m := range mail { 301 if bytes.Equal(m.Payload, expectedMessage) { 302 cnt++ 303 } 304 } 305 306 if cnt == 0 { 307 // no messages received yet: nothing is wrong 308 return 309 } 310 if cnt > 1 { 311 t.Fatalf("node %d received %d.", index, cnt) 312 } 313 314 if cnt == 1 { 315 result.mutex.Lock() 316 defer result.mutex.Unlock() 317 result.counter[index] += cnt 318 if result.counter[index] > 1 { 319 t.Fatalf("node %d accumulated %d.", index, result.counter[index]) 320 } 321 } 322 } 323 324 func checkTestStatus() { 325 var cnt int 326 var arr [NumNodes]int 327 328 for i := 0; i < NumNodes; i++ { 329 arr[i] = nodes[i].server.PeerCount() 330 envelopes := nodes[i].shh.Envelopes() 331 if len(envelopes) >= NumNodes { 332 cnt++ 333 } 334 } 335 336 if debugMode { 337 if cntPrev != cnt { 338 fmt.Printf(" %v \t number of nodes that have received all msgs: %d, number of peers per node: %v \n", 339 time.Since(prevTime), cnt, arr) 340 prevTime = time.Now() 341 cntPrev = cnt 342 } 343 } 344 } 345 346 func isTestComplete() bool { 347 result.mutex.RLock() 348 defer result.mutex.RUnlock() 349 350 for i := 0; i < NumNodes; i++ { 351 if result.counter[i] < 1 { 352 return false 353 } 354 } 355 356 for i := 0; i < NumNodes; i++ { 357 envelopes := nodes[i].shh.Envelopes() 358 if len(envelopes) < NumNodes+1 { 359 return false 360 } 361 } 362 363 return true 364 } 365 366 func sendMsg(t *testing.T, expected bool, id int) { 367 if t.Failed() { 368 return 369 } 370 371 opt := MessageParams{KeySym: sharedKey, Topic: sharedTopic, Payload: expectedMessage, PoW: 0.00000001, WorkTime: 1} 372 if !expected { 373 opt.KeySym = wrongKey 374 opt.Topic = wrongTopic 375 opt.Payload = unexpectedMessage 376 opt.Payload[0] = byte(id) 377 } 378 379 msg, err := NewSentMessage(&opt) 380 if err != nil { 381 t.Fatalf("failed to create new message with seed %d: %s.", seed, err) 382 } 383 envelope, err := msg.Wrap(&opt) 384 if err != nil { 385 t.Fatalf("failed to seal message: %s", err) 386 } 387 388 err = nodes[id].shh.Send(envelope) 389 if err != nil { 390 t.Fatalf("failed to send message: %s", err) 391 } 392 } 393 394 func TestPeerBasic(t *testing.T) { 395 InitSingleTest() 396 397 params, err := generateMessageParams() 398 if err != nil { 399 t.Fatalf("failed generateMessageParams with seed %d.", seed) 400 } 401 402 params.PoW = 0.001 403 msg, err := NewSentMessage(params) 404 if err != nil { 405 t.Fatalf("failed to create new message with seed %d: %s.", seed, err) 406 } 407 env, err := msg.Wrap(params) 408 if err != nil { 409 t.Fatalf("failed Wrap with seed %d.", seed) 410 } 411 412 p := newPeer(nil, nil, nil) 413 p.mark(env) 414 if !p.marked(env) { 415 t.Fatalf("failed mark with seed %d.", seed) 416 } 417 } 418 419 func checkPowExchangeForNodeZero(t *testing.T) { 420 const iterations = 200 421 for j := 0; j < iterations; j++ { 422 lastCycle := (j == iterations-1) 423 ok := checkPowExchangeForNodeZeroOnce(t, lastCycle) 424 if ok { 425 break 426 } 427 time.Sleep(50 * time.Millisecond) 428 } 429 } 430 431 func checkPowExchangeForNodeZeroOnce(t *testing.T, mustPass bool) bool { 432 cnt := 0 433 for i, node := range nodes { 434 for peer := range node.shh.peers { 435 if peer.peer.ID() == discover.PubkeyID(&nodes[0].id.PublicKey) { 436 cnt++ 437 if peer.powRequirement != masterPow { 438 if mustPass { 439 t.Fatalf("node %d: failed to set the new pow requirement for node zero.", i) 440 } else { 441 return false 442 } 443 } 444 } 445 } 446 } 447 if cnt == 0 { 448 t.Fatalf("looking for node zero: no matching peers found.") 449 } 450 return true 451 } 452 453 func checkPowExchange(t *testing.T) { 454 for i, node := range nodes { 455 for peer := range node.shh.peers { 456 if peer.peer.ID() != discover.PubkeyID(&nodes[0].id.PublicKey) { 457 if peer.powRequirement != masterPow { 458 t.Fatalf("node %d: failed to exchange pow requirement in round %d; expected %f, got %f", 459 i, round, masterPow, peer.powRequirement) 460 } 461 } 462 } 463 } 464 } 465 466 func checkBloomFilterExchangeOnce(t *testing.T, mustPass bool) bool { 467 for i, node := range nodes { 468 for peer := range node.shh.peers { 469 peer.bloomMu.Lock() 470 equals := bytes.Equal(peer.bloomFilter, masterBloomFilter) 471 peer.bloomMu.Unlock() 472 if !equals { 473 if mustPass { 474 t.Fatalf("node %d: failed to exchange bloom filter requirement in round %d. \n%x expected \n%x got", 475 i, round, masterBloomFilter, peer.bloomFilter) 476 } else { 477 return false 478 } 479 } 480 } 481 } 482 483 return true 484 } 485 486 func checkBloomFilterExchange(t *testing.T) { 487 const iterations = 200 488 for j := 0; j < iterations; j++ { 489 lastCycle := (j == iterations-1) 490 ok := checkBloomFilterExchangeOnce(t, lastCycle) 491 if ok { 492 break 493 } 494 time.Sleep(50 * time.Millisecond) 495 } 496 } 497 498 func waitForServersToStart(t *testing.T) { 499 const iterations = 200 500 var started int64 501 for j := 0; j < iterations; j++ { 502 time.Sleep(50 * time.Millisecond) 503 started = atomic.LoadInt64(&result.started) 504 if started == NumNodes { 505 return 506 } 507 } 508 t.Fatalf("Failed to start all the servers, running: %d", started) 509 }