CreateP2PNetwork creates a P2PInterface implementation , gets a public IP and generates a secret key
(id []byte, ip, port string, netType int)
| 57 | |
| 58 | // CreateP2PNetwork creates a P2PInterface implementation , gets a public IP and generates a secret key |
| 59 | func CreateP2PNetwork(id []byte, ip, port string, netType int) (P2PInterface, error) { |
| 60 | suite := suites.MustFind("bn256") |
| 61 | |
| 62 | p := &server{ |
| 63 | suite: suite, |
| 64 | addIncomingC: make(chan *client), |
| 65 | removeIncomingC: make(chan []byte), |
| 66 | replying: make(chan p2pRequest), |
| 67 | calling: make(chan p2pRequest), |
| 68 | removeCallingC: make(chan []byte), |
| 69 | peersFeed: make(chan P2PMessage, 5), |
| 70 | peersEvent: make(chan discover.P2PEvent, 5), |
| 71 | subscribeMsg: make(chan *subscription), |
| 72 | unscribeMsg: make(chan string), |
| 73 | subscribeEvent: make(chan *subscription), |
| 74 | unscribeEvent: make(chan int), |
| 75 | port: port, |
| 76 | logger: log.New("module", "p2p"), |
| 77 | } |
| 78 | p.ctx, p.cancel = context.WithCancel(context.Background()) |
| 79 | p.secKey = suite.Scalar().Pick(suite.RandomStream()) |
| 80 | p.pubKey = suite.Point().Mul(p.secKey, nil) |
| 81 | p.id = id |
| 82 | |
| 83 | // If user specify a public ip from the env variable,use it as external IP. |
| 84 | if addr := net.ParseIP(ip); addr != nil { |
| 85 | p.addr = addr |
| 86 | } else { |
| 87 | ip, err := getIP() |
| 88 | if err != nil { |
| 89 | return nil, err |
| 90 | } |
| 91 | if netutil.IsLAN(ip) { |
| 92 | natdev, err := nat.DiscoverGateway() |
| 93 | if err != nil { |
| 94 | return nil, err |
| 95 | } |
| 96 | |
| 97 | externalIp, err := natdev.GetExternalAddress() |
| 98 | if err != nil { |
| 99 | fmt.Println(err) |
| 100 | return nil, err |
| 101 | } |
| 102 | if netutil.IsLAN(externalIp) { |
| 103 | return nil, errors.New("NAT IP is a local IP Address") |
| 104 | } |
| 105 | |
| 106 | portInt, err := strconv.Atoi(port) |
| 107 | if err != nil { |
| 108 | return nil, err |
| 109 | } |
| 110 | |
| 111 | if err := nat.SetMapping(p.ctx, natdev, "tcp", portInt, portInt, "DosClient"); err != nil { |
| 112 | fmt.Println(err) |
| 113 | return nil, err |
| 114 | } |
| 115 | |
| 116 | if netType == GossipDiscover { |