github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/p2p/protocols/accounting_simulation_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 protocols
    18  
    19  import (
    20  	"context"
    21  	"flag"
    22  	"fmt"
    23  	"math/rand"
    24  	"reflect"
    25  	"sync"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/mattn/go-colorable"
    30  
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/rpc"
    33  
    34  	"github.com/ethereum/go-ethereum/node"
    35  	"github.com/ethereum/go-ethereum/p2p"
    36  	"github.com/ethereum/go-ethereum/p2p/enode"
    37  	"github.com/ethereum/go-ethereum/p2p/simulations"
    38  	"github.com/ethereum/go-ethereum/p2p/simulations/adapters"
    39  )
    40  
    41  const (
    42  	content = "123456789"
    43  )
    44  
    45  var (
    46  	nodes    = flag.Int("nodes", 30, "number of nodes to create (default 30)")
    47  	msgs     = flag.Int("msgs", 100, "number of messages sent by node (default 100)")
    48  	loglevel = flag.Int("loglevel", 0, "verbosity of logs")
    49  	rawlog   = flag.Bool("rawlog", false, "remove terminal formatting from logs")
    50  )
    51  
    52  func init() {
    53  	flag.Parse()
    54  	log.PrintOrigins(true)
    55  	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(!*rawlog))))
    56  }
    57  
    58  //TestAccountingSimulation runs a p2p/simulations simulation
    59  //It creates a *nodes number of nodes, connects each one with each other,
    60  //then sends out a random selection of messages up to *msgs amount of messages
    61  //from the test protocol spec.
    62  //The spec has some accounted messages defined through the Prices interface.
    63  //The test does accounting for all the message exchanged, and then checks
    64  //that every node has the same balance with a peer, but with opposite signs.
    65  //Balance(AwithB) = 0 - Balance(BwithA) or Abs|Balance(AwithB)| == Abs|Balance(BwithA)|
    66  func TestAccountingSimulation(t *testing.T) {
    67  	//setup the balances objects for every node
    68  	bal := newBalances(*nodes)
    69  	//define the node.Service for this test
    70  	services := adapters.Services{
    71  		"accounting": func(ctx *adapters.ServiceContext) (node.Service, error) {
    72  			return bal.newNode(), nil
    73  		},
    74  	}
    75  	//setup the simulation
    76  	adapter := adapters.NewSimAdapter(services)
    77  	net := simulations.NewNetwork(adapter, &simulations.NetworkConfig{DefaultService: "accounting"})
    78  	defer net.Shutdown()
    79  
    80  	// we send msgs messages per node, wait for all messages to arrive
    81  	bal.wg.Add(*nodes * *msgs)
    82  	trigger := make(chan enode.ID)
    83  	go func() {
    84  		// wait for all of them to arrive
    85  		bal.wg.Wait()
    86  		// then trigger a check
    87  		// the selected node for the trigger is irrelevant,
    88  		// we just want to trigger the end of the simulation
    89  		trigger <- net.Nodes[0].ID()
    90  	}()
    91  
    92  	// create nodes and start them
    93  	for i := 0; i < *nodes; i++ {
    94  		conf := adapters.RandomNodeConfig()
    95  		bal.id2n[conf.ID] = i
    96  		if _, err := net.NewNodeWithConfig(conf); err != nil {
    97  			t.Fatal(err)
    98  		}
    99  		if err := net.Start(conf.ID); err != nil {
   100  			t.Fatal(err)
   101  		}
   102  	}
   103  	// fully connect nodes
   104  	for i, n := range net.Nodes {
   105  		for _, m := range net.Nodes[i+1:] {
   106  			if err := net.Connect(n.ID(), m.ID()); err != nil {
   107  				t.Fatal(err)
   108  			}
   109  		}
   110  	}
   111  
   112  	// empty action
   113  	action := func(ctx context.Context) error {
   114  		return nil
   115  	}
   116  	// 	check always checks out
   117  	check := func(ctx context.Context, id enode.ID) (bool, error) {
   118  		return true, nil
   119  	}
   120  
   121  	// run simulation
   122  	timeout := 30 * time.Second
   123  	ctx, cancel := context.WithTimeout(context.Background(), timeout)
   124  	defer cancel()
   125  	result := simulations.NewSimulation(net).Run(ctx, &simulations.Step{
   126  		Action:  action,
   127  		Trigger: trigger,
   128  		Expect: &simulations.Expectation{
   129  			Nodes: []enode.ID{net.Nodes[0].ID()},
   130  			Check: check,
   131  		},
   132  	})
   133  
   134  	if result.Error != nil {
   135  		t.Fatal(result.Error)
   136  	}
   137  
   138  	// check if balance matrix is symmetric
   139  	if err := bal.symmetric(); err != nil {
   140  		t.Fatal(err)
   141  	}
   142  }
   143  
   144  // matrix is a matrix of nodes and its balances
   145  // matrix is in fact a linear array of size n*n,
   146  // so the balance for any node A with B is at index
   147  // A*n + B, while the balance of node B with A is at
   148  // B*n + A
   149  // (n entries in the array will not be filled -
   150  //  the balance of a node with itself)
   151  type matrix struct {
   152  	n int     //number of nodes
   153  	m []int64 //array of balances
   154  }
   155  
   156  // create a new matrix
   157  func newMatrix(n int) *matrix {
   158  	return &matrix{
   159  		n: n,
   160  		m: make([]int64, n*n),
   161  	}
   162  }
   163  
   164  // called from the testBalance's Add accounting function: register balance change
   165  func (m *matrix) add(i, j int, v int64) error {
   166  	// index for the balance of local node i with remote nodde j is
   167  	// i * number of nodes + remote node
   168  	mi := i*m.n + j
   169  	// register that balance
   170  	m.m[mi] += v
   171  	return nil
   172  }
   173  
   174  // check that the balances are symmetric:
   175  // balance of node i with node j is the same as j with i but with inverted signs
   176  func (m *matrix) symmetric() error {
   177  	//iterate all nodes
   178  	for i := 0; i < m.n; i++ {
   179  		//iterate starting +1
   180  		for j := i + 1; j < m.n; j++ {
   181  			log.Debug("bal", "1", i, "2", j, "i,j", m.m[i*m.n+j], "j,i", m.m[j*m.n+i])
   182  			if m.m[i*m.n+j] != -m.m[j*m.n+i] {
   183  				return fmt.Errorf("value mismatch. m[%v, %v] = %v; m[%v, %v] = %v", i, j, m.m[i*m.n+j], j, i, m.m[j*m.n+i])
   184  			}
   185  		}
   186  	}
   187  	return nil
   188  }
   189  
   190  // all the balances
   191  type balances struct {
   192  	i int
   193  	*matrix
   194  	id2n map[enode.ID]int
   195  	wg   *sync.WaitGroup
   196  }
   197  
   198  func newBalances(n int) *balances {
   199  	return &balances{
   200  		matrix: newMatrix(n),
   201  		id2n:   make(map[enode.ID]int),
   202  		wg:     &sync.WaitGroup{},
   203  	}
   204  }
   205  
   206  // create a new testNode for every node created as part of the service
   207  func (b *balances) newNode() *testNode {
   208  	defer func() { b.i++ }()
   209  	return &testNode{
   210  		bal:   b,
   211  		i:     b.i,
   212  		peers: make([]*testPeer, b.n), //a node will be connected to n-1 peers
   213  	}
   214  }
   215  
   216  type testNode struct {
   217  	bal       *balances
   218  	i         int
   219  	lock      sync.Mutex
   220  	peers     []*testPeer
   221  	peerCount int
   222  }
   223  
   224  // do the accounting for the peer's test protocol
   225  // testNode implements protocols.Balance
   226  func (t *testNode) Add(a int64, p *Peer) error {
   227  	//get the index for the remote peer
   228  	remote := t.bal.id2n[p.ID()]
   229  	log.Debug("add", "local", t.i, "remote", remote, "amount", a)
   230  	return t.bal.add(t.i, remote, a)
   231  }
   232  
   233  //run the p2p protocol
   234  //for every node, represented by testNode, create a remote testPeer
   235  func (t *testNode) run(p *p2p.Peer, rw p2p.MsgReadWriter) error {
   236  	spec := createTestSpec()
   237  	//create accounting hook
   238  	spec.Hook = NewAccounting(t, &dummyPrices{})
   239  
   240  	//create a peer for this node
   241  	tp := &testPeer{NewPeer(p, rw, spec), t.i, t.bal.id2n[p.ID()], t.bal.wg}
   242  	t.lock.Lock()
   243  	t.peers[t.bal.id2n[p.ID()]] = tp
   244  	t.peerCount++
   245  	if t.peerCount == t.bal.n-1 {
   246  		//when all peer connections are established, start sending messages from this peer
   247  		go t.send()
   248  	}
   249  	t.lock.Unlock()
   250  	return tp.Run(tp.handle)
   251  }
   252  
   253  // p2p message receive handler function
   254  func (tp *testPeer) handle(ctx context.Context, msg interface{}) error {
   255  	tp.wg.Done()
   256  	log.Debug("receive", "from", tp.remote, "to", tp.local, "type", reflect.TypeOf(msg), "msg", msg)
   257  	return nil
   258  }
   259  
   260  type testPeer struct {
   261  	*Peer
   262  	local, remote int
   263  	wg            *sync.WaitGroup
   264  }
   265  
   266  func (t *testNode) send() {
   267  	log.Debug("start sending")
   268  	for i := 0; i < *msgs; i++ {
   269  		//determine randomly to which peer to send
   270  		whom := rand.Intn(t.bal.n - 1)
   271  		if whom >= t.i {
   272  			whom++
   273  		}
   274  		t.lock.Lock()
   275  		p := t.peers[whom]
   276  		t.lock.Unlock()
   277  
   278  		//determine a random message from the spec's messages to be sent
   279  		which := rand.Intn(len(p.spec.Messages))
   280  		msg := p.spec.Messages[which]
   281  		switch msg.(type) {
   282  		case *perBytesMsgReceiverPays:
   283  			msg = &perBytesMsgReceiverPays{Content: content[:rand.Intn(len(content))]}
   284  		case *perBytesMsgSenderPays:
   285  			msg = &perBytesMsgSenderPays{Content: content[:rand.Intn(len(content))]}
   286  		}
   287  		log.Debug("send", "from", t.i, "to", whom, "type", reflect.TypeOf(msg), "msg", msg)
   288  		p.Send(context.TODO(), msg)
   289  	}
   290  }
   291  
   292  // define the protocol
   293  func (t *testNode) Protocols() []p2p.Protocol {
   294  	return []p2p.Protocol{{
   295  		Length: 100,
   296  		Run:    t.run,
   297  	}}
   298  }
   299  
   300  func (t *testNode) APIs() []rpc.API {
   301  	return nil
   302  }
   303  
   304  func (t *testNode) Start(server *p2p.Server) error {
   305  	return nil
   306  }
   307  
   308  func (t *testNode) Stop() error {
   309  	return nil
   310  }