You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

249 lines
5.7 KiB

  1. package p2p
  2. import (
  3. "fmt"
  4. "net"
  5. "time"
  6. crypto "github.com/tendermint/tendermint/crypto"
  7. "github.com/tendermint/tendermint/crypto/ed25519"
  8. cmn "github.com/tendermint/tendermint/libs/common"
  9. "github.com/tendermint/tendermint/libs/log"
  10. "github.com/tendermint/tendermint/config"
  11. "github.com/tendermint/tendermint/p2p/conn"
  12. )
  13. func AddPeerToSwitch(sw *Switch, peer Peer) {
  14. sw.peers.Add(peer)
  15. }
  16. func CreateRandomPeer(outbound bool) *peer {
  17. addr, netAddr := CreateRoutableAddr()
  18. p := &peer{
  19. peerConn: peerConn{
  20. outbound: outbound,
  21. },
  22. nodeInfo: NodeInfo{
  23. ID: netAddr.ID,
  24. ListenAddr: netAddr.DialString(),
  25. },
  26. mconn: &conn.MConnection{},
  27. }
  28. p.SetLogger(log.TestingLogger().With("peer", addr))
  29. return p
  30. }
  31. func CreateRoutableAddr() (addr string, netAddr *NetAddress) {
  32. for {
  33. var err error
  34. addr = fmt.Sprintf("%X@%v.%v.%v.%v:26656", cmn.RandBytes(20), cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256)
  35. netAddr, err = NewNetAddressString(addr)
  36. if err != nil {
  37. panic(err)
  38. }
  39. if netAddr.Routable() {
  40. break
  41. }
  42. }
  43. return
  44. }
  45. //------------------------------------------------------------------
  46. // Connects switches via arbitrary net.Conn. Used for testing.
  47. const TEST_HOST = "localhost"
  48. // MakeConnectedSwitches returns n switches, connected according to the connect func.
  49. // If connect==Connect2Switches, the switches will be fully connected.
  50. // initSwitch defines how the i'th switch should be initialized (ie. with what reactors).
  51. // NOTE: panics if any switch fails to start.
  52. func MakeConnectedSwitches(cfg *config.P2PConfig, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch {
  53. switches := make([]*Switch, n)
  54. for i := 0; i < n; i++ {
  55. switches[i] = MakeSwitch(cfg, i, TEST_HOST, "123.123.123", initSwitch)
  56. }
  57. if err := StartSwitches(switches); err != nil {
  58. panic(err)
  59. }
  60. for i := 0; i < n; i++ {
  61. for j := i + 1; j < n; j++ {
  62. connect(switches, i, j)
  63. }
  64. }
  65. return switches
  66. }
  67. // Connect2Switches will connect switches i and j via net.Pipe().
  68. // Blocks until a connection is established.
  69. // NOTE: caller ensures i and j are within bounds.
  70. func Connect2Switches(switches []*Switch, i, j int) {
  71. switchI := switches[i]
  72. switchJ := switches[j]
  73. c1, c2 := conn.NetPipe()
  74. doneCh := make(chan struct{})
  75. go func() {
  76. err := switchI.addPeerWithConnection(c1)
  77. if err != nil {
  78. panic(err)
  79. }
  80. doneCh <- struct{}{}
  81. }()
  82. go func() {
  83. err := switchJ.addPeerWithConnection(c2)
  84. if err != nil {
  85. panic(err)
  86. }
  87. doneCh <- struct{}{}
  88. }()
  89. <-doneCh
  90. <-doneCh
  91. }
  92. func (sw *Switch) addPeerWithConnection(conn net.Conn) error {
  93. pc, err := testInboundPeerConn(conn, sw.config, sw.nodeKey.PrivKey)
  94. if err != nil {
  95. if err := conn.Close(); err != nil {
  96. sw.Logger.Error("Error closing connection", "err", err)
  97. }
  98. return err
  99. }
  100. ni, err := handshake(conn, 50*time.Millisecond, sw.nodeInfo)
  101. if err != nil {
  102. if err := conn.Close(); err != nil {
  103. sw.Logger.Error("Error closing connection", "err", err)
  104. }
  105. return err
  106. }
  107. p := newPeer(
  108. pc,
  109. sw.mConfig,
  110. ni,
  111. sw.reactorsByCh,
  112. sw.chDescs,
  113. sw.StopPeerForError,
  114. )
  115. if err = sw.addPeer(p); err != nil {
  116. pc.CloseConn()
  117. return err
  118. }
  119. return nil
  120. }
  121. // StartSwitches calls sw.Start() for each given switch.
  122. // It returns the first encountered error.
  123. func StartSwitches(switches []*Switch) error {
  124. for _, s := range switches {
  125. err := s.Start() // start switch and reactors
  126. if err != nil {
  127. return err
  128. }
  129. }
  130. return nil
  131. }
  132. func MakeSwitch(
  133. cfg *config.P2PConfig,
  134. i int,
  135. network, version string,
  136. initSwitch func(int, *Switch) *Switch,
  137. opts ...SwitchOption,
  138. ) *Switch {
  139. var (
  140. nodeKey = NodeKey{
  141. PrivKey: ed25519.GenPrivKey(),
  142. }
  143. ni = NodeInfo{
  144. ID: nodeKey.ID(),
  145. Moniker: fmt.Sprintf("switch%d", i),
  146. Network: network,
  147. Version: version,
  148. ListenAddr: fmt.Sprintf("127.0.0.1:%d", cmn.RandIntn(64512)+1023),
  149. Other: NodeInfoOther{
  150. AminoVersion: "1.0",
  151. P2PVersion: "1.0",
  152. ConsensusVersion: "1.0",
  153. RPCVersion: "1.0",
  154. TxIndex: "off",
  155. RPCAddress: fmt.Sprintf("127.0.0.1:%d", cmn.RandIntn(64512)+1023),
  156. },
  157. }
  158. )
  159. addr, err := NewNetAddressStringWithOptionalID(
  160. IDAddressString(nodeKey.ID(), ni.ListenAddr),
  161. )
  162. if err != nil {
  163. panic(err)
  164. }
  165. t := NewMultiplexTransport(ni, nodeKey)
  166. if err := t.Listen(*addr); err != nil {
  167. panic(err)
  168. }
  169. // TODO: let the config be passed in?
  170. sw := initSwitch(i, NewSwitch(cfg, t, opts...))
  171. sw.SetLogger(log.TestingLogger())
  172. sw.SetNodeKey(&nodeKey)
  173. for ch := range sw.reactorsByCh {
  174. ni.Channels = append(ni.Channels, ch)
  175. }
  176. // TODO: We need to setup reactors ahead of time so the NodeInfo is properly
  177. // populated and we don't have to do those awkward overrides and setters.
  178. t.nodeInfo = ni
  179. sw.SetNodeInfo(ni)
  180. return sw
  181. }
  182. func testInboundPeerConn(
  183. conn net.Conn,
  184. config *config.P2PConfig,
  185. ourNodePrivKey crypto.PrivKey,
  186. ) (peerConn, error) {
  187. return testPeerConn(conn, config, false, false, ourNodePrivKey, nil)
  188. }
  189. func testPeerConn(
  190. rawConn net.Conn,
  191. cfg *config.P2PConfig,
  192. outbound, persistent bool,
  193. ourNodePrivKey crypto.PrivKey,
  194. originalAddr *NetAddress,
  195. ) (pc peerConn, err error) {
  196. conn := rawConn
  197. // Fuzz connection
  198. if cfg.TestFuzz {
  199. // so we have time to do peer handshakes and get set up
  200. conn = FuzzConnAfterFromConfig(conn, 10*time.Second, cfg.TestFuzzConfig)
  201. }
  202. // Encrypt connection
  203. conn, err = upgradeSecretConn(conn, cfg.HandshakeTimeout, ourNodePrivKey)
  204. if err != nil {
  205. return pc, cmn.ErrorWrap(err, "Error creating peer")
  206. }
  207. // Only the information we already have
  208. return peerConn{
  209. config: cfg,
  210. outbound: outbound,
  211. persistent: persistent,
  212. conn: conn,
  213. originalAddr: originalAddr,
  214. }, nil
  215. }