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.

85 lines
2.2 KiB

  1. package p2p
  2. import "net"
  3. import "time"
  4. import "sync/atomic"
  5. import log "github.com/sirupsen/logrus"
  6. import "github.com/deroproject/derosuite/globals"
  7. import "github.com/deroproject/derosuite/blockchain"
  8. var chain *blockchain.Blockchain // external reference to chain
  9. var Exit_Event = make(chan bool) // causes all threads to exit
  10. var Exit_In_Progress bool // marks we are doing exit
  11. var logger *log.Entry // global logger, every logger in this package is a child of this
  12. // Initialize P2P subsystem
  13. func P2P_Init(params map[string]interface{}) error {
  14. logger = globals.Logger.WithFields(log.Fields{"com": "P2P"}) // all components must use this logger
  15. chain = params["chain"].(*blockchain.Blockchain)
  16. go P2P_engine() // start outgoing engine
  17. //go P2P_Server_v1() // start accepting connections
  18. logger.Infof("P2P started")
  19. atomic.AddUint32(&globals.Subsystem_Active, 1) // increment subsystem
  20. return nil
  21. }
  22. func P2P_engine() {
  23. for {
  24. if Exit_In_Progress {
  25. return
  26. }
  27. //remote_addr := "localhost:18090"
  28. //remote_addr := "192.168.56.1:18090"
  29. //remote_addr := "76.74.170.128:18090"
  30. remote_addr := "89.38.97.110:18090"
  31. remote_ip, err := net.ResolveTCPAddr("tcp", remote_addr)
  32. if err != nil {
  33. if Exit_In_Progress {
  34. return
  35. }
  36. logger.Debugf("Resolve address failed:", err.Error())
  37. time.Sleep(2 * time.Second)
  38. continue
  39. }
  40. // since we may be connecting through socks, grab the remote ip for our purpose rightnow
  41. conn, err := globals.Dialer.Dial("tcp", remote_ip.String())
  42. if err != nil {
  43. if Exit_In_Progress {
  44. return
  45. }
  46. logger.Debugf("Dial failed err %s", err.Error())
  47. time.Sleep(2 * time.Second)
  48. continue
  49. }
  50. logger.Debugf("Connection established to %s", remote_ip)
  51. Handle_Connection(conn, remote_ip, false) // handle connection
  52. time.Sleep(4 * time.Second)
  53. }
  54. }
  55. // shutdown the p2p component
  56. func P2P_Shutdown() {
  57. Exit_In_Progress = true
  58. close(Exit_Event) // send signal to all connections to exit
  59. // TODO we must wait for connections to kill themselves
  60. time.Sleep(1 * time.Second)
  61. logger.Infof("P2P Shutdown")
  62. atomic.AddUint32(&globals.Subsystem_Active, ^uint32(0)) // this decrement 1 fom subsystem
  63. }
  64. func Connection_ShutDown(connection *Connection) {
  65. connection.Conn.Close()
  66. }