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