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