network_tools.py 5.86 KB
Newer Older
Moul's avatar
Moul committed
1
from __future__ import unicode_literals
2
3
from ipaddress import ip_address
from json import loads
Moul's avatar
Moul committed
4
5
import socket
import urllib.request
6
import logging
7
from sys import exit, stderr
8
from commandlines import Command
Moul's avatar
Moul committed
9

10
from silkaj.constants import G1_DEFAULT_ENDPOINT, G1_TEST_DEFAULT_ENDPOINT, CONNECTION_TIMEOUT
Moul's avatar
Moul committed
11

12
def discover_peers(discover):
13
14
15
16
17
18
    """
    From first node, discover his known nodes.
    Remove from know nodes if nodes are down.
    If discover option: scan all network to know all nodes.
        display percentage discovering.
    """
19
    endpoints = parse_endpoints(get_request("network/peers")["peers"])
Moul's avatar
Moul committed
20
21
    if discover:
        print("Discovering network")
22
    for i, endpoint in enumerate(endpoints):
Moul's avatar
Moul committed
23
24
        if discover:
            print("{0:.0f}%".format(i / len(endpoints) * 100))
25
26
        if best_node(endpoint, False) is None:
            endpoints.remove(endpoint)
Moul's avatar
Moul committed
27
        elif discover:
28
            endpoints = recursive_discovering(endpoints, endpoint)
29
    return endpoints
30

Moul's avatar
Moul committed
31

32
def recursive_discovering(endpoints):
33
34
35
36
    """
    Discover recursively new nodes.
    If new node found add it and try to found new node from his known nodes.
    """
37
    news = parse_endpoints(get_request("network/peers")["peers"])
38
    for new in news:
Moul's avatar
Moul committed
39
        if best_node(new, False) is not None and new not in endpoints:
40
41
            endpoints.append(new)
            recursive_discovering(endpoints, new)
42
    return endpoints
Moul's avatar
Moul committed
43

Moul's avatar
Moul committed
44
45
46
47
48
49
50
51
52
53
54
55

def parse_endpoints(rep):
    """
    endpoints[]{"domain", "ip4", "ip6", "pubkey"}
    list of dictionaries
    reps: raw endpoints
    """
    i, j, endpoints = 0, 0, []
    while (i < len(rep)):
        if (rep[i]["status"] == "UP"):
            while j < len(rep[i]["endpoints"]):
                ep = parse_endpoint(rep[i]["endpoints"][j])
Moul's avatar
Moul committed
56
                j += 1
57
58
59
                if ep is None:
                    break
                ep["pubkey"] = rep[i]["pubkey"]
Moul's avatar
Moul committed
60
                endpoints.append(ep)
Moul's avatar
Moul committed
61
62
        i += 1
        j = 0
63
    return endpoints
Moul's avatar
Moul committed
64

Moul's avatar
Moul committed
65

66
67
68
69
70
71
72
73
74
75
76
77
class EndPoint(object):
    __instance = None

    # Try to inheritate this part for all singleton classes
    def __new__(cls):
        if EndPoint.__instance is None:
            EndPoint.__instance = object.__new__(cls)
        return EndPoint.__instance

    def __init__(self):
        cli_args = Command()
        ep = dict()
Moul's avatar
Moul committed
78
79
80
81
        if cli_args.contains_switches('p'):
            ep["domain"], ep["port"] = cli_args.get_definition('p').rsplit(':', 1)
        else:
            ep["domain"], ep["port"] = G1_TEST_DEFAULT_ENDPOINT if cli_args.contains_switches("gtest") else G1_DEFAULT_ENDPOINT
82
83
        if ep["domain"].startswith('[') and ep["domain"].endswith(']'):
            ep["domain"] = ep["domain"][1:-1]
84
85
86
        self.ep = ep


Moul's avatar
Moul committed
87
88
89
90
91
92
93
def parse_endpoint(rep):
    """
    rep: raw endpoint, sep: split endpoint
    domain, ip4 or ip6 could miss on raw endpoint
    """
    ep, sep = {}, rep.split(" ")
    if sep[0] == "BASIC_MERKLED_API":
Moul's avatar
Moul committed
94
95
        if check_port(sep[-1]):
            ep["port"] = sep[-1]
Moul's avatar
Moul committed
96
97
98
99
100
101
102
        if len(sep) == 5 and check_ip(sep[1]) == 0 and check_ip(sep[2]) == 4 and check_ip(sep[3]) == 6:
            ep["domain"], ep["ip4"], ep["ip6"] = sep[1], sep[2], sep[3]
        if len(sep) == 4:
            ep = endpoint_type(sep[1], ep)
            ep = endpoint_type(sep[2], ep)
        if len(sep) == 3:
            ep = endpoint_type(sep[1], ep)
103
        return ep
104
    else:
105
        return None
Moul's avatar
Moul committed
106

Moul's avatar
Moul committed
107

Moul's avatar
Moul committed
108
109
def endpoint_type(sep, ep):
    typ = check_ip(sep)
Moul's avatar
Moul committed
110
111
112
113
114
115
    if typ == 0:
        ep["domain"] = sep
    elif typ == 4:
        ep["ip4"] = sep
    elif typ == 6:
        ep["ip6"] = sep
116
    return ep
Moul's avatar
Moul committed
117

Moul's avatar
Moul committed
118

Moul's avatar
Moul committed
119
def check_ip(address):
Moul's avatar
Moul committed
120
    try:
121
        return ip_address(address).version
Moul's avatar
Moul committed
122
123
124
    except:
        return 0

Moul's avatar
Moul committed
125

126
def get_request(path, ep=EndPoint().ep):
Moul's avatar
Moul committed
127
    address = best_node(ep, False)
Moul's avatar
Moul committed
128
129
    if address is None:
        return address
130
    url = "http://" + ep[address] + ":" + ep["port"] + "/" + path
131
132
    if ep["port"] == "443":
        url = "https://" + ep[address] + "/" + path
Moul's avatar
Moul committed
133
    request = urllib.request.Request(url)
134
    response = urllib.request.urlopen(request, timeout=CONNECTION_TIMEOUT)
Moul's avatar
Moul committed
135
    encoding = response.info().get_content_charset('utf8')
136
    return loads(response.read().decode(encoding))
Moul's avatar
Moul committed
137

Moul's avatar
Moul committed
138

139
def post_request(path, postdata, ep=EndPoint().ep):
Moul's avatar
Moul committed
140
    address = best_node(ep, False)
Moul's avatar
Moul committed
141
142
    if address is None:
        return address
Tortue95's avatar
Tortue95 committed
143
144
145
    url = "http://" + ep[address] + ":" + ep["port"] + "/" + path
    if ep["port"] == "443":
        url = "https://" + ep[address] + "/" + path
146
    request = urllib.request.Request(url, bytes(postdata, 'utf-8'))
Tortue95's avatar
Tortue95 committed
147
    try:
148
        response = urllib.request.urlopen(request, timeout=CONNECTION_TIMEOUT)
Tortue95's avatar
Tortue95 committed
149
    except urllib.error.URLError as e:
150
151
        print(e, file=stderr)
        exit(1)
Tortue95's avatar
Tortue95 committed
152
    encoding = response.info().get_content_charset('utf8')
153
    return loads(response.read().decode(encoding))
Tortue95's avatar
Tortue95 committed
154

Moul's avatar
Moul committed
155

Moul's avatar
Moul committed
156
157
def best_node(ep, main):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
158
    s.settimeout(CONNECTION_TIMEOUT)
159
    addresses, port = ("domain", "ip6", "ip4"), int(ep["port"])
Moul's avatar
Moul committed
160
161
162
163
    for address in addresses:
        if address in ep:
            try:
                s.connect((ep[address], port))
164
                s.close()
165
                return address
166
            except Exception as e:
167
                logging.debug("Connection to endpoint %s (%s) failled (%s)" % (ep, address, e))
Moul's avatar
Moul committed
168
    if main:
vincentux's avatar
vincentux committed
169
        print("Wrong node given as argument", file=stderr)
170
        exit(1)
171
    return None
Moul's avatar
Moul committed
172
173


Moul's avatar
Moul committed
174
175
176
177
def check_port(port):
    try:
        port = int(port)
    except:
178
        print("Port must be an integer", file=stderr)
179
        return False
Moul's avatar
Moul committed
180
    if (port < 0 or port > 65536):
181
        print("Wrong port number", file=stderr)
182
183
        return False
    return True
184

185

186
187
class HeadBlock(object):
    __instance = None
188

189
    def __new__(cls):
190
191
192
        if HeadBlock.__instance is None:
            HeadBlock.__instance = object.__new__(cls)
        return HeadBlock.__instance
193

194
195
    def __init__(self):
        self.head_block = get_request("blockchain/current")