peer_test.go 13 KB

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