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.

89 lines
2.2 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "net"
  6. "os"
  7. "time"
  8. "github.com/fatih/color"
  9. )
  10. type Peer struct {
  11. ID string `json:"id"` //in the future, this will be the peer hash
  12. IP string `json:"ip"`
  13. Port string `json:"port"`
  14. RESTPort string `json:"restport"`
  15. Role string `json:"role"` //client or server
  16. Conn net.Conn `json:"conn"`
  17. }
  18. var running bool
  19. var thisPeerID string
  20. var runningPeer Peer
  21. func main() {
  22. //initialize some vars
  23. rand.Seed(time.Now().Unix())
  24. running = true
  25. color.Blue("Starting Peer")
  26. //read configuration file
  27. readConfig("config.json")
  28. //runningPeer.ID = strconv.Itoa(randInt(1, 1000)) //0 is reserved for server
  29. runningPeer.IP = config.IP
  30. runningPeer.Port = config.Port
  31. runningPeer.RESTPort = config.RESTPort
  32. runningPeer.ID = hashPeer(runningPeer)
  33. runningPeer.Role = "client"
  34. //TODO clean and reorder the following lines (43 to 62)
  35. //read flags, to know if is runned as p2p server
  36. if len(os.Args) > 1 {
  37. if os.Args[1] == "server" {
  38. color.Yellow("Running as p2p server")
  39. runningPeer.Role = "server"
  40. runningPeer.Port = config.ServerPort
  41. runningPeer.ID = hashPeer(runningPeer)
  42. //runningPeer.ID = "0"
  43. }
  44. if len(os.Args) > 3 {
  45. config.Port = os.Args[2]
  46. config.RESTPort = os.Args[3]
  47. runningPeer.Port = os.Args[2]
  48. runningPeer.RESTPort = os.Args[3]
  49. if os.Args[1] == "server" {
  50. runningPeer.Port = config.ServerPort
  51. }
  52. runningPeer.ID = hashPeer(runningPeer)
  53. }
  54. }
  55. go runRestServer()
  56. thisPeerID = runningPeer.ID
  57. outcomingPeersList.PeerID = runningPeer.ID
  58. fmt.Println(runningPeer)
  59. //outcomingPeersList.Peers = append(outcomingPeersList.Peers, runningPeer)
  60. outcomingPeersList = appendPeerIfNoExist(outcomingPeersList, runningPeer)
  61. fmt.Println(outcomingPeersList)
  62. if runningPeer.Role == "server" {
  63. go acceptPeers(runningPeer)
  64. }
  65. if runningPeer.Role == "client" {
  66. var serverPeer Peer
  67. //serverPeer.ID = "0"
  68. serverPeer.IP = config.ServerIP
  69. serverPeer.Port = config.ServerPort
  70. serverPeer.ID = hashPeer(serverPeer)
  71. serverPeer.Role = "server"
  72. go acceptPeers(runningPeer)
  73. connectToPeer(serverPeer)
  74. reconstructBlockchainFromBlock("http://"+config.IP+":"+config.ServerRESTPort, blockchain.GenesisBlock)
  75. }
  76. for running {
  77. time.Sleep(1000 * time.Millisecond)
  78. }
  79. }