removed old share explorer redirect page
[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             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_work2.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     
206     new_root = resource.Resource()
207     web_root.putChild('web', new_root)
208     
209     stat_log = []
210     if os.path.exists(os.path.join(datadir_path, 'stats')):
211         try:
212             with open(os.path.join(datadir_path, 'stats'), 'rb') as f:
213                 stat_log = json.loads(f.read())
214         except:
215             log.err(None, 'Error loading stats:')
216     def update_stat_log():
217         while stat_log and stat_log[0]['time'] < time.time() - 24*60*60:
218             stat_log.pop(0)
219         
220         lookbehind = 3600//net.SHARE_PERIOD
221         if tracker.get_height(current_work.value['best_share_hash']) < lookbehind:
222             return None
223         
224         global_stale_prop = p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], lookbehind)
225         (stale_orphan_shares, stale_doa_shares), shares, _ = get_stale_counts()
226         miner_hash_rates, miner_dead_hash_rates = get_local_rates()
227         
228         stat_log.append(dict(
229             time=time.time(),
230             pool_hash_rate=p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], lookbehind)/(1-global_stale_prop),
231             pool_stale_prop=global_stale_prop,
232             local_hash_rates=miner_hash_rates,
233             local_dead_hash_rates=miner_dead_hash_rates,
234             shares=shares,
235             stale_shares=stale_orphan_shares + stale_doa_shares,
236             stale_shares_breakdown=dict(orphan=stale_orphan_shares, doa=stale_doa_shares),
237             current_payout=get_current_txouts().get(bitcoin_data.pubkey_hash_to_script2(my_pubkey_hash), 0)*1e-8,
238             peers=dict(
239                 incoming=sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming),
240                 outgoing=sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming),
241             ),
242             attempts_to_share=bitcoin_data.target_to_average_attempts(tracker.shares[current_work.value['best_share_hash']].max_target),
243             attempts_to_block=bitcoin_data.target_to_average_attempts(current_work.value['bits'].target),
244             block_value=current_work2.value['subsidy']*1e-8,
245         ))
246         
247         with open(os.path.join(datadir_path, 'stats'), 'wb') as f:
248             f.write(json.dumps(stat_log))
249     task.LoopingCall(update_stat_log).start(5*60)
250     new_root.putChild('log', WebInterface(lambda: stat_log))
251     
252     def get_share(share_hash_str):
253         if int(share_hash_str, 16) not in tracker.shares:
254             return None
255         share = tracker.shares[int(share_hash_str, 16)]
256         
257         return dict(
258             parent='%064x' % share.previous_hash,
259             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
260             local=dict(
261                 verified=share.hash in tracker.verified.shares,
262                 time_first_seen=start_time if share.time_seen == 0 else share.time_seen,
263                 peer_first_received_from=share.peer.addr if share.peer is not None else None,
264             ),
265             share_data=dict(
266                 timestamp=share.timestamp,
267                 target=share.target,
268                 max_target=share.max_target,
269                 payout_address=bitcoin_data.script2_to_address(share.new_script, net.PARENT),
270                 donation=share.share_data['donation']/65535,
271                 stale_info=share.share_data['stale_info'],
272                 nonce=share.share_data['nonce'],
273                 desired_version=share.share_data['desired_version'],
274             ),
275             block=dict(
276                 hash='%064x' % share.header_hash,
277                 header=dict(
278                     version=share.header['version'],
279                     previous_block='%064x' % share.header['previous_block'],
280                     merkle_root='%064x' % share.header['merkle_root'],
281                     timestamp=share.header['timestamp'],
282                     target=share.header['bits'].target,
283                     nonce=share.header['nonce'],
284                 ),
285                 gentx=dict(
286                     hash='%064x' % share.gentx_hash,
287                     coinbase=share.share_data['coinbase'].ljust(2, '\x00').encode('hex'),
288                     value=share.share_data['subsidy']*1e-8,
289                 ),
290                 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'])],
291             ),
292         )
293     new_root.putChild('share', WebInterface(lambda share_hash_str: get_share(share_hash_str)))
294     new_root.putChild('heads', WebInterface(lambda: ['%064x' % x for x in tracker.heads]))
295     new_root.putChild('verified_heads', WebInterface(lambda: ['%064x' % x for x in tracker.verified.heads]))
296     new_root.putChild('tails', WebInterface(lambda: ['%064x' % x for t in tracker.tails for x in tracker.reverse_shares.get(t, set())]))
297     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())]))
298     new_root.putChild('best_share_hash', WebInterface(lambda: '%064x' % current_work.value['best_share_hash']))
299     new_root.putChild('currency_info', WebInterface(lambda: dict(
300         symbol=net.PARENT.SYMBOL,
301         block_explorer_url_prefix=net.PARENT.BLOCK_EXPLORER_URL_PREFIX,
302         address_explorer_url_prefix=net.PARENT.ADDRESS_EXPLORER_URL_PREFIX,
303     )))
304     
305     hd_path = os.path.join(datadir_path, 'graph_db')
306     hd_data = _atomic_read(hd_path)
307     hd_obj = {}
308     if hd_data is not None:
309         try:
310             hd_obj = json.loads(hd_data)
311         except Exception:
312             log.err(None, 'Error reading graph database:')
313     dataview_descriptions = {
314         'last_hour': graph.DataViewDescription(150, 60*60),
315         'last_day': graph.DataViewDescription(300, 60*60*24),
316         'last_week': graph.DataViewDescription(300, 60*60*24*7),
317         'last_month': graph.DataViewDescription(300, 60*60*24*30),
318         'last_year': graph.DataViewDescription(300, 60*60*24*365.25),
319     }
320     hd = graph.HistoryDatabase.from_obj({
321         'local_hash_rate': graph.DataStreamDescription(dataview_descriptions, is_gauge=False),
322         'local_dead_hash_rate': graph.DataStreamDescription(dataview_descriptions, is_gauge=False),
323         'local_share_hash_rate': graph.DataStreamDescription(dataview_descriptions, is_gauge=False),
324         'local_dead_share_hash_rate': graph.DataStreamDescription(dataview_descriptions, is_gauge=False),
325         'pool_rate': graph.DataStreamDescription(dataview_descriptions),
326         'pool_stale_rate': graph.DataStreamDescription(dataview_descriptions),
327         'current_payout': graph.DataStreamDescription(dataview_descriptions),
328         'current_payouts': graph.DataStreamDescription(dataview_descriptions, multivalues=True),
329         'incoming_peers': graph.DataStreamDescription(dataview_descriptions),
330         'outgoing_peers': graph.DataStreamDescription(dataview_descriptions),
331         'miner_hash_rates': graph.DataStreamDescription(dataview_descriptions, is_gauge=False, multivalues=True),
332         'miner_dead_hash_rates': graph.DataStreamDescription(dataview_descriptions, is_gauge=False, multivalues=True),
333         'desired_versions': graph.DataStreamDescription(dataview_descriptions, multivalues=True),
334     }, hd_obj)
335     task.LoopingCall(lambda: _atomic_write(hd_path, json.dumps(hd.to_obj()))).start(100)
336     @pseudoshare_received.watch
337     def _(work, dead, user):
338         t = time.time()
339         hd.datastreams['local_hash_rate'].add_datum(t, work)
340         if dead:
341             hd.datastreams['local_dead_hash_rate'].add_datum(t, work)
342         if user is not None:
343             hd.datastreams['miner_hash_rates'].add_datum(t, {user: work})
344             if dead:
345                 hd.datastreams['miner_dead_hash_rates'].add_datum(t, {user: work})
346     @share_received.watch
347     def _(work, dead):
348         t = time.time()
349         hd.datastreams['local_share_hash_rate'].add_datum(t, work)
350         if dead:
351             hd.datastreams['local_dead_share_hash_rate'].add_datum(t, work)
352     def add_point():
353         if tracker.get_height(current_work.value['best_share_hash']) < 720:
354             return
355         nonstalerate = p2pool_data.get_pool_attempts_per_second(tracker, current_work.value['best_share_hash'], 720)
356         poolrate = nonstalerate / (1 - p2pool_data.get_average_stale_prop(tracker, current_work.value['best_share_hash'], 720))
357         t = time.time()
358         hd.datastreams['pool_rate'].add_datum(t, poolrate)
359         hd.datastreams['pool_stale_rate'].add_datum(t, poolrate - nonstalerate)
360         current_txouts = get_current_txouts()
361         hd.datastreams['current_payout'].add_datum(t, current_txouts.get(bitcoin_data.pubkey_hash_to_script2(my_pubkey_hash), 0)*1e-8)
362         miner_hash_rates, miner_dead_hash_rates = get_local_rates()
363         current_txouts_by_address = dict((bitcoin_data.script2_to_address(script, net.PARENT), amount) for script, amount in current_txouts.iteritems())
364         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))
365         hd.datastreams['incoming_peers'].add_datum(t, sum(1 for peer in p2p_node.peers.itervalues() if peer.incoming))
366         hd.datastreams['outgoing_peers'].add_datum(t, sum(1 for peer in p2p_node.peers.itervalues() if not peer.incoming))
367         
368         vs = p2pool_data.get_desired_version_counts(tracker, current_work.value['best_share_hash'], 720)
369         vs_total = sum(vs.itervalues())
370         hd.datastreams['desired_versions'].add_datum(t, dict((str(k), v/vs_total) for k, v in vs.iteritems()))
371     task.LoopingCall(add_point).start(5)
372     new_root.putChild('graph_data', WebInterface(lambda source, view: hd.datastreams[source].dataviews[view].get_data(time.time())))
373     
374     web_root.putChild('static', static.File(os.path.join(os.path.dirname(sys.argv[0]), 'web-static')))
375     
376     return web_root