7 "github.com/tendermint/go-crypto"
8 cmn "github.com/tendermint/tmlibs/common"
10 cfg "github.com/bytom/config"
11 "github.com/bytom/p2p/connection"
14 //PanicOnAddPeerErr add peer error
15 var PanicOnAddPeerErr = false
17 func CreateRandomPeer(outbound bool) *Peer {
18 _, netAddr := CreateRoutableAddr()
24 ListenAddr: netAddr.DialString(),
26 mconn: &connection.MConnection{},
31 func CreateRoutableAddr() (addr string, netAddr *NetAddress) {
34 addr = cmn.Fmt("%X@%v.%v.%v.%v:46656", cmn.RandBytes(20), cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256)
35 netAddr, err = NewNetAddressString(addr)
39 if netAddr.Routable() {
46 // MakeConnectedSwitches switches connected via arbitrary net.Conn; useful for testing
47 // Returns n switches, connected according to the connect func.
48 // If connect==Connect2Switches, the switches will be fully connected.
49 // initSwitch defines how the ith switch should be initialized (ie. with what reactors).
50 // NOTE: panics if any switch fails to start.
51 func MakeConnectedSwitches(cfg *cfg.P2PConfig, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch {
52 switches := make([]*Switch, n)
53 for i := 0; i < n; i++ {
54 switches[i] = MakeSwitch(cfg, i, "testing", "123.123.123", initSwitch)
57 if err := startSwitches(switches); err != nil {
61 for i := 0; i < n; i++ {
62 for j := i; j < n; j++ {
63 connect(switches, i, j)
70 // Connect2Switches will connect switches i and j via net.Pipe()
71 // Blocks until a conection is established.
72 // NOTE: caller ensures i and j are within bounds
73 func Connect2Switches(switches []*Switch, i, j int) {
74 switchI := switches[i]
75 switchJ := switches[j]
77 doneCh := make(chan struct{})
79 err := switchI.addPeerWithConnection(c1)
80 if PanicOnAddPeerErr && err != nil {
86 err := switchJ.addPeerWithConnection(c2)
87 if PanicOnAddPeerErr && err != nil {
96 func startSwitches(switches []*Switch) error {
97 for _, s := range switches {
98 _, err := s.Start() // start switch and reactors
106 func MakeSwitch(cfg *cfg.P2PConfig, i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch {
107 privKey := crypto.GenPrivKeyEd25519()
108 // new switch, add reactors
109 // TODO: let the config be passed in?
110 s := initSwitch(i, NewSwitch(cfg, nil, nil))
111 s.SetNodeInfo(&NodeInfo{
112 PubKey: privKey.PubKey().Unwrap().(crypto.PubKeyEd25519),
113 Moniker: cmn.Fmt("switch%d", i),
116 ListenAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023),
118 s.SetNodePrivKey(privKey)