github.com/codingfuture/orig-energi3@v0.8.4/p2p/protocols/accounting_simulation_test.go (about)

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