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.

94 lines
2.3 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. //read the stored blockchain
  29. err := blockchain.readFromDisk()
  30. check(err)
  31. blockchain.print()
  32. //runningPeer.ID = strconv.Itoa(randInt(1, 1000)) //0 is reserved for server
  33. runningPeer.IP = config.IP
  34. runningPeer.Port = config.Port
  35. runningPeer.RESTPort = config.RESTPort
  36. runningPeer.ID = hashPeer(runningPeer)
  37. runningPeer.Role = "client"
  38. //TODO clean and reorder the following lines (43 to 62)
  39. //read flags, to know if is runned as p2p server
  40. if len(os.Args) > 1 {
  41. if os.Args[1] == "server" {
  42. color.Yellow("Running as p2p server")
  43. runningPeer.Role = "server"
  44. runningPeer.Port = config.ServerPort
  45. runningPeer.ID = hashPeer(runningPeer)
  46. //runningPeer.ID = "0"
  47. }
  48. if len(os.Args) > 3 {
  49. config.Port = os.Args[2]
  50. config.RESTPort = os.Args[3]
  51. runningPeer.Port = os.Args[2]
  52. runningPeer.RESTPort = os.Args[3]
  53. if os.Args[1] == "server" {
  54. runningPeer.Port = config.ServerPort
  55. }
  56. runningPeer.ID = hashPeer(runningPeer)
  57. }
  58. }
  59. go runRestServer()
  60. thisPeerID = runningPeer.ID
  61. outcomingPeersList.PeerID = runningPeer.ID
  62. fmt.Println(runningPeer)
  63. //outcomingPeersList.Peers = append(outcomingPeersList.Peers, runningPeer)
  64. outcomingPeersList = appendPeerIfNoExist(outcomingPeersList, runningPeer)
  65. fmt.Println(outcomingPeersList)
  66. if runningPeer.Role == "server" {
  67. go acceptPeers(runningPeer)
  68. }
  69. if runningPeer.Role == "client" {
  70. var serverPeer Peer
  71. //serverPeer.ID = "0"
  72. serverPeer.IP = config.ServerIP
  73. serverPeer.Port = config.ServerPort
  74. serverPeer.ID = hashPeer(serverPeer)
  75. serverPeer.Role = "server"
  76. go acceptPeers(runningPeer)
  77. connectToPeer(serverPeer)
  78. reconstructBlockchainFromBlock("http://"+config.IP+":"+config.ServerRESTPort, blockchain.GenesisBlock)
  79. }
  80. for running {
  81. time.Sleep(1000 * time.Millisecond)
  82. }
  83. }