github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/whisper/whisperv6/peer_test.go (about)

     1  // Copyright 2016 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package whisperv6
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/ecdsa"
    22  	"fmt"
    23  	"net"
    24  	"sync"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/SmartMeshFoundation/Spectrum/common"
    29  	"github.com/SmartMeshFoundation/Spectrum/crypto"
    30  	"github.com/SmartMeshFoundation/Spectrum/p2p"
    31  	"github.com/SmartMeshFoundation/Spectrum/p2p/discover"
    32  	"github.com/SmartMeshFoundation/Spectrum/p2p/nat"
    33  )
    34  
    35  var keys []string = []string{
    36  	"d49dcf37238dc8a7aac57dc61b9fee68f0a97f062968978b9fafa7d1033d03a9",
    37  	"73fd6143c48e80ed3c56ea159fe7494a0b6b393a392227b422f4c3e8f1b54f98",
    38  	"119dd32adb1daa7a4c7bf77f847fb28730785aa92947edf42fdd997b54de40dc",
    39  	"deeda8709dea935bb772248a3144dea449ffcc13e8e5a1fd4ef20ce4e9c87837",
    40  	"5bd208a079633befa349441bdfdc4d85ba9bd56081525008380a63ac38a407cf",
    41  	"1d27fb4912002d58a2a42a50c97edb05c1b3dffc665dbaa42df1fe8d3d95c9b5",
    42  	"15def52800c9d6b8ca6f3066b7767a76afc7b611786c1276165fbc61636afb68",
    43  	"51be6ab4b2dc89f251ff2ace10f3c1cc65d6855f3e083f91f6ff8efdfd28b48c",
    44  	"ef1ef7441bf3c6419b162f05da6037474664f198b58db7315a6f4de52414b4a0",
    45  	"09bdf6985aabc696dc1fbeb5381aebd7a6421727343872eb2fadfc6d82486fd9",
    46  	"15d811bf2e01f99a224cdc91d0cf76cea08e8c67905c16fee9725c9be71185c4",
    47  	"2f83e45cf1baaea779789f755b7da72d8857aeebff19362dd9af31d3c9d14620",
    48  	"73f04e34ac6532b19c2aae8f8e52f38df1ac8f5cd10369f92325b9b0494b0590",
    49  	"1e2e07b69e5025537fb73770f483dc8d64f84ae3403775ef61cd36e3faf162c1",
    50  	"8963d9bbb3911aac6d30388c786756b1c423c4fbbc95d1f96ddbddf39809e43a",
    51  	"0422da85abc48249270b45d8de38a4cc3c02032ede1fcf0864a51092d58a2f1f",
    52  	"8ae5c15b0e8c7cade201fdc149831aa9b11ff626a7ffd27188886cc108ad0fa8",
    53  	"acd8f5a71d4aecfcb9ad00d32aa4bcf2a602939b6a9dd071bab443154184f805",
    54  	"a285a922125a7481600782ad69debfbcdb0316c1e97c267aff29ef50001ec045",
    55  	"28fd4eee78c6cd4bf78f39f8ab30c32c67c24a6223baa40e6f9c9a0e1de7cef5",
    56  	"c5cca0c9e6f043b288c6f1aef448ab59132dab3e453671af5d0752961f013fc7",
    57  	"46df99b051838cb6f8d1b73f232af516886bd8c4d0ee07af9a0a033c391380fd",
    58  	"c6a06a53cbaadbb432884f36155c8f3244e244881b5ee3e92e974cfa166d793f",
    59  	"783b90c75c63dc72e2f8d11b6f1b4de54d63825330ec76ee8db34f06b38ea211",
    60  	"9450038f10ca2c097a8013e5121b36b422b95b04892232f930a29292d9935611",
    61  	"e215e6246ed1cfdcf7310d4d8cdbe370f0d6a8371e4eb1089e2ae05c0e1bc10f",
    62  	"487110939ed9d64ebbc1f300adeab358bc58875faf4ca64990fbd7fe03b78f2b",
    63  	"824a70ea76ac81366da1d4f4ac39de851c8ac49dca456bb3f0a186ceefa269a5",
    64  	"ba8f34fa40945560d1006a328fe70c42e35cc3d1017e72d26864cd0d1b150f15",
    65  	"30a5dfcfd144997f428901ea88a43c8d176b19c79dde54cc58eea001aa3d246c",
    66  	"de59f7183aca39aa245ce66a05245fecfc7e2c75884184b52b27734a4a58efa2",
    67  	"92629e2ff5f0cb4f5f08fffe0f64492024d36f045b901efb271674b801095c5a",
    68  	"7184c1701569e3a4c4d2ddce691edd983b81e42e09196d332e1ae2f1e062cff4",
    69  }
    70  
    71  const NumNodes = 16 // must not exceed the number of keys (32)
    72  
    73  type TestData struct {
    74  	counter [NumNodes]int
    75  	mutex   sync.RWMutex
    76  }
    77  
    78  type TestNode struct {
    79  	shh     *Whisper
    80  	id      *ecdsa.PrivateKey
    81  	server  *p2p.Server
    82  	filerId string
    83  }
    84  
    85  var result TestData
    86  var nodes [NumNodes]*TestNode
    87  var sharedKey []byte = []byte("some arbitrary data here")
    88  var sharedTopic TopicType = TopicType{0xF, 0x1, 0x2, 0}
    89  var expectedMessage []byte = []byte("per rectum ad astra")
    90  
    91  func TestSimulation(t *testing.T) {
    92  	// create a chain of whisper nodes,
    93  	// installs the filters with shared (predefined) parameters
    94  	initialize(t)
    95  
    96  	// each node sends a number of random (undecryptable) messages
    97  	for i := 0; i < NumNodes; i++ {
    98  		sendMsg(t, false, i)
    99  	}
   100  
   101  	// node #0 sends one expected (decryptable) message
   102  	sendMsg(t, true, 0)
   103  
   104  	// check if each node have received and decrypted exactly one message
   105  	checkPropagation(t, true)
   106  
   107  	// send protocol-level messages (powRequirementCode) and check the new PoW requirement values
   108  	powReqExchange(t)
   109  
   110  	// node #1 sends one expected (decryptable) message
   111  	sendMsg(t, true, 1)
   112  
   113  	// check if each node (except node #0) have received and decrypted exactly one message
   114  	checkPropagation(t, false)
   115  
   116  	stopServers()
   117  }
   118  
   119  func initialize(t *testing.T) {
   120  	var err error
   121  	ip := net.IPv4(127, 0, 0, 1)
   122  	port0 := 30303
   123  
   124  	for i := 0; i < NumNodes; i++ {
   125  		var node TestNode
   126  		node.shh = New(&DefaultConfig)
   127  		node.shh.SetMinimumPowTest(0.00000001)
   128  		node.shh.Start(nil)
   129  		topics := make([]TopicType, 0)
   130  		topics = append(topics, sharedTopic)
   131  		f := Filter{KeySym: sharedKey}
   132  		f.Topics = [][]byte{topics[0][:]}
   133  		node.filerId, err = node.shh.Subscribe(&f)
   134  		if err != nil {
   135  			t.Fatalf("failed to install the filter: %s.", err)
   136  		}
   137  		node.id, err = crypto.HexToECDSA(keys[i])
   138  		if err != nil {
   139  			t.Fatalf("failed convert the key: %s.", keys[i])
   140  		}
   141  		port := port0 + i
   142  		addr := fmt.Sprintf(":%d", port) // e.g. ":30303"
   143  		name := common.MakeName("whisper-go", "2.0")
   144  		var peers []*discover.Node
   145  		if i > 0 {
   146  			peerNodeId := nodes[i-1].id
   147  			peerPort := uint16(port - 1)
   148  			peerNode := discover.PubkeyID(&peerNodeId.PublicKey)
   149  			peer := discover.NewNode(peerNode, ip, peerPort, peerPort)
   150  			peers = append(peers, peer)
   151  		}
   152  
   153  		node.server = &p2p.Server{
   154  			Config: p2p.Config{
   155  				PrivateKey:     node.id,
   156  				MaxPeers:       NumNodes/2 + 1,
   157  				Name:           name,
   158  				Protocols:      node.shh.Protocols(),
   159  				ListenAddr:     addr,
   160  				NAT:            nat.Any(),
   161  				BootstrapNodes: peers,
   162  				StaticNodes:    peers,
   163  				TrustedNodes:   peers,
   164  			},
   165  		}
   166  
   167  		nodes[i] = &node
   168  	}
   169  
   170  	for i := 1; i < NumNodes; i++ {
   171  		go nodes[i].server.Start()
   172  	}
   173  
   174  	// we need to wait until the first node actually starts
   175  	err = nodes[0].server.Start()
   176  	if err != nil {
   177  		t.Fatalf("failed to start the fisrt server.")
   178  	}
   179  }
   180  
   181  func stopServers() {
   182  	for i := 0; i < NumNodes; i++ {
   183  		n := nodes[i]
   184  		if n != nil {
   185  			n.shh.Unsubscribe(n.filerId)
   186  			n.shh.Stop()
   187  			n.server.Stop()
   188  		}
   189  	}
   190  }
   191  
   192  func checkPropagation(t *testing.T, includingNodeZero bool) {
   193  	if t.Failed() {
   194  		return
   195  	}
   196  
   197  	const cycle = 50
   198  	const iterations = 200
   199  
   200  	first := 0
   201  	if !includingNodeZero {
   202  		first = 1
   203  	}
   204  
   205  	for j := 0; j < iterations; j++ {
   206  		for i := first; i < NumNodes; i++ {
   207  			f := nodes[i].shh.GetFilter(nodes[i].filerId)
   208  			if f == nil {
   209  				t.Fatalf("failed to get filterId %s from node %d.", nodes[i].filerId, i)
   210  			}
   211  
   212  			mail := f.Retrieve()
   213  			if !validateMail(t, i, mail) {
   214  				return
   215  			}
   216  
   217  			if isTestComplete() {
   218  				return
   219  			}
   220  		}
   221  
   222  		time.Sleep(cycle * time.Millisecond)
   223  	}
   224  
   225  	t.Fatalf("Test was not complete: timeout %d seconds.", iterations*cycle/1000)
   226  
   227  	if !includingNodeZero {
   228  		f := nodes[0].shh.GetFilter(nodes[0].filerId)
   229  		if f != nil {
   230  			t.Fatalf("node zero received a message with low PoW.")
   231  		}
   232  	}
   233  }
   234  
   235  func validateMail(t *testing.T, index int, mail []*ReceivedMessage) bool {
   236  	var cnt int
   237  	for _, m := range mail {
   238  		if bytes.Equal(m.Payload, expectedMessage) {
   239  			cnt++
   240  		}
   241  	}
   242  
   243  	if cnt == 0 {
   244  		// no messages received yet: nothing is wrong
   245  		return true
   246  	}
   247  	if cnt > 1 {
   248  		t.Fatalf("node %d received %d.", index, cnt)
   249  		return false
   250  	}
   251  
   252  	if cnt > 0 {
   253  		result.mutex.Lock()
   254  		defer result.mutex.Unlock()
   255  		result.counter[index] += cnt
   256  		if result.counter[index] > 1 {
   257  			t.Fatalf("node %d accumulated %d.", index, result.counter[index])
   258  		}
   259  	}
   260  	return true
   261  }
   262  
   263  func isTestComplete() bool {
   264  	result.mutex.RLock()
   265  	defer result.mutex.RUnlock()
   266  
   267  	for i := 0; i < NumNodes; i++ {
   268  		if result.counter[i] < 1 {
   269  			return false
   270  		}
   271  	}
   272  
   273  	for i := 0; i < NumNodes; i++ {
   274  		envelopes := nodes[i].shh.Envelopes()
   275  		if len(envelopes) < 2 {
   276  			return false
   277  		}
   278  	}
   279  
   280  	return true
   281  }
   282  
   283  func sendMsg(t *testing.T, expected bool, id int) {
   284  	if t.Failed() {
   285  		return
   286  	}
   287  
   288  	opt := MessageParams{KeySym: sharedKey, Topic: sharedTopic, Payload: expectedMessage, PoW: 0.00000001, WorkTime: 1}
   289  	if !expected {
   290  		opt.KeySym[0]++
   291  		opt.Topic[0]++
   292  		opt.Payload = opt.Payload[1:]
   293  	}
   294  
   295  	msg, err := NewSentMessage(&opt)
   296  	if err != nil {
   297  		t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
   298  	}
   299  	envelope, err := msg.Wrap(&opt)
   300  	if err != nil {
   301  		t.Fatalf("failed to seal message: %s", err)
   302  	}
   303  
   304  	err = nodes[id].shh.Send(envelope)
   305  	if err != nil {
   306  		t.Fatalf("failed to send message: %s", err)
   307  	}
   308  }
   309  
   310  func TestPeerBasic(t *testing.T) {
   311  	InitSingleTest()
   312  
   313  	params, err := generateMessageParams()
   314  	if err != nil {
   315  		t.Fatalf("failed generateMessageParams with seed %d.", seed)
   316  	}
   317  
   318  	params.PoW = 0.001
   319  	msg, err := NewSentMessage(params)
   320  	if err != nil {
   321  		t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
   322  	}
   323  	env, err := msg.Wrap(params)
   324  	if err != nil {
   325  		t.Fatalf("failed Wrap with seed %d.", seed)
   326  	}
   327  
   328  	p := newPeer(nil, nil, nil)
   329  	p.mark(env)
   330  	if !p.marked(env) {
   331  		t.Fatalf("failed mark with seed %d.", seed)
   332  	}
   333  }
   334  
   335  func powReqExchange(t *testing.T) {
   336  	for i, node := range nodes {
   337  		for peer := range node.shh.peers {
   338  			if peer.powRequirement > 1000.0 {
   339  				t.Fatalf("node %d: one of the peers' pow requirement is too big (%f).", i, peer.powRequirement)
   340  			}
   341  		}
   342  	}
   343  
   344  	const pow float64 = 7777777.0
   345  	nodes[0].shh.SetMinimumPoW(pow)
   346  
   347  	// wait until all the messages are delivered
   348  	time.Sleep(64 * time.Millisecond)
   349  
   350  	cnt := 0
   351  	for i, node := range nodes {
   352  		for peer := range node.shh.peers {
   353  			if peer.peer.ID() == discover.PubkeyID(&nodes[0].id.PublicKey) {
   354  				cnt++
   355  				if peer.powRequirement != pow {
   356  					t.Fatalf("node %d: failed to set the new pow requirement.", i)
   357  				}
   358  			}
   359  		}
   360  	}
   361  
   362  	if cnt == 0 {
   363  		t.Fatalf("no matching peers found.")
   364  	}
   365  }