network_tools.py 5.61 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
79
80
81
82
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()
        ep["domain"], ep["port"] = G1_TEST_DEFAULT_ENDPOINT if cli_args.contains_switches("gtest") else G1_DEFAULT_ENDPOINT
        self.ep = ep


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

Moul's avatar
Moul committed
103

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

Moul's avatar
Moul committed
114

Moul's avatar
Moul committed
115
def check_ip(address):
Moul's avatar
Moul committed
116
    try:
117
        return ip_address(address).version
Moul's avatar
Moul committed
118
119
120
    except:
        return 0

Moul's avatar
Moul committed
121

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

Moul's avatar
Moul committed
134

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

Moul's avatar
Moul committed
152

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


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

182

183
184
185
class HeadBlock(object):
    __instance = None

186
    def __new__(cls):
187
188
189
190
        if HeadBlock.__instance is None:
            HeadBlock.__instance = object.__new__(cls)
        return HeadBlock.__instance

191
192
    def __init__(self):
        self.head_block = get_request("blockchain/current")