display per-miner current payout in graphs
[p2pool.git] / p2pool / web.py
1 from __future__ import division
2
3 import errno
4 import json
5 import os
6 import sys
7 import time
8
9 from twisted.internet import task
10 from twisted.python import log
11 from twisted.web import resource, static
12
13 from bitcoin import data as bitcoin_data
14 from . import data as p2pool_data
15 from util import graph, math
16
17 def _atomic_read(filename):
18     try:
19         with open(filename, 'rb') as f:
20             return f.read()
21     except IOError, e:
22         if e.errno != errno.ENOENT:
23             raise
24     try:
25         with open(filename + '.new', 'rb') as f:
26             return f.read()
27     except IOError, e:
28         if e.errno != errno.ENOENT:
29             raise
30     return None
31
32 def _atomic_write(filename, data):
33     with open(filename + '.new', 'wb') as f:
34         f.write(data)
35         f.flush()
36         try:
37             os.fsync(f.fileno())
38         except:
39             pass
40     try:
41         os.rename(filename + '.new', filename)
42     except os.error: # windows can't overwrite
43         os.remove(filename)
44         os.rename(filename + '.new', filename)
45
46 def get_web_root(tracker, current_work, current_work2, get_current_txouts, datadir_path, net, get_stale_counts, my_pubkey_hash, local_rate_monitor, worker_fee, p2p_node, my_share_hashes, pseudoshare_received, share_received):
47     start_time = time.time()
48     
49     web_root = resource.Resource()
50     
51     def get_users():
52         height, last = tracker.get_height_and_last(current_work.value['best_share_hash'])
53         weights, total_weight, donation_weight = tracker.get_cumulative_weights(current_work.value['best_share_hash'], min(height, 720), 65535*2**256)
54         res = {}
55         for script in sorted(weights, key=lambda s: weights[s]):
56             res[bitcoin_data.script2_to_address(script, net.PARENT)] = weights[script]/total_weight
57         return res
58     
59     def get_current_scaled_txouts(scale, trunc=0):
60         txouts = get_current_txouts()
61         total = sum(txouts.itervalues())
62         results = dict((script, value*scale//total) for script, value in txouts.iteritems())
63         if trunc > 0:
64             total_random = 0
65             random_set = set()
66             for s in sorted(results, key=results.__getitem__):
67                 if results[s] >= trunc:
68                     break
69                 total_random += results[s]
70                 random_set.add(s)
71             if total_random:
72                 winner = math.weighted_choice((script, results[script]) for script in random_set)
73                 for script in random_set:
74                     del results[script]
75                 results[winner] = total_random
76         if sum(results.itervalues()) < int(scale):
77             results[math.weighted_choice(results.iteritems())] += int(scale) - sum(results.itervalues())
78         return results
79     
80     def get_patron_sendmany(total=None, trunc='0.01'):
81         if total is None:
82             return 'need total argument. go to patron_sendmany/<TOTAL>'
83         total = int(float(total)*1e8)
84         trunc = int(float(trunc)*1e8)
85         return dict(
86             (bitcoin_data.script2_to_address(script, net.PARENT), value/1e8)
87             for script, value in get_current_scaled_txouts(total, trunc).iteritems()
88             if bitcoin_data.script2_to_address(script, net.PARENT) is not None
89         )
90     
91     def get_local_rates():
92         miner_hash_rates = {}
93         miner_dead_hash_rates = {}
94         datums, dt = local_rate_monitor.get_datums_in_last()
95         for datum in datums:
96             miner_hash_rates[datum['user']] = miner_hash_rates.get(datum['user'], 0) + datum['work']/dt
97             if datum['dead']:
98                 miner_dead_hash_rates[datum['user']] = miner_dead_hash_rates.get(datum['user'], 0) + datum['work']/dt
99         return miner_hash_rates, miner_dead_hash_rates
100     
101     def get_global_stats():
102         # averaged over last hour
103         lookbehind = 3600//net.SHARE_PERIOD
104         if tracker.get_height(current_work.value['best_share_hash']) < lookbehind:
105             return None
106         
107         nonstale_hash_rate = p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], lookbehind)
108         stale_prop = p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], lookbehind)
109         return dict(
110             pool_nonstale_hash_rate=nonstale_hash_rate,
111             pool_hash_rate=nonstale_hash_rate/(1 - stale_prop),
112             pool_stale_prop=stale_prop,
113         )
114     
115     def get_local_stats():
116         lookbehind = 3600//net.SHARE_PERIOD
117         if tracker.get_height(current_work.value['best_share_hash']) < lookbehind:
118             return None
119         
120         global_stale_prop = p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], lookbehind)
121         
122         my_unstale_count = sum(1 for share in tracker.get_chain(current_work.value['best_share_hash'], lookbehind) if share.hash in my_share_hashes)
123         my_orphan_count = sum(1 for share in tracker.get_chain(current_work.value['best_share_hash'], lookbehind) if share.hash in my_share_hashes and share.share_data['stale_info'] == 253)
124         my_doa_count = sum(1 for share in tracker.get_chain(current_work.value['best_share_hash'], lookbehind) if share.hash in my_share_hashes and share.share_data['stale_info'] == 254)
125         my_share_count = my_unstale_count + my_orphan_count + my_doa_count
126         my_stale_count = my_orphan_count + my_doa_count
127         
128         my_stale_prop = my_stale_count/my_share_count if my_share_count != 0 else None
129         
130         my_work = sum(bitcoin_data.target_to_average_attempts(share.target)
131             for share in tracker.get_chain(current_work.value['best_share_hash'], lookbehind - 1)
132             if share.hash in my_share_hashes)
133         actual_time = (tracker.shares[current_work.value['best_share_hash']].timestamp -
134             tracker.shares[tracker.get_nth_parent_hash(current_work.value['best_share_hash'], lookbehind - 1)].timestamp)
135         share_att_s = my_work / actual_time
136         
137         miner_hash_rates, miner_dead_hash_rates = get_local_rates()
138         (stale_orphan_shares, stale_doa_shares), shares, _ = get_stale_counts()
139         
140         return dict(
141             my_hash_rates_in_last_hour=dict(
142                 note="DEPRECATED",
143                 nonstale=share_att_s,
144                 rewarded=share_att_s/(1 - global_stale_prop),
145                 actual=share_att_s/(1 - my_stale_prop) if my_stale_prop is not None else 0, # 0 because we don't have any shares anyway
146             ),
147             my_share_counts_in_last_hour=dict(
148                 shares=my_share_count,
149                 unstale_shares=my_unstale_count,
150                 stale_shares=my_stale_count,
151                 orphan_stale_shares=my_orphan_count,
152                 doa_stale_shares=my_doa_count,
153             ),
154             my_stale_proportions_in_last_hour=dict(
155                 stale=my_stale_prop,
156                 orphan_stale=my_orphan_count/my_share_count if my_share_count != 0 else None,
157                 dead_stale=my_doa_count/my_share_count if my_share_count != 0 else None,
158             ),
159             miner_hash_rates=miner_hash_rates,
160             miner_dead_hash_rates=miner_dead_hash_rates,
161             efficiency_if_miner_perfect=(1 - stale_orphan_shares/shares)/(1 - global_stale_prop) if shares else None, # ignores dead shares because those are miner's fault and indicated by pseudoshare rejection
162         )
163     
164     class WebInterface(resource.Resource):
165         def __init__(self, func, mime_type='application/json', args=()):
166             resource.Resource.__init__(self)
167             self.func, self.mime_type, self.args = func, mime_type, args
168         
169         def getChild(self, child, request):
170             return WebInterface(self.func, self.mime_type, self.args + (child,))
171         
172         def render_GET(self, request):
173             request.setHeader('Content-Type', self.mime_type)
174             request.setHeader('Access-Control-Allow-Origin', '*')
175             res = self.func(*self.args)
176             return json.dumps(res) if self.mime_type == 'application/json' else res
177     
178     web_root.putChild('rate', WebInterface(lambda: p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], 720)/(1-p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], 720))))
179     web_root.putChild('difficulty', WebInterface(lambda: bitcoin_data.target_to_difficulty(tracker.shares[current_work.value['best_share_hash']].max_target)))
180     web_root.putChild('users', WebInterface(get_users))
181     web_root.putChild('fee', WebInterface(lambda: worker_fee))
182     web_root.putChild('current_payouts', WebInterface(lambda: dict((bitcoin_data.script2_to_address(script, net.PARENT), value/1e8) for script, value in get_current_txouts().iteritems())))
183     web_root.putChild('patron_sendmany', WebInterface(get_patron_sendmany, 'text/plain'))
184     web_root.putChild('global_stats', WebInterface(get_global_stats))
185     web_root.putChild('local_stats', WebInterface(get_local_stats))
186     web_root.putChild('peer_addresses', WebInterface(lambda: ' '.join(peer.transport.getPeer().host + (':' + str(peer.transport.getPeer().port) if peer.transport.getPeer().port != net.P2P_PORT else '') for peer in p2p_node.peers.itervalues()), 'text/plain'))
187     web_root.putChild('peer_versions', WebInterface(lambda: ''.join('%s:%i ' % peer.addr + peer.other_sub_version + '\n' for peer in p2p_node.peers.itervalues()), 'text/plain'))
188     web_root.putChild('payout_addr', WebInterface(lambda: bitcoin_data.pubkey_hash_to_address(my_pubkey_hash, net.PARENT)))
189     web_root.putChild('recent_blocks', WebInterface(lambda: [dict(ts=s.timestamp, hash='%064x' % s.header_hash) for s in tracker.get_chain(current_work.value['best_share_hash'], 24*60*60//net.SHARE_PERIOD) if s.pow_hash <= s.header['bits'].target]))
190     web_root.putChild('uptime', WebInterface(lambda: time.time() - start_time))
191     
192     new_root = resource.Resource()
193     web_root.putChild('web', new_root)
194     
195     stat_log = []
196     if os.path.exists(os.path.join(datadir_path, 'stats')):
197         try:
198             with open(os.path.join(datadir_path, 'stats'), 'rb') as f:
199                 stat_log = json.loads(f.read())
200         except:
201             log.err(None, 'Error loading stats:')
202     def update_stat_log():
203         while stat_log and stat_log[0]['time'] < time.time() - 24*60*60:
204             stat_log.pop(0)
205         
206         lookbehind = 3600//net.SHARE_PERIOD
207         if tracker.get_height(current_work.value['best_share_hash']) < lookbehind:
208             return None
209         
210         global_stale_prop = p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], lookbehind)
211         (stale_orphan_shares, stale_doa_shares), shares, _ = get_stale_counts()
212         miner_hash_rates, miner_dead_hash_rates = get_local_rates()
213         
214         stat_log.append(dict(
215             time=time.time(),
216             pool_hash_rate=p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], lookbehind)/(1-global_stale_prop),
217             pool_stale_prop=global_stale_prop,
218             local_hash_rates=miner_hash_rates,
219             local_dead_hash_rates=miner_dead_hash_rates,
220             shares=shares,
221             stale_shares=stale_orphan_shares + stale_doa_shares,
222             stale_shares_breakdown=dict(orphan=stale_orphan_shares, doa=stale_doa_shares),
223             current_payout=get_current_txouts().get(bitcoin_data.pubkey_hash_to_script2(my_pubkey_hash), 0)*1e-8,
224             peers=dict(
225                 incoming=sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming),
226                 outgoing=sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming),
227             ),
228             attempts_to_share=bitcoin_data.target_to_average_attempts(tracker.shares[current_work.value['best_share_hash']].max_target),
229             attempts_to_block=bitcoin_data.target_to_average_attempts(current_work.value['bits'].target),
230             block_value=current_work2.value['subsidy']*1e-8,
231         ))
232         
233         with open(os.path.join(datadir_path, 'stats'), 'wb') as f:
234             f.write(json.dumps(stat_log))
235     task.LoopingCall(update_stat_log).start(5*60)
236     new_root.putChild('log', WebInterface(lambda: stat_log))
237     
238     def get_share(share_hash_str):
239         if int(share_hash_str, 16) not in tracker.shares:
240             return None
241         share = tracker.shares[int(share_hash_str, 16)]
242         
243         return dict(
244             parent='%064x' % share.previous_hash,
245             children=['%064x' % x for x in sorted(tracker.reverse_shares.get(share.hash, set()), key=lambda sh: -len(tracker.reverse_shares.get(sh, set())))], # sorted from most children to least children
246             local=dict(
247                 verified=share.hash in tracker.verified.shares,
248                 time_first_seen=start_time if share.time_seen == 0 else share.time_seen,
249                 peer_first_received_from=share.peer.addr if share.peer is not None else None,
250             ),
251             share_data=dict(
252                 timestamp=share.timestamp,
253                 target=share.target,
254                 max_target=share.max_target,
255                 payout_address=bitcoin_data.script2_to_address(share.new_script, net.PARENT),
256                 donation=share.share_data['donation']/65535,
257                 stale_info=share.share_data['stale_info'],
258                 nonce=share.share_data['nonce'],
259             ),
260             block=dict(
261                 hash='%064x' % share.header_hash,
262                 header=dict(
263                     version=share.header['version'],
264                     previous_block='%064x' % share.header['previous_block'],
265                     merkle_root='%064x' % share.header['merkle_root'],
266                     timestamp=share.header['timestamp'],
267                     target=share.header['bits'].target,
268                     nonce=share.header['nonce'],
269                 ),
270                 gentx=dict(
271                     hash='%064x' % share.gentx_hash,
272                     coinbase=share.share_data['coinbase'].ljust(2, '\x00').encode('hex'),
273                     value=share.share_data['subsidy']*1e-8,
274                 ),
275                 txn_count_range=[len(share.other_txs), len(share.other_txs)] if share.other_txs is not None else 1 if len(share.merkle_link['branch']) == 0 else [2**len(share.merkle_link['branch'])//2+1, 2**len(share.merkle_link['branch'])],
276             ),
277         )
278     new_root.putChild('share', WebInterface(lambda share_hash_str: get_share(share_hash_str)))
279     new_root.putChild('heads', WebInterface(lambda: ['%064x' % x for x in tracker.heads]))
280     new_root.putChild('verified_heads', WebInterface(lambda: ['%064x' % x for x in tracker.verified.heads]))
281     new_root.putChild('tails', WebInterface(lambda: ['%064x' % x for t in tracker.tails for x in tracker.reverse_shares.get(t, set())]))
282     new_root.putChild('verified_tails', WebInterface(lambda: ['%064x' % x for t in tracker.verified.tails for x in tracker.verified.reverse_shares.get(t, set())]))
283     new_root.putChild('best_share_hash', WebInterface(lambda: '%064x' % current_work.value['best_share_hash']))
284     
285     class Explorer(resource.Resource):
286         def render_GET(self, request):
287             return 'moved to /static/'
288         def getChild(self, child, request):
289             return self
290     new_root.putChild('explorer', Explorer())
291     
292     hd_path = os.path.join(datadir_path, 'graph_db')
293     hd_data = _atomic_read(hd_path)
294     hd_obj = {}
295     if hd_data is not None:
296         try:
297             hd_obj = json.loads(hd_data)
298         except Exception:
299             log.err(None, 'Error reading graph database:')
300     dataview_descriptions = {
301         'last_hour': graph.DataViewDescription(150, 60*60),
302         'last_day': graph.DataViewDescription(300, 60*60*24),
303         'last_week': graph.DataViewDescription(300, 60*60*24*7),
304         'last_month': graph.DataViewDescription(300, 60*60*24*30),
305         'last_year': graph.DataViewDescription(300, 60*60*24*365.25),
306     }
307     hd = graph.HistoryDatabase.from_obj({
308         'local_hash_rate': graph.DataStreamDescription(False, dataview_descriptions),
309         'local_dead_hash_rate': graph.DataStreamDescription(False, dataview_descriptions),
310         'local_share_hash_rate': graph.DataStreamDescription(False, dataview_descriptions),
311         'local_dead_share_hash_rate': graph.DataStreamDescription(False, dataview_descriptions),
312         'pool_rate': graph.DataStreamDescription(True, dataview_descriptions),
313         'pool_stale_rate': graph.DataStreamDescription(True, dataview_descriptions),
314         'current_payout': graph.DataStreamDescription(True, dataview_descriptions),
315         'current_payouts': graph.DataStreamDescription(True, dataview_descriptions, multivalues=True),
316         'incoming_peers': graph.DataStreamDescription(True, dataview_descriptions),
317         'outgoing_peers': graph.DataStreamDescription(True, dataview_descriptions),
318         'miner_hash_rates': graph.DataStreamDescription(False, dataview_descriptions, multivalues=True),
319         'miner_dead_hash_rates': graph.DataStreamDescription(False, dataview_descriptions, multivalues=True),
320     }, hd_obj)
321     task.LoopingCall(lambda: _atomic_write(hd_path, json.dumps(hd.to_obj()))).start(100)
322     @pseudoshare_received.watch
323     def _(work, dead, user):
324         t = time.time()
325         hd.datastreams['local_hash_rate'].add_datum(t, work)
326         if dead:
327             hd.datastreams['local_dead_hash_rate'].add_datum(t, work)
328         if user is not None:
329             hd.datastreams['miner_hash_rates'].add_datum(t, {user: work})
330             if dead:
331                 hd.datastreams['miner_dead_hash_rates'].add_datum(t, {user: work})
332     @share_received.watch
333     def _(work, dead):
334         t = time.time()
335         hd.datastreams['local_share_hash_rate'].add_datum(t, work)
336         if dead:
337             hd.datastreams['local_dead_share_hash_rate'].add_datum(t, work)
338     def add_point():
339         if tracker.get_height(current_work.value['best_share_hash']) < 720:
340             return
341         nonstalerate = p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], 720)
342         poolrate = nonstalerate / (1 - p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], 720))
343         t = time.time()
344         hd.datastreams['pool_rate'].add_datum(t, poolrate)
345         hd.datastreams['pool_stale_rate'].add_datum(t, poolrate - nonstalerate)
346         current_txouts = get_current_txouts()
347         hd.datastreams['current_payout'].add_datum(t, current_txouts.get(bitcoin_data.pubkey_hash_to_script2(my_pubkey_hash), 0)*1e-8)
348         miner_hash_rates, miner_dead_hash_rates = get_local_rates()
349         current_txouts_by_address = dict((bitcoin_data.script2_to_address(script, net.PARENT), amount) for script, amount in current_txouts.iteritems())
350         hd.datastreams['current_payouts'].add_datum(t, dict((user, current_txouts_by_address[user]*1e-8) for user in miner_hash_rates if user in current_txouts_by_address))
351         hd.datastreams['incoming_peers'].add_datum(t, sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming))
352         hd.datastreams['outgoing_peers'].add_datum(t, sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming))
353     task.LoopingCall(add_point).start(5)
354     new_root.putChild('graph_data', WebInterface(lambda source, view: hd.datastreams[source].dataviews[view].get_data(time.time())))
355     
356     web_root.putChild('static', static.File(os.path.join(os.path.dirname(sys.argv[0]), 'web-static')))
357     
358     return web_root