github.com/cranelv/ethereum_mpc@v0.0.0-20191031014521-23aeb1415092/mpcService/testPeerServer.go (about)

     1  package mpcService
     2  
     3  import (
     4  	"github.com/ethereum/go-ethereum/p2p/discover"
     5  	"github.com/ethereum/go-ethereum/p2p"
     6  	"bytes"
     7  	"github.com/ethereum/go-ethereum/rlp"
     8  	"time"
     9  	"github.com/ethereum/go-ethereum/mpcService/protocol"
    10  	"github.com/ethereum/go-ethereum/common"
    11  	"github.com/ethereum/go-ethereum/log"
    12  )
    13  
    14  type testPeer struct {
    15  	self discover.Node
    16  	message chan protocol.PeerMessage
    17  	netWork *testP2pNetWork
    18  }
    19  func newTestPeer(selfId *discover.NodeID,network *testP2pNetWork)*testPeer{
    20  	test := &testPeer{message:make(chan protocol.PeerMessage,100),netWork:network}
    21  	test.self.ID =*selfId
    22  	return test
    23  }
    24  func (ts *testPeer) SendToPeer(to *discover.NodeID, code uint64,msg interface{}) error {
    25  	return ts.netWork.SendToPeer(&ts.self.ID,to,code,msg)
    26  }
    27  func (ts *testPeer) MessageChannel() <-chan protocol.PeerMessage{
    28  	return ts.message
    29  }
    30  func (ts *testPeer) GetPeers()[]*discover.NodeID{
    31  	return ts.netWork.GetPeers()
    32  }
    33  func (ts *testPeer) Self() *discover.Node{
    34  	return &ts.self
    35  }
    36  func (ts *testPeer) IsActivePeer(*discover.NodeID) bool {
    37  	return true
    38  }
    39  type testP2pNetWork struct {
    40  	network map[discover.NodeID]*testPeer
    41  }
    42  func (ts *testP2pNetWork) SendToPeer(from,to *discover.NodeID, code uint64,msg interface{}) error {
    43  	payload,err := rlp.EncodeToBytes(msg)
    44  	if err!= nil {
    45  		log.Error(err.Error())
    46  		return err
    47  	}
    48  	ts.network[*to].message <- protocol.PeerMessage{*from,&p2p.Msg{code,uint32(len(payload)),bytes.NewReader(payload),time.Now()}}
    49  	return nil
    50  }
    51  func (ts *testP2pNetWork) GetPeers()[]*discover.NodeID{
    52  	peers := make([]*discover.NodeID,len(ts.network))
    53  	i := 0
    54  	for nodeid,_ := range ts.network {
    55  		peers[i] = &discover.NodeID{}
    56  		*peers[i] = nodeid
    57  		i++
    58  	}
    59  	return peers
    60  }
    61  func newTestNetWork(peerNum int)*testP2pNetWork{
    62  	ts := &testP2pNetWork{make(map[discover.NodeID]*testPeer)}
    63  	nodeId := common.Hex2Bytes("8f8581b96c387d80c64b8924ec466b17d3994db98ea5601c4ccb4b0a5acead74f43b7ffde50cfcf96efd19005e3986186268d0c0865b4217d28eff61d693bc16")
    64  	for i := 0; i < peerNum; i++ {
    65  		nodeId[0] = byte(i+16)
    66  		peerId := discover.NodeID{}
    67  		copy(peerId[:],nodeId)
    68  		tsPeer := newTestPeer(&peerId,ts)
    69  		ts.network[peerId] = tsPeer
    70  	}
    71  	return ts
    72  }