display current version on web
[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 import p2pool
14 from bitcoin import data as bitcoin_data
15 from . import data as p2pool_data
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: # XXX windows can't overwrite
44         os.remove(filename)
45         os.rename(filename + '.new', filename)
46
47 def get_web_root(tracker, current_work, 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):
48     start_time = time.time()
49     
50     web_root = resource.Resource()
51     
52     def get_users():
53         height, last = tracker.get_height_and_last(current_work.value['best_share_hash'])
54         weights, total_weight, donation_weight = tracker.get_cumulative_weights(current_work.value['best_share_hash'], min(height, 720), 65535*2**256)
55         res = {}
56         for script in sorted(weights, key=lambda s: weights[s]):
57             res[bitcoin_data.script2_to_address(script, net.PARENT)] = weights[script]/total_weight
58         return res
59     
60     def get_current_scaled_txouts(scale, trunc=0):
61         txouts = get_current_txouts()
62         total = sum(txouts.itervalues())
63         results = dict((script, value*scale//total) for script, value in txouts.iteritems())
64         if trunc > 0:
65             total_random = 0
66             random_set = set()
67             for s in sorted(results, key=results.__getitem__):
68                 if results[s] >= trunc:
69                     break
70                 total_random += results[s]
71                 random_set.add(s)
72             if total_random:
73                 winner = math.weighted_choice((script, results[script]) for script in random_set)
74                 for script in random_set:
75                     del results[script]
76                 results[winner] = total_random
77         if sum(results.itervalues()) < int(scale):
78             results[math.weighted_choice(results.iteritems())] += int(scale) - sum(results.itervalues())
79         return results
80     
81     def get_patron_sendmany(total=None, trunc='0.01'):
82         if total is None:
83             return 'need total argument. go to patron_sendmany/<TOTAL>'
84         total = int(float(total)*1e8)
85         trunc = int(float(trunc)*1e8)
86         return json.dumps(dict(
87             (bitcoin_data.script2_to_address(script, net.PARENT), value/1e8)
88             for script, value in get_current_scaled_txouts(total, trunc).iteritems()
89             if bitcoin_data.script2_to_address(script, net.PARENT) is not None
90         ))
91     
92     def get_local_rates():
93         miner_hash_rates = {}
94         miner_dead_hash_rates = {}
95         datums, dt = local_rate_monitor.get_datums_in_last()
96         for datum in datums:
97             miner_hash_rates[datum['user']] = miner_hash_rates.get(datum['user'], 0) + datum['work']/dt
98             if datum['dead']:
99                 miner_dead_hash_rates[datum['user']] = miner_dead_hash_rates.get(datum['user'], 0) + datum['work']/dt
100         return miner_hash_rates, miner_dead_hash_rates
101     
102     def get_global_stats():
103         # averaged over last hour
104         lookbehind = 3600//net.SHARE_PERIOD
105         if tracker.get_height(current_work.value['best_share_hash']) < lookbehind:
106             return None
107         
108         nonstale_hash_rate = p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], lookbehind)
109         stale_prop = p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], lookbehind)
110         return dict(
111             pool_nonstale_hash_rate=nonstale_hash_rate,
112             pool_hash_rate=nonstale_hash_rate/(1 - stale_prop),
113             pool_stale_prop=stale_prop,
114             min_difficulty=bitcoin_data.target_to_difficulty(tracker.shares[current_work.value['best_share_hash']].max_target),
115         )
116     
117     def get_local_stats():
118         lookbehind = 3600//net.SHARE_PERIOD
119         if tracker.get_height(current_work.value['best_share_hash']) < lookbehind:
120             return None
121         
122         global_stale_prop = p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], lookbehind)
123         
124         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)
125         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'] == 'orphan')
126         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'] == 'doa')
127         my_share_count = my_unstale_count + my_orphan_count + my_doa_count
128         my_stale_count = my_orphan_count + my_doa_count
129         
130         my_stale_prop = my_stale_count/my_share_count if my_share_count != 0 else None
131         
132         my_work = sum(bitcoin_data.target_to_average_attempts(share.target)
133             for share in tracker.get_chain(current_work.value['best_share_hash'], lookbehind - 1)
134             if share.hash in my_share_hashes)
135         actual_time = (tracker.shares[current_work.value['best_share_hash']].timestamp -
136             tracker.shares[tracker.get_nth_parent_hash(current_work.value['best_share_hash'], lookbehind - 1)].timestamp)
137         share_att_s = my_work / actual_time
138         
139         miner_hash_rates, miner_dead_hash_rates = get_local_rates()
140         (stale_orphan_shares, stale_doa_shares), shares, _ = get_stale_counts()
141         
142         return dict(
143             my_hash_rates_in_last_hour=dict(
144                 note="DEPRECATED",
145                 nonstale=share_att_s,
146                 rewarded=share_att_s/(1 - global_stale_prop),
147                 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
148             ),
149             my_share_counts_in_last_hour=dict(
150                 shares=my_share_count,
151                 unstale_shares=my_unstale_count,
152                 stale_shares=my_stale_count,
153                 orphan_stale_shares=my_orphan_count,
154                 doa_stale_shares=my_doa_count,
155             ),
156             my_stale_proportions_in_last_hour=dict(
157                 stale=my_stale_prop,
158                 orphan_stale=my_orphan_count/my_share_count if my_share_count != 0 else None,
159                 dead_stale=my_doa_count/my_share_count if my_share_count != 0 else None,
160             ),
161             miner_hash_rates=miner_hash_rates,
162             miner_dead_hash_rates=miner_dead_hash_rates,
163             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
164             efficiency=(1 - (stale_orphan_shares+stale_doa_shares)/shares)/(1 - global_stale_prop) if shares else None,
165             peers=dict(
166                 incoming=sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming),
167                 outgoing=sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming),
168             ),
169             shares=dict(
170                 total=shares,
171                 orphan=stale_orphan_shares,
172                 dead=stale_doa_shares,
173             ),
174             uptime=time.time() - start_time,
175             block_value=current_work.value['subsidy']*1e-8,
176             warnings=p2pool_data.get_warnings(tracker, current_work, net),
177         )
178     
179     class WebInterface(resource.Resource):
180         def __init__(self, func, mime_type='application/json', args=()):
181             resource.Resource.__init__(self)
182             self.func, self.mime_type, self.args = func, mime_type, args
183         
184         def getChild(self, child, request):
185             return WebInterface(self.func, self.mime_type, self.args + (child,))
186         
187         def render_GET(self, request):
188             request.setHeader('Content-Type', self.mime_type)
189             request.setHeader('Access-Control-Allow-Origin', '*')
190             res = self.func(*self.args)
191             return json.dumps(res) if self.mime_type == 'application/json' else res
192     
193     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))))
194     web_root.putChild('difficulty', WebInterface(lambda: bitcoin_data.target_to_difficulty(tracker.shares[current_work.value['best_share_hash']].max_target)))
195     web_root.putChild('users', WebInterface(get_users))
196     web_root.putChild('fee', WebInterface(lambda: worker_fee))
197     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())))
198     web_root.putChild('patron_sendmany', WebInterface(get_patron_sendmany, 'text/plain'))
199     web_root.putChild('global_stats', WebInterface(get_global_stats))
200     web_root.putChild('local_stats', WebInterface(get_local_stats))
201     web_root.putChild('peer_addresses', WebInterface(lambda: ['%s:%i' % (peer.transport.getPeer().host, peer.transport.getPeer().port) for peer in p2p_node.peers.itervalues()]))
202     web_root.putChild('peer_versions', WebInterface(lambda: dict(('%s:%i' % peer.addr, peer.other_sub_version) for peer in p2p_node.peers.itervalues())))
203     web_root.putChild('payout_addr', WebInterface(lambda: bitcoin_data.pubkey_hash_to_address(my_pubkey_hash, net.PARENT)))
204     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]))
205     web_root.putChild('uptime', WebInterface(lambda: time.time() - start_time))
206     web_root.putChild('stale_rates', WebInterface(lambda: p2pool_data.get_stale_counts(tracker, current_work.value['best_share_hash'], 720, rates=True)))
207     
208     new_root = resource.Resource()
209     web_root.putChild('web', new_root)
210     
211     stat_log = []
212     if os.path.exists(os.path.join(datadir_path, 'stats')):
213         try:
214             with open(os.path.join(datadir_path, 'stats'), 'rb') as f:
215                 stat_log = json.loads(f.read())
216         except:
217             log.err(None, 'Error loading stats:')
218     def update_stat_log():
219         while stat_log and stat_log[0]['time'] < time.time() - 24*60*60:
220             stat_log.pop(0)
221         
222         lookbehind = 3600//net.SHARE_PERIOD
223         if tracker.get_height(current_work.value['best_share_hash']) < lookbehind:
224             return None
225         
226         global_stale_prop = p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], lookbehind)
227         (stale_orphan_shares, stale_doa_shares), shares, _ = get_stale_counts()
228         miner_hash_rates, miner_dead_hash_rates = get_local_rates()
229         
230         stat_log.append(dict(
231             time=time.time(),
232             pool_hash_rate=p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], lookbehind)/(1-global_stale_prop),
233             pool_stale_prop=global_stale_prop,
234             local_hash_rates=miner_hash_rates,
235             local_dead_hash_rates=miner_dead_hash_rates,
236             shares=shares,
237             stale_shares=stale_orphan_shares + stale_doa_shares,
238             stale_shares_breakdown=dict(orphan=stale_orphan_shares, doa=stale_doa_shares),
239             current_payout=get_current_txouts().get(bitcoin_data.pubkey_hash_to_script2(my_pubkey_hash), 0)*1e-8,
240             peers=dict(
241                 incoming=sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming),
242                 outgoing=sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming),
243             ),
244             attempts_to_share=bitcoin_data.target_to_average_attempts(tracker.shares[current_work.value['best_share_hash']].max_target),
245             attempts_to_block=bitcoin_data.target_to_average_attempts(current_work.value['bits'].target),
246             block_value=current_work.value['subsidy']*1e-8,
247         ))
248         
249         with open(os.path.join(datadir_path, 'stats'), 'wb') as f:
250             f.write(json.dumps(stat_log))
251     task.LoopingCall(update_stat_log).start(5*60)
252     new_root.putChild('log', WebInterface(lambda: stat_log))
253     
254     def get_share(share_hash_str):
255         if int(share_hash_str, 16) not in tracker.shares:
256             return None
257         share = tracker.shares[int(share_hash_str, 16)]
258         
259         return dict(
260             parent='%064x' % share.previous_hash,
261             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
262             local=dict(
263                 verified=share.hash in tracker.verified.shares,
264                 time_first_seen=start_time if share.time_seen == 0 else share.time_seen,
265                 peer_first_received_from=share.peer.addr if share.peer is not None else None,
266             ),
267             share_data=dict(
268                 timestamp=share.timestamp,
269                 target=share.target,
270                 max_target=share.max_target,
271                 payout_address=bitcoin_data.script2_to_address(share.new_script, net.PARENT),
272                 donation=share.share_data['donation']/65535,
273                 stale_info=share.share_data['stale_info'],
274                 nonce=share.share_data['nonce'],
275                 desired_version=share.share_data['desired_version'],
276             ),
277             block=dict(
278                 hash='%064x' % share.header_hash,
279                 header=dict(
280                     version=share.header['version'],
281                     previous_block='%064x' % share.header['previous_block'],
282                     merkle_root='%064x' % share.header['merkle_root'],
283                     timestamp=share.header['timestamp'],
284                     target=share.header['bits'].target,
285                     nonce=share.header['nonce'],
286                 ),
287                 gentx=dict(
288                     hash='%064x' % share.gentx_hash,
289                     coinbase=share.share_data['coinbase'].ljust(2, '\x00').encode('hex'),
290                     value=share.share_data['subsidy']*1e-8,
291                 ),
292                 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'])],
293             ),
294         )
295     new_root.putChild('share', WebInterface(lambda share_hash_str: get_share(share_hash_str)))
296     new_root.putChild('heads', WebInterface(lambda: ['%064x' % x for x in tracker.heads]))
297     new_root.putChild('verified_heads', WebInterface(lambda: ['%064x' % x for x in tracker.verified.heads]))
298     new_root.putChild('tails', WebInterface(lambda: ['%064x' % x for t in tracker.tails for x in tracker.reverse_shares.get(t, set())]))
299     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())]))
300     new_root.putChild('best_share_hash', WebInterface(lambda: '%064x' % current_work.value['best_share_hash']))
301     new_root.putChild('currency_info', WebInterface(lambda: dict(
302         symbol=net.PARENT.SYMBOL,
303         block_explorer_url_prefix=net.PARENT.BLOCK_EXPLORER_URL_PREFIX,
304         address_explorer_url_prefix=net.PARENT.ADDRESS_EXPLORER_URL_PREFIX,
305     )))
306     new_root.putChild('version', WebInterface(lambda: p2pool.__version__))
307     
308     hd_path = os.path.join(datadir_path, 'graph_db')
309     hd_data = _atomic_read(hd_path)
310     hd_obj = {}
311     if hd_data is not None:
312         try:
313             hd_obj = json.loads(hd_data)
314         except Exception:
315             log.err(None, 'Error reading graph database:')
316     dataview_descriptions = {
317         'last_hour': graph.DataViewDescription(150, 60*60),
318         'last_day': graph.DataViewDescription(300, 60*60*24),
319         'last_week': graph.DataViewDescription(300, 60*60*24*7),
320         'last_month': graph.DataViewDescription(300, 60*60*24*30),
321         'last_year': graph.DataViewDescription(300, 60*60*24*365.25),
322     }
323     def build_pool_rates(ds_name, ds_desc, dv_name, dv_desc, obj):
324         if not obj:
325             last_bin_end = 0
326             bins = dv_desc.bin_count*[{}]
327         else:
328             pool_rate = obj['pool_rate'][dv_name]
329             pool_stale_rate = obj['pool_stale_rate'][dv_name]
330             last_bin_end = max(pool_rate['last_bin_end'], pool_stale_rate['last_bin_end'])
331             bins = dv_desc.bin_count*[{}]
332             def get_value(obj, t):
333                 n = int((obj['last_bin_end'] - t)/dv_desc.bin_width)
334                 if n < 0 or n >= dv_desc.bin_count:
335                     return None, 0
336                 total, count = obj['bins'][n].get('null', [0, 0])
337                 if count == 0:
338                     return None, 0
339                 return total/count, count
340             def get_bin(t):
341                 total, total_count = get_value(pool_rate, t)
342                 bad, bad_count = get_value(pool_stale_rate, t)
343                 if total is None or bad is None:
344                     return {}
345                 count = int((total_count+bad_count)/2+1/2)
346                 return dict(good=[(total-bad)*count, count], bad=[bad*count, count], null=[0, count])
347             bins = [get_bin(last_bin_end - (i+1/2)*dv_desc.bin_width) for i in xrange(dv_desc.bin_count)]
348         return graph.DataView(dv_desc, ds_desc, last_bin_end, bins)
349     hd = graph.HistoryDatabase.from_obj({
350         'local_hash_rate': graph.DataStreamDescription(dataview_descriptions, is_gauge=False),
351         'local_dead_hash_rate': graph.DataStreamDescription(dataview_descriptions, is_gauge=False),
352         'local_share_hash_rate': graph.DataStreamDescription(dataview_descriptions, is_gauge=False),
353         'local_dead_share_hash_rate': graph.DataStreamDescription(dataview_descriptions, is_gauge=False),
354         'pool_rates': graph.DataStreamDescription(dataview_descriptions, multivalues=True,
355             multivalue_undefined_means_0=True, default_func=build_pool_rates),
356         'current_payout': graph.DataStreamDescription(dataview_descriptions),
357         'current_payouts': graph.DataStreamDescription(dataview_descriptions, multivalues=True),
358         'incoming_peers': graph.DataStreamDescription(dataview_descriptions),
359         'outgoing_peers': graph.DataStreamDescription(dataview_descriptions),
360         'miner_hash_rates': graph.DataStreamDescription(dataview_descriptions, is_gauge=False, multivalues=True),
361         'miner_dead_hash_rates': graph.DataStreamDescription(dataview_descriptions, is_gauge=False, multivalues=True),
362         'desired_versions': graph.DataStreamDescription(dataview_descriptions, multivalues=True,
363             multivalue_undefined_means_0=True),
364     }, hd_obj)
365     task.LoopingCall(lambda: _atomic_write(hd_path, json.dumps(hd.to_obj()))).start(100)
366     @pseudoshare_received.watch
367     def _(work, dead, user):
368         t = time.time()
369         hd.datastreams['local_hash_rate'].add_datum(t, work)
370         if dead:
371             hd.datastreams['local_dead_hash_rate'].add_datum(t, work)
372         if user is not None:
373             hd.datastreams['miner_hash_rates'].add_datum(t, {user: work})
374             if dead:
375                 hd.datastreams['miner_dead_hash_rates'].add_datum(t, {user: work})
376     @share_received.watch
377     def _(work, dead):
378         t = time.time()
379         hd.datastreams['local_share_hash_rate'].add_datum(t, work)
380         if dead:
381             hd.datastreams['local_dead_share_hash_rate'].add_datum(t, work)
382     def add_point():
383         if tracker.get_height(current_work.value['best_share_hash']) < 720:
384             return
385         t = time.time()
386         hd.datastreams['pool_rates'].add_datum(t, p2pool_data.get_stale_counts(tracker, current_work.value['best_share_hash'], 720, rates=True))
387         current_txouts = get_current_txouts()
388         hd.datastreams['current_payout'].add_datum(t, current_txouts.get(bitcoin_data.pubkey_hash_to_script2(my_pubkey_hash), 0)*1e-8)
389         miner_hash_rates, miner_dead_hash_rates = get_local_rates()
390         current_txouts_by_address = dict((bitcoin_data.script2_to_address(script, net.PARENT), amount) for script, amount in current_txouts.iteritems())
391         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))
392         hd.datastreams['incoming_peers'].add_datum(t, sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming))
393         hd.datastreams['outgoing_peers'].add_datum(t, sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming))
394         
395         vs = p2pool_data.get_desired_version_counts(tracker, current_work.value['best_share_hash'], 720)
396         vs_total = sum(vs.itervalues())
397         hd.datastreams['desired_versions'].add_datum(t, dict((str(k), v/vs_total) for k, v in vs.iteritems()))
398     task.LoopingCall(add_point).start(5)
399     new_root.putChild('graph_data', WebInterface(lambda source, view: hd.datastreams[source].dataviews[view].get_data(time.time())))
400     
401     web_root.putChild('static', static.File(os.path.join(os.path.dirname(sys.argv[0]), 'web-static')))
402     
403     return web_root