added per-miner graphs
[p2pool.git] / p2pool / web.py
1 from __future__ import division
2
3 import cgi
4 import errno
5 import json
6 import os
7 import sys
8 import time
9
10 from twisted.internet import reactor, task
11 from twisted.python import log
12 from twisted.web import resource, static
13
14 from bitcoin import data as bitcoin_data
15 from . import data as p2pool_data, graphs
16 from util import graph, math
17
18 def _atomic_read(filename):
19     try:
20         with open(filename, 'rb') as f:
21             return f.read()
22     except IOError, e:
23         if e.errno != errno.ENOENT:
24             raise
25     try:
26         with open(filename + '.new', 'rb') as f:
27             return f.read()
28     except IOError, e:
29         if e.errno != errno.ENOENT:
30             raise
31     return None
32
33 def _atomic_write(filename, data):
34     with open(filename + '.new', 'wb') as f:
35         f.write(data)
36         f.flush()
37         try:
38             os.fsync(f.fileno())
39         except:
40             pass
41     try:
42         os.rename(filename + '.new', filename)
43     except os.error: # windows can't overwrite
44         os.remove(filename)
45         os.rename(filename + '.new', filename)
46
47 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, recent_blocks, pseudoshare_received):
48     start_time = time.time()
49     
50     web_root = resource.Resource()
51     
52     def get_rate():
53         if tracker.get_height(current_work.value['best_share_hash']) < 720:
54             return json.dumps(None)
55         return json.dumps(p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], 720)
56             / (1 - p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], 720)))
57     
58     def get_users():
59         height, last = tracker.get_height_and_last(current_work.value['best_share_hash'])
60         weights, total_weight, donation_weight = tracker.get_cumulative_weights(current_work.value['best_share_hash'], min(height, 720), 65535*2**256, False)
61         res = {}
62         for script in sorted(weights, key=lambda s: weights[s]):
63             res[bitcoin_data.script2_to_human(script, net.PARENT)] = weights[script]/total_weight
64         return json.dumps(res)
65     
66     def get_current_scaled_txouts(scale, trunc=0):
67         txouts = get_current_txouts()
68         total = sum(txouts.itervalues())
69         results = dict((script, value*scale//total) for script, value in txouts.iteritems())
70         if trunc > 0:
71             total_random = 0
72             random_set = set()
73             for s in sorted(results, key=results.__getitem__):
74                 if results[s] >= trunc:
75                     break
76                 total_random += results[s]
77                 random_set.add(s)
78             if total_random:
79                 winner = math.weighted_choice((script, results[script]) for script in random_set)
80                 for script in random_set:
81                     del results[script]
82                 results[winner] = total_random
83         if sum(results.itervalues()) < int(scale):
84             results[math.weighted_choice(results.iteritems())] += int(scale) - sum(results.itervalues())
85         return results
86     
87     def get_current_payouts():
88         return json.dumps(dict((bitcoin_data.script2_to_human(script, net.PARENT), value/1e8) for script, value in get_current_txouts().iteritems()))
89     
90     def get_patron_sendmany(total=None, trunc='0.01'):
91         if total is None:
92             return 'need total argument. go to patron_sendmany/<TOTAL>'
93         total = int(float(total)*1e8)
94         trunc = int(float(trunc)*1e8)
95         return json.dumps(dict(
96             (bitcoin_data.script2_to_address(script, net.PARENT), value/1e8)
97             for script, value in get_current_scaled_txouts(total, trunc).iteritems()
98             if bitcoin_data.script2_to_address(script, net.PARENT) is not None
99         ))
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 json.dumps(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 = {}
138         miner_dead_hash_rates = {}
139         datums, dt = local_rate_monitor.get_datums_in_last()
140         for datum in datums:
141             miner_hash_rates[datum['user']] = miner_hash_rates.get(datum['user'], 0) + datum['work']/dt
142             if datum['dead']:
143                 miner_dead_hash_rates[datum['user']] = miner_dead_hash_rates.get(datum['user'], 0) + datum['work']/dt
144         
145         (stale_orphan_shares, stale_doa_shares), shares, _ = get_stale_counts()
146         
147         return json.dumps(dict(
148             my_hash_rates_in_last_hour=dict(
149                 note="DEPRECATED",
150                 nonstale=share_att_s,
151                 rewarded=share_att_s/(1 - global_stale_prop),
152                 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
153             ),
154             my_share_counts_in_last_hour=dict(
155                 shares=my_share_count,
156                 unstale_shares=my_unstale_count,
157                 stale_shares=my_stale_count,
158                 orphan_stale_shares=my_orphan_count,
159                 doa_stale_shares=my_doa_count,
160             ),
161             my_stale_proportions_in_last_hour=dict(
162                 stale=my_stale_prop,
163                 orphan_stale=my_orphan_count/my_share_count if my_share_count != 0 else None,
164                 dead_stale=my_doa_count/my_share_count if my_share_count != 0 else None,
165             ),
166             miner_hash_rates=miner_hash_rates,
167             miner_dead_hash_rates=miner_dead_hash_rates,
168             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
169         ))
170     
171     def get_peer_addresses():
172         return ' '.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())
173     
174     def get_uptime():
175         return json.dumps(time.time() - start_time)
176     
177     class WebInterface(resource.Resource):
178         def __init__(self, func, mime_type, args=()):
179             resource.Resource.__init__(self)
180             self.func, self.mime_type, self.args = func, mime_type, args
181         
182         def getChild(self, child, request):
183             return WebInterface(self.func, self.mime_type, self.args + (child,))
184         
185         def render_GET(self, request):
186             request.setHeader('Content-Type', self.mime_type)
187             request.setHeader('Access-Control-Allow-Origin', '*')
188             return self.func(*self.args)
189     
190     web_root.putChild('rate', WebInterface(get_rate, 'application/json'))
191     web_root.putChild('users', WebInterface(get_users, 'application/json'))
192     web_root.putChild('fee', WebInterface(lambda: json.dumps(worker_fee), 'application/json'))
193     web_root.putChild('current_payouts', WebInterface(get_current_payouts, 'application/json'))
194     web_root.putChild('patron_sendmany', WebInterface(get_patron_sendmany, 'text/plain'))
195     web_root.putChild('global_stats', WebInterface(get_global_stats, 'application/json'))
196     web_root.putChild('local_stats', WebInterface(get_local_stats, 'application/json'))
197     web_root.putChild('peer_addresses', WebInterface(get_peer_addresses, 'text/plain'))
198     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'))
199     web_root.putChild('payout_addr', WebInterface(lambda: json.dumps(bitcoin_data.pubkey_hash_to_address(my_pubkey_hash, net.PARENT)), 'application/json'))
200     web_root.putChild('recent_blocks', WebInterface(lambda: json.dumps(recent_blocks), 'application/json'))
201     web_root.putChild('uptime', WebInterface(get_uptime, 'application/json'))
202     
203     try:
204         from . import draw
205         web_root.putChild('chain_img', WebInterface(lambda: draw.get(tracker, current_work.value['best_share_hash']), 'image/png'))
206     except ImportError:
207         print "Install Pygame and PIL to enable visualizations! Visualizations disabled."
208     
209     new_root = resource.Resource()
210     web_root.putChild('web', new_root)
211     
212     stat_log = []
213     if os.path.exists(os.path.join(datadir_path, 'stats')):
214         try:
215             with open(os.path.join(datadir_path, 'stats'), 'rb') as f:
216                 stat_log = json.loads(f.read())
217         except:
218             log.err(None, 'Error loading stats:')
219     def update_stat_log():
220         while stat_log and stat_log[0]['time'] < time.time() - 24*60*60:
221             stat_log.pop(0)
222         
223         lookbehind = 3600//net.SHARE_PERIOD
224         if tracker.get_height(current_work.value['best_share_hash']) < lookbehind:
225             return None
226         
227         global_stale_prop = p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], lookbehind)
228         (stale_orphan_shares, stale_doa_shares), shares, _ = get_stale_counts()
229         
230         miner_hash_rates = {}
231         miner_dead_hash_rates = {}
232         datums, dt = local_rate_monitor.get_datums_in_last()
233         for datum in datums:
234             miner_hash_rates[datum['user']] = miner_hash_rates.get(datum['user'], 0) + datum['work']/dt
235             if datum['dead']:
236                 miner_dead_hash_rates[datum['user']] = miner_dead_hash_rates.get(datum['user'], 0) + datum['work']/dt
237         
238         stat_log.append(dict(
239             time=time.time(),
240             pool_hash_rate=p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], lookbehind)/(1-global_stale_prop),
241             pool_stale_prop=global_stale_prop,
242             local_hash_rates=miner_hash_rates,
243             local_dead_hash_rates=miner_dead_hash_rates,
244             shares=shares,
245             stale_shares=stale_orphan_shares + stale_doa_shares,
246             stale_shares_breakdown=dict(orphan=stale_orphan_shares, doa=stale_doa_shares),
247             current_payout=get_current_txouts().get(bitcoin_data.pubkey_hash_to_script2(my_pubkey_hash), 0)*1e-8,
248             peers=dict(
249                 incoming=sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming),
250                 outgoing=sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming),
251             ),
252             attempts_to_share=bitcoin_data.target_to_average_attempts(tracker.shares[current_work.value['best_share_hash']].max_target),
253             attempts_to_block=bitcoin_data.target_to_average_attempts(current_work.value['bits'].target),
254             block_value=current_work2.value['subsidy']*1e-8,
255         ))
256         
257         with open(os.path.join(datadir_path, 'stats'), 'wb') as f:
258             f.write(json.dumps(stat_log))
259     task.LoopingCall(update_stat_log).start(5*60)
260     new_root.putChild('log', WebInterface(lambda: json.dumps(stat_log), 'application/json'))
261     
262     class ShareExplorer(resource.Resource):
263         def __init__(self, share_hash):
264             self.share_hash = share_hash
265         def render_GET(self, request):
266             request.setHeader('Content-Type', 'text/html')
267             if self.share_hash not in tracker.shares:
268                 return 'share not known'
269             share = tracker.shares[self.share_hash]
270             
271             format_bits = lambda bits: '%f (bits=%#8x) Work required: %sH</p>' % (bitcoin_data.target_to_difficulty(bits.target), bits.bits, math.format(bitcoin_data.target_to_average_attempts(bits.target)))
272             
273             request.write('<h1>%s <a href="%x">%s</a></h1>' % (share.__class__.__name__, share.hash, p2pool_data.format_hash(share.hash)))
274             if share.previous_hash is not None:
275                 request.write('<p>Previous: <a href="%x">%s</a>' % (share.previous_hash, p2pool_data.format_hash(share.previous_hash)))
276             if tracker.get_height(share.hash) >= 100:
277                 jump_hash = tracker.get_nth_parent_hash(share.hash, 100)
278                 if jump_hash is not None:
279                     request.write(' (100 jump <a href="%x">%s</a>)' % (jump_hash, p2pool_data.format_hash(jump_hash)))
280             request.write('</p>')
281             request.write('<p>Next: %s</p>' % (', '.join('<a href="%x">%s</a>' % (next, p2pool_data.format_hash(next)) for next in sorted(tracker.reverse_shares.get(share.hash, set()), key=lambda sh: -len(tracker.reverse_shares.get(sh, set())))),))
282             request.write('<p>Verified: %s</p>' % (share.hash in tracker.verified.shares,))
283             request.write('<p>Time first seen: %s</p>' % (time.ctime(start_time if share.time_seen == 0 else share.time_seen),))
284             request.write('<p>Peer first received from: %s</p>' % ('%s:%i' % share.peer.addr if share.peer is not None else 'self or cache',))
285             
286             request.write('<h2>Share data</h2>')
287             request.write('<p>Timestamp: %s (%i)</p>' % (time.ctime(share.timestamp), share.timestamp))
288             request.write('<p>Difficulty: %s</p>' % (format_bits(share.share_info['bits']),))
289             request.write('<p>Minimum difficulty: %s</p>' % (format_bits(share.share_info.get('max_bits', share.share_info['bits'])),))
290             request.write('<p>Payout script: %s</p>' % (bitcoin_data.script2_to_human(share.new_script, share.net.PARENT),))
291             request.write('<p>Donation: %.2f%%</p>' % (share.share_data['donation']/65535*100,))
292             request.write('<p>Stale info: %s</p>' % ({0: 'none', 253: 'had an orphan', 254: 'had a dead'}.get(share.share_data['stale_info'], 'unknown %i' % (share.share_data['stale_info'],)),))
293             request.write('<p>Nonce: %s</p>' % (cgi.escape(repr(share.share_data['nonce'])),))
294             
295             request.write('<h2>Block header</h2>')
296             request.write('<p>Hash: <a href="%s%064x">%064x</a></p>' % (net.PARENT.BLOCK_EXPLORER_URL_PREFIX, share.header_hash, share.header_hash))
297             request.write('<p>Version: %i</p>' % (share.header['version'],))
298             request.write('<p>Previous block: <a href="%s%064x">%064x</a></p>' % (net.PARENT.BLOCK_EXPLORER_URL_PREFIX, share.header['previous_block'], share.header['previous_block']))
299             request.write('<p>Timestamp: %s (%i)</p>' % (time.ctime(share.header['timestamp']), share.header['timestamp']))
300             request.write('<p>Difficulty: %f (bits=%#8x) Work: %sH</p>' % (bitcoin_data.target_to_difficulty(share.header['bits'].target), share.header['bits'].bits, math.format(bitcoin_data.target_to_average_attempts(share.header['bits'].target))))
301             request.write('<p>Nonce: %i</p>' % (share.header['nonce'],))
302             if share.other_txs is not None:
303                 tx_count = len(share.other_txs)
304             elif len(share.merkle_link['branch']) == 0:
305                 tx_count = 1
306             else:
307                 tx_count = 'between %i and %i' % (2**len(share.merkle_link['branch'])//2+1, 2**len(share.merkle_link['branch']))
308             request.write('<p>Transactions: %s</p>' % (tx_count,))
309             coinbase = share.share_data['coinbase'].ljust(2, '\x00')
310             request.write('<p>Coinbase: %s %s</p>' % (cgi.escape(repr(coinbase)), coinbase.encode('hex')))
311             request.write('<p>Generation value: %.8f %s</p>' % (share.share_data['subsidy']*1e-8, net.PARENT.SYMBOL))
312             #request.write('<p>Generation txn: %32x</p>' % (share.gentx_hash,))
313             
314             return ''
315     class Explorer(resource.Resource):
316         def render_GET(self, request):
317             if not request.path.endswith('/'):
318                 request.redirect(request.path + '/')
319                 return ''
320             request.setHeader('Content-Type', 'text/html')
321             request.write('<h1>P2Pool share explorer</h1>')
322             
323             request.write('<h2>Verified heads</h2>')
324             request.write('<ul>')
325             for h in tracker.verified.heads:
326                 request.write('<li><a href="%x">%s%s</a></li>' % (h, p2pool_data.format_hash(h), ' BEST' if h == current_work.value['best_share_hash'] else ''))
327             request.write('</ul>')
328             
329             request.write('<h2>Verified tails</h2>')
330             request.write('<ul>')
331             for tail in tracker.verified.tails:
332                 for h in tracker.reverse_shares.get(tail, set()):
333                     request.write('<li><a href="%x">%s%s</a></li>' % (h, p2pool_data.format_hash(h), ' BEST' if h == current_work.value['best_share_hash'] else ''))
334             request.write('</ul>')
335             
336             request.write('<h2>Heads</h2>')
337             request.write('<ul>')
338             for h in tracker.heads:
339                 request.write('<li><a href="%x">%s%s</a></li>' % (h, p2pool_data.format_hash(h), ' BEST' if h == current_work.value['best_share_hash'] else ''))
340             request.write('</ul>')
341             
342             request.write('<h2>Tails</h2>')
343             request.write('<ul>')
344             for tail in tracker.tails:
345                 for h in tracker.reverse_shares.get(tail, set()):
346                     request.write('<li><a href="%x">%s%s</a></li>' % (h, p2pool_data.format_hash(h), ' BEST' if h == current_work.value['best_share_hash'] else ''))
347             request.write('</ul>')
348             
349             return ''
350         def getChild(self, child, request):
351             if not child:
352                 return self
353             return ShareExplorer(int(child, 16))
354     new_root.putChild('explorer', Explorer())
355     
356     grapher = graphs.Grapher(os.path.join(datadir_path, 'rrd'))
357     web_root.putChild('graphs', grapher.get_resource())
358     def add_point():
359         if tracker.get_height(current_work.value['best_share_hash']) < 720:
360             return
361         nonstalerate = p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], 720)
362         poolrate = nonstalerate / (1 - p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], 720))
363         grapher.add_poolrate_point(poolrate, poolrate - nonstalerate)
364     task.LoopingCall(add_point).start(100)
365     @pseudoshare_received.watch
366     def _(work, dead, user):
367         reactor.callLater(1, grapher.add_localrate_point, work, dead)
368         if user is not None:
369             reactor.callLater(1, grapher.add_localminer_point, user, work, dead)
370     
371     hd_path = os.path.join(datadir_path, 'graph_db')
372     hd_data = _atomic_read(hd_path)
373     hd_obj = {}
374     if hd_data is not None:
375         try:
376             hd_obj = json.loads(hd_data)
377         except Exception:
378             log.err(None, 'Error reading graph database:')
379     dataview_descriptions = {
380         'last_hour': graph.DataViewDescription(150, 60*60),
381         'last_day': graph.DataViewDescription(300, 60*60*24),
382         'last_week': graph.DataViewDescription(300, 60*60*24*7),
383         'last_month': graph.DataViewDescription(300, 60*60*24*30),
384         'last_year': graph.DataViewDescription(300, 60*60*24*365.25),
385     }
386     hd = graph.HistoryDatabase.from_obj({
387         'local_hash_rate': graph.DataStreamDescription(False, dataview_descriptions),
388         'local_dead_hash_rate': graph.DataStreamDescription(False, dataview_descriptions),
389         'pool_rate': graph.DataStreamDescription(True, dataview_descriptions),
390         'pool_stale_rate': graph.DataStreamDescription(True, dataview_descriptions),
391         'current_payout': graph.DataStreamDescription(True, dataview_descriptions),
392         'incoming_peers': graph.DataStreamDescription(True, dataview_descriptions),
393         'outgoing_peers': graph.DataStreamDescription(True, dataview_descriptions),
394         'miner_hash_rates': graph.DataStreamDescription(False, dataview_descriptions, {}, math.add_dicts, math.mult_dict),
395         'miner_dead_hash_rates': graph.DataStreamDescription(False, dataview_descriptions, {}, math.add_dicts, math.mult_dict),
396     }, hd_obj)
397     task.LoopingCall(lambda: _atomic_write(hd_path, json.dumps(hd.to_obj()))).start(100)
398     @pseudoshare_received.watch
399     def _(work, dead, user):
400         t = time.time()
401         hd.datastreams['local_hash_rate'].add_datum(t, work)
402         if dead:
403             hd.datastreams['local_dead_hash_rate'].add_datum(t, work)
404         if user is not None:
405             hd.datastreams['miner_hash_rates'].add_datum(t, {user: work})
406             if dead:
407                 hd.datastreams['miner_dead_hash_rates'].add_datum(t, {user: work})
408     def add_point():
409         if tracker.get_height(current_work.value['best_share_hash']) < 720:
410             return
411         nonstalerate = p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], 720)
412         poolrate = nonstalerate / (1 - p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], 720))
413         t = time.time()
414         hd.datastreams['pool_rate'].add_datum(t, poolrate)
415         hd.datastreams['pool_stale_rate'].add_datum(t, poolrate - nonstalerate)
416         hd.datastreams['current_payout'].add_datum(t, get_current_txouts().get(bitcoin_data.pubkey_hash_to_script2(my_pubkey_hash), 0)*1e-8)
417         hd.datastreams['incoming_peers'].add_datum(t, sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming))
418         hd.datastreams['outgoing_peers'].add_datum(t, sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming))
419     task.LoopingCall(add_point).start(5)
420     new_root.putChild('graph_data', WebInterface(lambda source, view: json.dumps(hd.datastreams[source].dataviews[view].get_data(time.time())), 'application/json'))
421     
422     web_root.putChild('static', static.File(os.path.join(os.path.dirname(sys.argv[0]), 'web-static')))
423     
424     return web_root