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