1 #!/usr/bin/env python3
2 # Copyright (c) 2013-2022 The Limenka developers
3 # Distributed under the MIT software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #
6 # Generate seeds.txt from Pieter's DNS seeder
7 #
8 9 import argparse
10 import collections
11 import ipaddress
12 from pathlib import Path
13 import random
14 import re
15 import sys
16 from typing import Union
17 18 asmap_dir = Path(__file__).parent.parent / "asmap"
19 sys.path.append(str(asmap_dir))
20 from asmap import ASMap, net_to_prefix # noqa: E402
21 22 NSEEDS=512
23 24 MAX_SEEDS_PER_ASN = {
25 'ipv4': 2,
26 'ipv6': 10,
27 }
28 29 MIN_BLOCKS = 868000
30 31 PATTERN_IPV4 = re.compile(r"^(([0-2]?\d{1,2})\.([0-2]?\d{1,2})\.([0-2]?\d{1,2})\.([0-2]?\d{1,2})):(\d{1,5})$")
32 PATTERN_IPV6 = re.compile(r"^\[([\da-f:]+)]:(\d{1,5})$", re.IGNORECASE)
33 PATTERN_ONION = re.compile(r"^([a-z2-7]{56}\.onion):(\d+)$")
34 PATTERN_I2P = re.compile(r"^([a-z2-7]{52}\.b32\.i2p):(\d{1,5})$")
35 PATTERN_AGENT = re.compile(
36 r"^/limenka:("
37 r"0\.14\.(0|1|2|3|99)"
38 r"|0\.15\.(0|1|2|99)"
39 r"|0\.16\.(0|1|2|3|99)"
40 r"|0\.17\.(0|0\.1|1|2|99)"
41 r"|0\.18\.(0|1|99)"
42 r"|0\.19\.(0|1|2|99)"
43 r"|0\.20\.(0|1|2|99)"
44 r"|0\.21\.(0|1|2|99)"
45 r"|22\.(0|1|99)\.0"
46 r"|23\.(0|1|2|99)\.0"
47 r"|24\.(0|1|2|99)\.(0|1)"
48 r"|25\.(0|1|2|99)\.0"
49 r"|26\.(0|1|2|99)\.0"
50 r"|27\.(0|1|2|99)\.0"
51 r"|28\.(0|1|99)\.0"
52 r")")
53 54 def parseline(line: str) -> Union[dict, None]:
55 """ Parses a line from `seeds_main.txt` into a dictionary of details for that line.
56 or `None`, if the line could not be parsed.
57 """
58 if line.startswith('#'):
59 # Ignore line that starts with comment
60 return None
61 sline = line.split()
62 if len(sline) < 11:
63 # line too short to be valid, skip it.
64 return None
65 # Skip bad results.
66 if int(sline[1]) == 0:
67 return None
68 m = PATTERN_IPV4.match(sline[0])
69 sortkey = None
70 ip = None
71 if m is None:
72 m = PATTERN_IPV6.match(sline[0])
73 if m is None:
74 m = PATTERN_ONION.match(sline[0])
75 if m is None:
76 m = PATTERN_I2P.match(sline[0])
77 if m is None:
78 return None
79 else:
80 net = 'i2p'
81 ipstr = sortkey = m.group(1)
82 port = int(m.group(2))
83 else:
84 net = 'onion'
85 ipstr = sortkey = m.group(1)
86 port = int(m.group(2))
87 else:
88 net = 'ipv6'
89 if m.group(1) in ['::']: # Not interested in localhost
90 return None
91 ipstr = m.group(1)
92 if ipstr.startswith("fc"): # cjdns looks like ipv6 but always begins with fc
93 net = "cjdns"
94 sortkey = ipstr # XXX parse IPv6 into number, could use name_to_ipv6 from generate-seeds
95 port = int(m.group(2))
96 else:
97 # Do IPv4 sanity check
98 ip = 0
99 for i in range(0,4):
100 if int(m.group(i+2)) < 0 or int(m.group(i+2)) > 255:
101 return None
102 ip = ip + (int(m.group(i+2)) << (8*(3-i)))
103 if ip == 0:
104 return None
105 net = 'ipv4'
106 sortkey = ip
107 ipstr = m.group(1)
108 port = int(m.group(6))
109 # Extract uptime %.
110 uptime30 = float(sline[7][:-1])
111 # Extract Unix timestamp of last success.
112 lastsuccess = int(sline[2])
113 # Extract protocol version.
114 version = int(sline[10])
115 # Extract user agent.
116 agent = sline[11][1:-1]
117 # Extract service flags.
118 service = int(sline[9], 16)
119 # Extract blocks.
120 blocks = int(sline[8])
121 # Construct result.
122 return {
123 'net': net,
124 'ip': ipstr,
125 'port': port,
126 'ipnum': ip,
127 'uptime': uptime30,
128 'lastsuccess': lastsuccess,
129 'version': version,
130 'agent': agent,
131 'service': service,
132 'blocks': blocks,
133 'sortkey': sortkey,
134 }
135 136 def dedup(ips: list[dict]) -> list[dict]:
137 """ Remove duplicates from `ips` where multiple ips share address and port. """
138 d = {}
139 for ip in ips:
140 d[ip['ip'],ip['port']] = ip
141 return list(d.values())
142 143 def filtermultiport(ips: list[dict]) -> list[dict]:
144 """ Filter out hosts with more nodes per IP"""
145 hist = collections.defaultdict(list)
146 for ip in ips:
147 hist[ip['sortkey']].append(ip)
148 return [value[0] for (key,value) in list(hist.items()) if len(value)==1]
149 150 # Based on Greg Maxwell's seed_filter.py
151 def filterbyasn(asmap: ASMap, ips: list[dict], max_per_asn: dict, max_per_net: int) -> list[dict]:
152 """ Prunes `ips` by
153 (a) trimming ips to have at most `max_per_net` ips from each net (e.g. ipv4, ipv6); and
154 (b) trimming ips to have at most `max_per_asn` ips from each asn in each net.
155 """
156 # Sift out ips by type
157 ips_ipv46 = [ip for ip in ips if ip['net'] in ['ipv4', 'ipv6']]
158 ips_onion = [ip for ip in ips if ip['net'] == 'onion']
159 ips_i2p = [ip for ip in ips if ip['net'] == 'i2p']
160 ips_cjdns = [ip for ip in ips if ip["net"] == "cjdns"]
161 162 # Filter IPv46 by ASN, and limit to max_per_net per network
163 result = []
164 net_count: dict[str, int] = collections.defaultdict(int)
165 asn_count: dict[int, int] = collections.defaultdict(int)
166 167 for i, ip in enumerate(ips_ipv46):
168 if net_count[ip['net']] == max_per_net:
169 # do not add this ip as we already too many
170 # ips from this network
171 continue
172 asn = asmap.lookup(net_to_prefix(ipaddress.ip_network(ip['ip'])))
173 if not asn or asn_count[ip['net'], asn] == max_per_asn[ip['net']]:
174 # do not add this ip as we already have too many
175 # ips from this ASN on this network
176 continue
177 asn_count[ip['net'], asn] += 1
178 net_count[ip['net']] += 1
179 ip['asn'] = asn
180 result.append(ip)
181 182 # Add back Onions (up to max_per_net)
183 result.extend(ips_onion[0:max_per_net])
184 result.extend(ips_i2p[0:max_per_net])
185 result.extend(ips_cjdns[0:max_per_net])
186 return result
187 188 def ip_stats(ips: list[dict]) -> str:
189 """ Format and return pretty string from `ips`. """
190 hist: dict[str, int] = collections.defaultdict(int)
191 for ip in ips:
192 if ip is not None:
193 hist[ip['net']] += 1
194 195 return f"{hist['ipv4']:6d} {hist['ipv6']:6d} {hist['onion']:6d} {hist['i2p']:6d} {hist['cjdns']:6d}"
196 197 def parse_args():
198 argparser = argparse.ArgumentParser(description='Generate a list of limenka node seed ip addresses.')
199 argparser.add_argument("-a","--asmap", help='the location of the asmap asn database file (required)', required=True)
200 argparser.add_argument("-s","--seeds", help='the location of the DNS seeds file (required)', required=True)
201 argparser.add_argument("-m", "--minblocks", help="The minimum number of blocks each node must have", default=MIN_BLOCKS, type=int)
202 return argparser.parse_args()
203 204 def main():
205 args = parse_args()
206 207 print(f'Loading asmap database "{args.asmap}"…', end='', file=sys.stderr, flush=True)
208 with open(args.asmap, 'rb') as f:
209 asmap = ASMap.from_binary(f.read())
210 print('Done.', file=sys.stderr)
211 212 print('Loading and parsing DNS seeds…', end='', file=sys.stderr, flush=True)
213 with open(args.seeds, 'r', encoding='utf8') as f:
214 lines = f.readlines()
215 ips = [parseline(line) for line in lines]
216 random.shuffle(ips)
217 print('Done.', file=sys.stderr)
218 219 print('\x1b[7m IPv4 IPv6 Onion I2P CJDNS Pass \x1b[0m', file=sys.stderr)
220 print(f'{ip_stats(ips):s} Initial', file=sys.stderr)
221 # Skip entries with invalid address.
222 ips = [ip for ip in ips if ip is not None]
223 print(f'{ip_stats(ips):s} Skip entries with invalid address', file=sys.stderr)
224 # Skip duplicates (in case multiple seeds files were concatenated)
225 ips = dedup(ips)
226 print(f'{ip_stats(ips):s} After removing duplicates', file=sys.stderr)
227 # Enforce minimal number of blocks.
228 ips = [ip for ip in ips if ip['blocks'] >= args.minblocks]
229 print(f'{ip_stats(ips):s} Enforce minimal number of blocks', file=sys.stderr)
230 # Require service bit 1.
231 ips = [ip for ip in ips if (ip['service'] & 1) == 1]
232 print(f'{ip_stats(ips):s} Require service bit 1', file=sys.stderr)
233 # Require at least 50% 30-day uptime for clearnet, onion and i2p; 10% for cjdns
234 req_uptime = {
235 'ipv4': 50,
236 'ipv6': 50,
237 'onion': 50,
238 'i2p': 50,
239 'cjdns': 10,
240 }
241 ips = [ip for ip in ips if ip['uptime'] > req_uptime[ip['net']]]
242 print(f'{ip_stats(ips):s} Require minimum uptime', file=sys.stderr)
243 # Require a known and recent user agent.
244 ips = [ip for ip in ips if PATTERN_AGENT.match(ip['agent'])]
245 print(f'{ip_stats(ips):s} Require a known and recent user agent', file=sys.stderr)
246 # Sort by availability (and use last success as tie breaker)
247 ips.sort(key=lambda x: (x['uptime'], x['lastsuccess'], x['ip']), reverse=True)
248 # Filter out hosts with multiple limenka ports, these are likely abusive
249 ips = filtermultiport(ips)
250 print(f'{ip_stats(ips):s} Filter out hosts with multiple limenka ports', file=sys.stderr)
251 # Look up ASNs and limit results, both per ASN and globally.
252 ips = filterbyasn(asmap, ips, MAX_SEEDS_PER_ASN, NSEEDS)
253 print(f'{ip_stats(ips):s} Look up ASNs and limit results per ASN and per net', file=sys.stderr)
254 # Sort the results by IP address (for deterministic output).
255 ips.sort(key=lambda x: (x['net'], x['sortkey']))
256 for ip in ips:
257 if ip['net'] == 'ipv6' or ip["net"] == "cjdns":
258 print(f"[{ip['ip']}]:{ip['port']}", end="")
259 else:
260 print(f"{ip['ip']}:{ip['port']}", end="")
261 if 'asn' in ip:
262 print(f" # AS{ip['asn']}", end="")
263 print()
264 265 if __name__ == '__main__':
266 main()
267