-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrepresentatives.py
executable file
·273 lines (214 loc) · 8.94 KB
/
representatives.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python3
from __future__ import annotations
import copy
import re
import requests
import json
import argparse
from typing import Dict, List, Set
import peercrawler
import pynanocoin
import acctools
import constants
from common import extract_ip_and_port_from_ipv6_address
from peer import Peer
RPC_URL = "https://mynano.ninja/api/node"
class Representative:
def __init__(self):
self.weight_perc = None
self.account = None
self.endpoint = None
self.weight = None
self.node_id = None
self.protover = None
self.voting = None
def set_weight(self, weight: int) -> None:
assert isinstance(weight, int)
self.weight = weight
self.weight_perc = weight_to_percentage(weight)
def __str__(self):
friendly_str = acctools.to_friendly_name(self.account)
if friendly_str != '':
friendly_str = ' (' + friendly_str + ')'
s = ''
s += 'Account: %s%s\n' % (self.account, friendly_str)
s += ' FriendlyName: %s\n' % acctools.to_friendly_name(self.account)
s += ' Endpoint: %s\n' % self.endpoint
s += ' Node ID: %s\n' % self.node_id
s += ' Weight: %s (%s)\n' % (self.weight, self.weight_perc)
s += ' ProtoVer: %s, ' % self.protover
s += ' Voting: %s' % self.voting
return s
class Quorum:
def __init__(self):
self.online_weight = None
self.delta = None
self.online_weight_quorum_percent = None
self.online_weight_minimum = None
self.online_stake_total = None
self.peers_stake_total = None
self.trended_stake_total = None
def set_delta(self, delta: int) -> None:
self.delta = delta
self.online_weight = int(delta * (100 / self.online_weight_quorum_percent))
def __str__(self):
s = 'Quorum:\n'
s += 'Online Weight : {:,}\n'.format(self.online_weight)
s += 'Quorum Delta : {:,}\n'.format(self.delta)
s += 'Online Weight Quorum Minimum : {:,}\n'.format(self.online_weight_quorum_percent)
s += 'Online Weight Minimum : {:,}\n'.format(self.online_weight_minimum)
s += 'Online Stake Total : {:,}\n'.format(self.online_stake_total)
s += 'Peers Stake Total : {:,}\n'.format(self.peers_stake_total)
s += 'Trended Stake Total : {:,}' .format(self.trended_stake_total)
return s
def weight_to_percentage(weight: int) -> float:
return weight * 100 / constants.max_nano_supply
# return the rep object if endpoint is a rep and has at least 'weight' raw weight
# return None otherwise
def endpoint_to_rep(reps: List[Representative], endpoint: str, weight: int) -> Representative:
if isinstance(reps, list):
for rep in reps:
if endpoint == rep.endpoint:
if rep.weight >= weight:
return rep
elif isinstance(reps, dict):
for acc, rep in reps.items():
if endpoint == rep.endpoint:
if rep.weight >= weight:
return rep
else:
assert 0
def get_reps_with_weights() -> List[Representative]:
reps = []
for acc, rep in get_representatives().items():
#if isinstance(rep, str):
# print('rep is string: %s' % rep)
# continue
#print(rep)
if rep.weight > 0:
reps.append(rep)
return reps
def post(session, params, timeout=5) -> dict:
resp = session.post(RPC_URL, json=params, timeout=timeout)
return resp.json()
def rpc_confirmation_quorum(session: requests.Session, peer_details: bool = True) -> dict:
params = {
'action': 'confirmation_quorum',
'peer_details': f'{str(peer_details).lower()}',
}
result = post(session, params)
return result
def rpc_peers(session: requests.Session) -> dict:
params = {
'action': 'peers',
'peer_details': 'true',
}
result = post(session, params)
return result
def rpc_representatives(session: requests.Session) -> dict:
params = {
'action': 'representatives',
}
result = post(session, params)
return result
def get_representatives(peer_service_url: str = None) -> Dict[str, Representative]:
session = requests.Session()
quorum_reply = rpc_confirmation_quorum(session)
quorum = Quorum()
quorum.online_weight_quorum_percent = int(quorum_reply['online_weight_quorum_percent'])
quorum.online_weight_minimum = int(quorum_reply['online_weight_minimum'])
quorum.online_stake_total = int(quorum_reply['online_stake_total'])
quorum.peers_stake_total = int(quorum_reply['peers_stake_total'])
quorum.trended_stake_total = int(quorum_reply['trended_stake_total'])
quorum.set_delta(int(quorum_reply['quorum_delta']))
reps = {}
# add the static representatives first
reps_reply = rpc_representatives(session)
reps_reply = {account: int(weight) for account, weight in reps_reply['representatives'].items() if int(weight) > 0} # filter out representatives with 0 voting weight
for acc, weight in reps_reply.items():
rep = Representative()
rep.account = acc
rep.set_weight(weight)
assert acc not in reps.keys()
reps[acc] = rep
# get representatives involved in peers_stake_total
# this call also provides ip addresses for some representatives
for p in quorum_reply['peers']:
acc = p['account']
weight = int(p['weight'])
if acc in reps.keys():
rep = reps[acc]
rep.endpoint = p['ip']
if weight != rep.weight:
print('Weight Diff (%s): %s(%s%%) - %s(%s%%) = %s(%s%%)' % (acc,
weight, weight_to_percentage(weight),
rep.weight, weight_to_percentage(rep.weight),
weight - rep.weight, weight_to_percentage(weight - rep.weight)))
assert rep.weight_perc == weight_to_percentage(rep.weight)
else:
rep = Representative()
rep.account = acc
rep.endpoint = p['ip']
rep.set_weight(weight)
reps[acc] = rep
# merge in node IDs and protocol version
peers = rpc_peers(session)['peers']
for endpoint in peers.keys():
for acc, rep in reps.items():
if endpoint == rep.endpoint:
rep.node_id = peers[endpoint]['node_id']
rep.protover = peers[endpoint]['protocol_version']
# merge in voting capabilities from peercrawler
peers = peercrawler.get_peers_from_service(pynanocoin.livectx, url=peer_service_url)
for peer in peers:
if peer.peer_id:
for acc, rep in reps.items():
if rep.node_id == acctools.to_account_addr(peer.peer_id, prefix='node_'):
rep.voting = peer.is_voting
return reps
# noinspection PyUnboundLocalVariable
def get_representatives_from_service(url: str, prs_only: bool = False) -> Set[Peer]:
representatives = requests.get(url).json()
peers = set()
if prs_only is True:
quorum = requests.get(url + "/network").json()
minimum_weight = int(quorum["online_stake_total"]) * 0.001
for representative in representatives.values():
if prs_only is True and int(representative["weight"]) < minimum_weight:
continue
address = representative["endpoint"] # example: "[::ffff:94.130.238.161]:7075"
if address is None:
continue
else:
ip_address, port = extract_ip_and_port_from_ipv6_address(address)
voting = representative["voting"] is True
peers.add(Peer(ip=pynanocoin.ip_addr.from_string(ip_address), port=port, is_voting=voting))
return peers
def parse_args():
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-b', '--beta', action='store_true', default=False,
help='use beta network')
group.add_argument('-t', '--test', action='store_true', default=False,
help='use test network')
group.add_argument('-z', '--zero', action='store_true', default=False,
help='show reps with zero weight')
group.add_argument('-i', '--noip', action='store_true', default=False,
help='show reps without an ip address')
return parser.parse_args()
def main() -> None:
args = parse_args()
reps = get_representatives()
reps_list = sorted(reps.values(), reverse=False, key = lambda rep: rep.weight)
count = 0
total_percentage = 0
for rep in reps_list:
if args.noip and rep.endpoint:
continue
count += 1
total_percentage += rep.weight_perc
print(rep)
print('count = %s' % count)
print('total percentage = %s' % total_percentage)
if __name__ == "__main__":
main()