network_tools.py 5.75 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
11
CONNECTION_TIMEOUT = 10
Moul's avatar
Moul committed
12

13
def discover_peers(discover):
14
15
16
17
18
19
    """
    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.
    """
20
    endpoints = parse_endpoints(get_request("network/peers")["peers"])
Moul's avatar
Moul committed
21
22
    if discover:
        print("Discovering network")
23
    for i, endpoint in enumerate(endpoints):
Moul's avatar
Moul committed
24
25
        if discover:
            print("{0:.0f}%".format(i / len(endpoints) * 100))
26
27
        if best_node(endpoint, False) is None:
            endpoints.remove(endpoint)
Moul's avatar
Moul committed
28
        elif discover:
29
            endpoints = recursive_discovering(endpoints, endpoint)
30
    return endpoints
31

Moul's avatar
Moul committed
32

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

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

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
57
                j += 1
58
59
60
                if ep is None:
                    break
                ep["pubkey"] = rep[i]["pubkey"]
Moul's avatar
Moul committed
61
                endpoints.append(ep)
Moul's avatar
Moul committed
62
63
        i += 1
        j = 0
64
    return endpoints
Moul's avatar
Moul committed
65

Moul's avatar
Moul committed
66

67
68
69
70
71
72
73
74
75
76
77
78
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
79
80
81
82
        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
83
84
85
        self.ep = ep


Moul's avatar
Moul committed
86
87
88
89
90
91
92
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
93
94
        if check_port(sep[-1]):
            ep["port"] = sep[-1]
Moul's avatar
Moul committed
95
96
97
98
99
100
101
        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)
102
        return ep
103
    else:
104
        return None
Moul's avatar
Moul committed
105

Moul's avatar
Moul committed
106

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

Moul's avatar
Moul committed
117

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

Moul's avatar
Moul committed
124

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

Moul's avatar
Moul committed
137

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'), timeout=CONNECTION_TIMEOUT)
Tortue95's avatar
Tortue95 committed
147
148
149
    try:
        response = urllib.request.urlopen(request)
    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
188
class HeadBlock(object):
    __instance = None

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

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