-
Notifications
You must be signed in to change notification settings - Fork 140
/
abe.py
executable file
·4506 lines (3895 loc) · 185 KB
/
abe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright(C) 2011,2012,2013,2014 by Abe developers.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/agpl.html>.
import sys
import os
import re
import types
from cgi import escape
import posixpath
import wsgiref.util
import time
import calendar
import logging
import json
import version
import DataStore
import readconf
# bitcointools -- modified deserialize.py to return raw transaction
import deserialize
import util # Added functions.
import base58
# MULTICHAIN START
import Chain
import urllib
import binascii
import urllib2
import threading
# MULTICHAIN END
__version__ = version.__version__
# MULTICHAIN START
ABE_APPNAME = "MultiChain Explorer"
ABE_VERSION = __version__
ABE_URL = 'https://github.com/multichain/multichain-explorer'
COPYRIGHT_YEARS = '2011-2017'
COPYRIGHT = "Coin Sciences Ltd and Abe developers"
COPYRIGHT_URL = 'https://github.com/multichain/multichain-explorer'
# MULTICHAIN END
TIME1970 = time.strptime('1970-01-01','%Y-%m-%d')
EPOCH1970 = calendar.timegm(TIME1970)
# Abe-generated content should all be valid HTML and XHTML fragments.
# Configurable templates may contain either. HTML seems better supported
# under Internet Explorer.
DEFAULT_CONTENT_TYPE = "text/html; charset=utf-8"
DEFAULT_HOMEPAGE = "chains"
# MULTICHAIN START
DEFAULT_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>%(title)s</title>
<!-- Bootstrap and Theme -->
<link href="%(dotdot)s%(STATIC_PATH)scss/bootstrap.min.css" rel="stylesheet">
<link href="%(dotdot)s%(STATIC_PATH)scss/bootstrap-theme.min.css" rel="stylesheet">
<link href="%(dotdot)s%(STATIC_PATH)sabe.css" rel="stylesheet">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="%(dotdot)s%(STATIC_PATH)sjs/jquery-1.11.3.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="%(dotdot)s%(STATIC_PATH)sjs/bootstrap.min.js"></script>
<script src="%(dotdot)s%(STATIC_PATH)sabe.js"></script>
%(myheader)s
</head>
<body>
<div class="container">
<table><td>
<a title="Back to home" href="%(dotdot)s%(HOMEPAGE)s"><img src="%(dotdot)s%(STATIC_PATH)slogo32.png" alt="MultiChain logo" /></a>
</td><td style="padding-left: 10px;" valign="middle">
<h1>%(h1)s<h1>
</td></table>
%(body)s
<!--<p><a href="%(dotdot)sq">API</a> (machine-readable pages)</p>-->
<br><br>
<p style="font-size: smaller">
<span style="font-style: italic">
Powered by <a href="%(ABE_URL)s">%(APPNAME)s</a>
</span>
%(download)s
</p>
</div>
</body>
</html>
"""
# MULTICHAIN END
DEFAULT_LOG_FORMAT = "%(message)s"
DEFAULT_DECIMALS = 8
# It is fun to change "6" to "3" and search lots of addresses.
ADDR_PREFIX_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{6,}\\Z')
HEIGHT_RE = re.compile('(?:0|[1-9][0-9]*)\\Z')
HASH_PREFIX_RE = re.compile('[0-9a-fA-F]{0,64}\\Z')
HASH_PREFIX_MIN = 6
NETHASH_HEADER = """\
blockNumber: height of last block in interval + 1
time: block time in seconds since 0h00 1 Jan 1970 UTC
target: decimal target at blockNumber
avgTargetSinceLast: harmonic mean of target over interval
difficulty: difficulty at blockNumber
hashesToWin: expected number of hashes needed to solve a block at this difficulty
avgIntervalSinceLast: interval seconds divided by blocks
netHashPerSecond: estimated network hash rate over interval
Statistical values are approximate and differ slightly from http://blockexplorer.com/q/nethash.
/chain/CHAIN/q/nethash[/INTERVAL[/START[/STOP]]]
Default INTERVAL=144, START=0, STOP=infinity.
Negative values back from the last block.
Append ?format=json to URL for headerless, JSON output.
blockNumber,time,target,avgTargetSinceLast,difficulty,hashesToWin,avgIntervalSinceLast,netHashPerSecond
START DATA
"""
NETHASH_SVG_TEMPLATE = """\
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:abe="http://abe.bit/abe"
viewBox="0 0 300 200"
preserveAspectRatio="none"
onload="Abe.draw(this)">
<style>
#chart polyline {
stroke-width: 0.1%%;
fill-opacity: 0;
stroke-opacity: 0.5;
</style>
<script type="application/ecmascript"
xlink:href="%(dotdot)s%(STATIC_PATH)snethash.js"/>
<g id="chart">
<polyline abe:window="1d" style="stroke: red;"/>
<polyline abe:window="3d" style="stroke: orange;"/>
<polyline abe:window="7d" style="stroke: yellow;"/>
<polyline abe:window="14d" style="stroke: green;"/>
<polyline abe:window="30d" style="stroke: blue;"/>
%(body)s
</g>
</svg>
"""
# How many addresses to accept in /unspent/ADDR|ADDR|...
MAX_UNSPENT_ADDRESSES = 200
# MULTICHAIN START
def html_keyvalue_tablerow(key, *values):
"""
Return string for a two column table row.
Where the first element is the key and everything else is treated as the value
"""
return '<tr><td>', key, '</td><td>', list(values), '</td></tr>'
def html_keyvalue_tablerow_wrap(minwidth, maxwidth, key, *values):
"""
Return string for a two column table row, with word wrapping of <td> element.
Where the first element is the key and everything else is treated as the value
"""
return '<tr><td style="word-wrap: break-word;min-width: ', minwidth, 'px;max-width: ',maxwidth,'px;white-space:normal;">', key, '</td><td style="word-wrap: break-word;min-width: ',minwidth,'px;max-width: ',maxwidth,'px;white-space:normal;">', list(values), '</td></tr>'
# MULTICHAIN END
def make_store(args):
store = DataStore.new(args)
if (not args.no_load):
store.catch_up()
return store
class NoSuchChainError(Exception):
"""Thrown when a chain lookup fails"""
class PageNotFound(Exception):
"""Thrown when code wants to return 404 Not Found"""
class Redirect(Exception):
"""Thrown when code wants to redirect the request"""
class Streamed(Exception):
"""Thrown when code has written the document to the callable
returned by start_response."""
class Abe:
def __init__(abe, store, args):
abe.store = store
abe.args = args
abe.htdocs = args.document_root or find_htdocs()
abe.static_path = '' if args.static_path is None else args.static_path
abe.template_vars = args.template_vars.copy()
abe.template_vars['STATIC_PATH'] = (
abe.template_vars.get('STATIC_PATH', abe.static_path))
abe.template = flatten(args.template)
abe.debug = args.debug
abe.log = logging.getLogger(__name__)
abe.log.info('Abe initialized.')
abe.home = str(abe.template_vars.get("HOMEPAGE", DEFAULT_HOMEPAGE))
if not args.auto_agpl:
abe.template_vars['download'] = (
abe.template_vars.get('download', ''))
abe.base_url = args.base_url
abe.address_history_rows_max = int(
args.address_history_rows_max or 1000)
if args.shortlink_type is None:
abe.shortlink_type = ("firstbits" if store.use_firstbits else
"non-firstbits")
else:
abe.shortlink_type = args.shortlink_type
if abe.shortlink_type != "firstbits":
abe.shortlink_type = int(abe.shortlink_type)
if abe.shortlink_type < 2:
raise ValueError("shortlink-type: 2 character minimum")
elif not store.use_firstbits:
abe.shortlink_type = "non-firstbits"
abe.log.warning("Ignoring shortlink-type=firstbits since" +
" the database does not support it.")
if abe.shortlink_type == "non-firstbits":
abe.shortlink_type = 10
# MULTICHAIN START
abe.blockchainparams = {}
# MULTICHAIN END
def __call__(abe, env, start_response):
import urlparse
page = {
"status": '200 OK',
"title": [escape(ABE_APPNAME), " ", ABE_VERSION],
"body": [],
"env": env,
"params": {},
"dotdot": "../" * (env['PATH_INFO'].count('/') - 1),
"start_response": start_response,
"content_type": str(abe.template_vars['CONTENT_TYPE']),
"template": abe.template,
"chain": None,
# MULTICHAIN START
"myheader": []
# MULTICHAIN END
}
if 'QUERY_STRING' in env:
page['params'] = urlparse.parse_qs(env['QUERY_STRING'])
if abe.fix_path_info(env):
abe.log.debug("fixed path_info")
return redirect(page)
# MULTICHAIN START
# First component of path is chain name
symbol = wsgiref.util.shift_path_info(env)
chain = None
handler = None
cmd = None
try:
chain = abe.chain_lookup_by_name(symbol)
page['chain'] = chain
except NoSuchChainError:
cmd = symbol
# If there is no chain, could be home page or resource
if chain is None:
if symbol.strip() == DEFAULT_HOMEPAGE:
cmd = DEFAULT_HOMEPAGE
handler = abe.get_handler(cmd)
elif symbol == 'search':
cmd = "search"
handler = abe.get_handler(cmd)
chain = abe.store.get_chain_by_id(1)
page['chain'] = chain
else:
# Second component of path is the command
cmd = wsgiref.util.shift_path_info(env)
if cmd=='' or cmd is None:
cmd = 'chain'
handler = abe.get_handler(cmd)
# MULTICHAIN END
tvars = abe.template_vars.copy()
tvars['dotdot'] = page['dotdot']
page['template_vars'] = tvars
try:
if handler is None:
return abe.serve_static(cmd + env['PATH_INFO'], start_response)
if (not abe.args.no_load):
# Always be up-to-date, even if we means having to wait
# for a response! XXX Could use threads, timers, or a
# cron job.
abe.store.catch_up()
handler(page)
except PageNotFound:
page['status'] = '404 Not Found'
page['body'] = ['<p class="error">Sorry, ', env['SCRIPT_NAME'],
env['PATH_INFO'],
' does not exist on this server.</p>']
except NoSuchChainError as e:
page['body'] += [
'<p class="error">'
'Sorry, I don\'t know about that chain!</p>\n']
except Redirect:
content=redirect(page)
if isinstance(content, unicode):
content = content.encode('utf-8') # Convert Unicode escaped bytes$
return content
except Streamed:
return ''
except Exception:
abe.store.rollback()
raise
abe.store.rollback() # Close implicitly opened transaction.
start_response(page['status'],
[('Content-type', page['content_type']),
('Cache-Control', 'max-age=30')])
# MULTICHAIN START
tvars['myheader'] = flatten(page['myheader'])
# MULTICHAIN END
tvars['title'] = flatten(page['title'])
tvars['h1'] = flatten(page.get('h1') or page['title'])
tvars['body'] = flatten(page['body'])
if abe.args.auto_agpl:
tvars['download'] = (
' <a href="' + page['dotdot'] + 'download">Source</a>')
content = page['template'] % tvars
if isinstance(content, unicode):
content = content.encode('utf-8') # Convert Unicode escaped bytes into binary. Used to be UTF-8.
return [content]
# MULTICHAIN START
# Return and cache blockchain params. Empty dictionary is returned if there is an error.
def get_blockchainparams(abe, chain):
if len(abe.blockchainparams) > 0:
return abe.blockchainparams
url = abe.store.get_url_by_chain(chain)
multichain_name = abe.store.get_multichain_name_by_id(chain.id)
params = {}
try:
params = util.jsonrpc(multichain_name, url, "getblockchainparams")
assert(len(params['chain-protocol']) > 0) # if we get invalid result, an exception is thrown
abe.blockchainparams = params
except Exception as e:
pass # nop
return params
# MULTICHAIN END
def get_handler(abe, cmd):
return getattr(abe, 'handle_' + cmd, None)
def handle_chains(abe, page):
# MULTICHAIN START
page['title'] = ABE_APPNAME
# MULTICHAIN END
body = page['body']
body += [
abe.search_form(page),
# MULTICHAIN START
'<table class="table table-striped">\n',
'<tr><th>Status</th>',
'<th>Chain</th>',
'<th>Blocks</th>',
'<th>Transactions</th>',
#'<th>Time</th>',
'<th>Assets</th>',
'<th>Addresses</th>',
'<th>Streams</th>',
'<th>Peers</th>'
'<th>Started</th><th>Age (days)</th>',
#'<th>Coins Created</th>',
#'<th>Avg Coin Age</th><th>',
#'% <a href="https://en.bitcoin.it/wiki/Bitcoin_Days_Destroyed">',
#'CoinDD</a></th>',
# MULTICHAIN END
'</tr>\n']
now = time.time() - EPOCH1970
rows = abe.store.selectall("""
SELECT c.chain_name, b.block_height, b.block_nTime, b.block_hash,
b.block_total_seconds, b.block_total_satoshis,
b.block_satoshi_seconds,
b.block_total_ss
FROM chain c
JOIN block b ON (c.chain_last_block_id = b.block_id)
ORDER BY c.chain_name
""")
for row in rows:
name = row[0]
chain = abe.store.get_chain_by_name(name)
if chain is None:
abe.log.warning("Store does not know chain: %s", name)
continue
# MULTICHAIN START
num_txs = abe.store.get_number_of_transactions(chain)
num_addresses = abe.store.get_number_of_addresses(chain)
connection_status = True
try:
num_peers = abe.store.get_number_of_peers(chain)
num_assets = abe.store.get_number_of_assets(chain)
num_streams = abe.store.get_number_of_streams(chain)
except Exception as e:
connection_status = False
abe.log.warning(e)
num_assets = -1
num_peers = -1
num_streams = -1
body += ['<tr><td>']
if connection_status is True:
body += '<span class="label label-success">Connected</span>'
else:
body += '<span class="label label-danger">No Connection</span>'
body += ['</td>']
body += [
'<td><a href="', escape(name), '/chain">',
escape(name), '</a></td>'] #<td>', escape(chain.code3), '</td>']
# MULTICHAIN END
if row[1] is not None:
(height, nTime, hash) = (
int(row[1]), int(row[2]), abe.store.hashout_hex(row[3]))
body += [
# MULTICHAIN START
'<td><a href="', escape(name), '/blocks">', height, '</a></td>',
'<td>', num_txs, '</td>']
#'<td><a href="block/', hash, '">', height, '</a></td>', ]
#'<td>', format_time(nTime), '</td>']
body += '<td>'
if chain.__class__.__name__ is "MultiChain":
if num_assets == -1:
body += '?'
elif num_assets>=0:
body += ['<a href="{0}/assets">'.format(escape(chain.name)), num_assets, '</a>']
else:
body += ['<td></td>']
body += ['<td>', num_addresses, '</td>']
body += '</td>'
# Display number of streams in the chain
body += '<td>'
if chain.__class__.__name__ is "MultiChain":
if num_streams == -1:
body += '?'
elif num_streams == 0:
body += '0'
else:
body += ['<a href="{0}/streams">'.format(escape(chain.name)), num_streams, '</a>']
else:
pass #body += ['<td></td>']
#body += ['<td>', num_streams, '</td>']
body += '</td>'
# MULTICHAIN END
if row[6] is not None and row[7] is not None:
(seconds, satoshis, ss, total_ss) = (
int(row[4]), int(row[5]), int(row[6]), int(row[7]))
started = nTime - seconds
chain_age = now - started
since_block = now - nTime
# MULTICHAIN START
# if satoshis == 0:
# avg_age = ' '
# else:
# avg_age = '%5g' % ((float(ss) / satoshis + since_block)
# / 86400.0)
# if chain_age <= 0:
# percent_destroyed = ' '
# else:
# more = since_block * satoshis
# denominator = total_ss + more
# if denominator <= 0:
# percent_destroyed = ' '
# else:
# percent_destroyed = '%5g%%' % (
# 100.0 - (100.0 * (ss + more) / denominator))
body += [
'<td>',
'?' if num_peers is -1 else num_peers,
'</td>',
'<td>', format_time(started)[:10], '</td>',
'<td>', "{0:.1f}".format(chain_age / 86400.0), '</td>']
# '<td>', format_satoshis(satoshis, chain), '</td>',
# '<td>', avg_age, '</td>',
# '<td>', percent_destroyed, '</td>']
# MULTICHAIN END
body += ['</tr>\n']
body += ['</table>\n']
if len(rows) == 0:
body += ['<p>No block data found.</p>\n']
# MULTICHAIN START
myheader = page['myheader']
mempool_refresh_interval_ms = abe.store.recent_tx_interval_ms
myheader += ['<script>'
'$(document).ready(function(){'
'setInterval(function(){'
'$("#recenttx").load(\'' + page['dotdot'] + urllib.quote(name, safe='') + '/recent?random=\' + Math.random().toString() )'
'}, ', mempool_refresh_interval_ms, ');'
'});'
'</script>']
page_refresh_interval_secs = abe.store.home_refresh_interval_secs
myheader += ['<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />',
'<meta http-equiv="Pragma" content="no-cache" />',
'<meta http-equiv="Expires" content="0" />']
myheader += ['<meta http-equiv="refresh" content="', page_refresh_interval_secs, '" >']
body += ['<div id="recenttx">']
body += abe.create_recent_table(page, chain)
body += ['</div>']
def handle_recent(abe, page):
chain = page['chain']
page['template'] = "%(body)s"
page['title'] = chain.name
body = page['body']
body += abe.create_recent_table(page, chain)
def create_recent_table(abe, page, chain):
"""
Create table of recent transactions via JSON-RPC and return list of HTML elements
:param chain:
:return:
"""
body = []
body += ['<h3>Latest Transactions</h3>'
'<table class="table table-striped">\n',
'<tr><th>Txid</th>', '<th>Type</th><th>Confirmation</th>'
'<th>Time</th>',
'</tr>\n']
now = time.time() - EPOCH1970
try:
mempool = abe.store.get_rawmempool(chain)
recenttx = abe.store.get_recent_transactions_as_json(chain, 10)
except Exception as e:
return ['<div class="alert alert-danger" role="warning">', e ,'</div>']
sorted_mempool = sorted(mempool.items()[:10], key=lambda tup: tup[1]['time'], reverse=True)
if len(sorted_mempool) < 10:
sorted_recenttx = sorted(recenttx, key=lambda tx: tx['time'], reverse=True)
existing_txids = [txid for (txid, value) in sorted_mempool]
for tx in sorted_recenttx:
if len(sorted_mempool) == 10:
break
if tx['txid'] not in existing_txids:
existing_txids.append(tx['txid'])
sorted_mempool.append((tx['txid'], tx))
for (k, v) in sorted_mempool: # mempool.iteritems():
txid = k
diff = int(now - v['time'])
if diff < 60:
elapsed = "< 1 minute"
elif diff < 3600:
elapsed = "< " + str(int((diff / 60)+0.5)) + " minutes"
elif diff < 3600*24*2:
elapsed = "< " + str(int(diff / 3600)) + " hours"
else:
elapsed = str(int((diff / 3600) / 24)) + " days"
body += ['<tr><td>']
if abe.store.does_transaction_exist(txid):
body += ['<a href="' + page['dotdot'] + escape(chain.name) + '/tx/' + txid + '">', txid, '</a>']
labels = abe.store.get_labels_for_tx(txid, chain)
else:
body += ['<a href="' + page['dotdot'] + escape(chain.name) + '/mempooltx/' + txid + '">', txid, '</a>']
json = None
try:
json = abe.store.get_rawtransaction_decoded(chain, txid)
except Exception:
pass
if json is not None:
scriptpubkeys = [vout['scriptPubKey']['hex'] for vout in json['vout']]
labels = None
d = set()
for hex in scriptpubkeys:
binscript = binascii.unhexlify(hex)
tmp = abe.store.get_labels_for_scriptpubkey(chain, binscript)
d |= set(tmp)
labels = list(d)
if labels is None:
labels = []
body += ['</td><td>']
for label in labels:
body += [' <span class="label label-primary">',label,'</span>']
body += ['</td><td>']
conf = v.get('confirmations', None)
if conf is None or conf == 0:
body += ['<span class="label label-default">Mempool</span>']
else:
body += ['<span class="label label-info">', conf, ' confirmations</span>']
body += ['</td><td>', elapsed, '</td></tr>']
body += ['</table>']
return body
# MULTICHAIN END
def chain_lookup_by_name(abe, symbol):
if symbol is None:
ret = abe.get_default_chain()
else:
ret = abe.store.get_chain_by_name(symbol)
if ret is None:
raise NoSuchChainError()
return ret
def get_default_chain(abe):
return abe.store.get_default_chain()
def format_addresses(abe, data, dotdot, chain):
# MULTICHAIN START
checksum = chain.address_checksum
# MULTICHAIN END
if data['binaddr'] is None:
return 'Unknown'
if 'subbinaddr' in data:
# Multisig or known P2SH.
# MULTICHAIN START
ret = [hash_to_address_link(chain.script_addr_vers, data['binaddr'], dotdot, text='Escrow', checksum=checksum),
' ', data['required_signatures'], ' of']
for binaddr in data['subbinaddr']:
ret += [' ', hash_to_address_link(data['address_version'], binaddr, dotdot, 10, checksum=checksum)]
return ret
return hash_to_address_link(data['address_version'], data['binaddr'], dotdot, checksum=checksum)
# MULTICHAIN END
def call_handler(abe, page, cmd):
handler = abe.get_handler(cmd)
if handler is None:
raise PageNotFound()
handler(page)
# MULTICHAIN_START
def handle_chain(abe, page):
chain = page['chain']
#page['content_type'] = 'text/html'
page['title'] = chain.name
body = page['body']
url = abe.store.get_url_by_chain(chain)
multichain_name = abe.store.get_multichain_name_by_id(chain.id)
# high level stats
num_txs = abe.store.get_number_of_transactions(chain)
num_addresses = abe.store.get_number_of_addresses(chain)
try:
num_peers = abe.store.get_number_of_peers(chain)
num_assets = abe.store.get_number_of_assets(chain)
except Exception as e:
abe.log.warning(e)
num_assets = -1
num_peers = -1
try:
num_streams = abe.store.get_number_of_streams(chain)
except Exception as e:
abe.log.warning(e)
num_streams = -1
info_resp = None
params_resp = None
try:
info_resp = util.jsonrpc(multichain_name, url, "getinfo")
params_resp = util.jsonrpc(multichain_name, url, "getblockchainparams")
except util.JsonrpcException as e:
msg= "JSON-RPC error({0}): {1}".format(e.code, e.message)
body += ['<div class="alert alert-danger" role="warning">', msg ,'</div>']
return
except IOError as e:
body += ['<div class="alert alert-danger" role="alert">', e, '</div>']
return
body += ['<div class="container"><div class="row"><div class="col-md-6">']
body += ['<h3>Summary</h3>']
body += ['<table class="table table-bordered table-striped table-condensed">']
body += ['<td>Blocks</td>', '<td><a href="', page['dotdot'], escape(chain.name), '/blocks/">', info_resp['blocks'], '</a></td>']
#body += html_keyvalue_tablerow('Blocks', info_resp['blocks'])
body += html_keyvalue_tablerow('Transactions', num_txs)
body += ['<td>Assets</td>', '<td><a href="', page['dotdot'], escape(chain.name), '/assets">', num_assets, '</a></td>']
#body += html_keyvalue_tablerow('Assets', num_assets)
body += html_keyvalue_tablerow('Addresses', num_addresses)
body += ['<td>Streams</td>', '<td><a href="', page['dotdot'], escape(chain.name), '/streams">', num_streams, '</a></td>']
#body += html_keyvalue_tablerow('Streams', num_streams)
body += ['</table>']
body += ['<h3>General Information</h3>']
body += ['<table class="table table-bordered table-striped table-condensed">']
#body += ['<colgroup><col class="col-md-4"><col class="col-md-8"></colgroup>']
for k,v in sorted(info_resp.items()):
if k in ('nodeaddress', 'port'):
continue
if k in ('relayfee'):
#v = '%.8g' % v # doesn't work?
v = ('%.20f' % v).rstrip('0') # so instead we force the number of decimal places and strip zeros
body += html_keyvalue_tablerow(k, v)
body += ['</table>']
body += ['</div><div class="col-md-6">']
body += ['<h3>Blockchain Parameters</h3>']
body += ['<table class="table table-bordered table-striped table-condensed">']
#body += ['<colgroup><col class="col-md-4"><col class="col-md-8"></colgroup>']
for k,v in sorted(params_resp.items()):
if k in ('default-network-port', 'default-rpc-port'):
continue
body += html_keyvalue_tablerow_wrap(50, 300, k, v)
body += ['</table>']
body += ['</div></div></div>'] # col, row, container
def handle_blocks(abe, page):
chain = page['chain']
# MULTICHAIN_END
cmd = wsgiref.util.shift_path_info(page['env'])
if cmd == '':
page['env']['SCRIPT_NAME'] = page['env']['SCRIPT_NAME'][:-1]
raise Redirect()
if cmd == 'chain' or cmd == 'chains':
raise PageNotFound()
if cmd is not None:
abe.call_handler(page, cmd)
return
page['title'] = chain.name
body = page['body']
body += abe.search_form(page)
count = get_int_param(page, 'count') or 20
hi = get_int_param(page, 'hi')
orig_hi = hi
if hi is None:
row = abe.store.selectrow("""
SELECT b.block_height
FROM block b
JOIN chain c ON (c.chain_last_block_id = b.block_id)
WHERE c.chain_id = ?
""", (chain.id,))
if row:
hi = row[0]
if hi is None:
if orig_hi is None and count > 0:
body += ['<p>I have no blocks in this chain.</p>']
else:
body += ['<p class="error">'
'The requested range contains no blocks.</p>\n']
return
rows = abe.store.selectall("""
SELECT b.block_hash, b.block_height, b.block_nTime, b.block_num_tx,
b.block_nBits, b.block_value_out,
b.block_total_seconds, b.block_satoshi_seconds,
b.block_total_satoshis, b.block_ss_destroyed,
b.block_total_ss
FROM block b
JOIN chain_candidate cc ON (b.block_id = cc.block_id)
WHERE cc.chain_id = ?
AND cc.block_height BETWEEN ? AND ?
AND cc.in_longest = 1
ORDER BY cc.block_height DESC LIMIT ?
""", (chain.id, hi - count + 1, hi, count))
if hi is None:
hi = int(rows[0][1])
basename = os.path.basename(page['env']['PATH_INFO'])
nav = ['<a href="',
basename, '?count=', str(count), '"><<</a>']
nav += [' <a href="', basename, '?hi=', str(hi + count),
'&count=', str(count), '"><</a>']
nav += [' ', '>']
if hi >= count:
nav[-1] = ['<a href="', basename, '?hi=', str(hi - count),
'&count=', str(count), '">', nav[-1], '</a>']
nav += [' ', '>>']
if hi != count - 1:
nav[-1] = ['<a href="', basename, '?hi=', str(count - 1),
'&count=', str(count), '">', nav[-1], '</a>']
for c in (20, 50, 100, 500):
nav += [' ']
if c != count:
nav += ['<a href="', basename, '?count=', str(c)]
if hi is not None:
nav += ['&hi=', str(max(hi, c - 1))]
nav += ['">']
nav += [' ', str(c)]
if c != count:
nav += ['</a>']
nav += [' <a href="', page['dotdot'], '">Search</a>']
extra = False
#extra = True
body += ['<p>', nav, '</p>\n',
# MULTICHAIN START
'<table class="table table-striped"><tr><th>Block</th><th>Miner</th><th>Approx. Time</th>',
'<th>Transactions</th>',
#'<th>Value Out</th>',
#'<th>Difficulty</th><th>Outstanding</th>',
#'<th>Average Age</th>'
'<th>Chain Age</th>',
#'<th>% ',
#'<a href="https://en.bitcoin.it/wiki/Bitcoin_Days_Destroyed">',
#'CoinDD</a></th>',
# MULTICHAIN END
['<th>Satoshi-seconds</th>',
'<th>Total ss</th>']
if extra else '',
'</tr>\n']
for row in rows:
(hash, height, nTime, num_tx, nBits, value_out,
seconds, ss, satoshis, destroyed, total_ss) = row
nTime = int(nTime)
value_out = int(value_out)
seconds = int(seconds)
satoshis = int(satoshis)
ss = int(ss)
total_ss = int(total_ss)
# if satoshis == 0:
# avg_age = ' '
# else:
# avg_age = '%5g' % (ss / satoshis / 86400.0)
if total_ss <= 0:
percent_destroyed = ' '
else:
percent_destroyed = '%5g%%' % (100.0 - (100.0 * ss / total_ss))
# MULTICHAIN START
miner_address = ''
miner_block = None
try:
miner_block = abe.store.export_block(chain, block_number=height)
except DataStore.MalformedHash:
pass
if miner_block is not None:
miner_txout = miner_block['transactions'][0]['out'][0]
if miner_txout['binaddr'] is not None:
miner_address = abe.format_addresses(miner_txout, page['dotdot'], chain)
#miner_address = miner_address[0:6]
else:
try:
blockjson = abe.store.get_block_by_hash(chain, miner_block['hash'])
miner = blockjson['miner']
miner_address = '<a href="' + page['dotdot'] + '/' + escape(chain.name) + '/address/' + miner + '">' + miner + '</a>'
except Exception:
miner_address = "Unknown"
body += [
'<tr><td><a href="', page['dotdot'], escape(chain.name), '/block/',
abe.store.hashout_hex(hash),
'">', height, '</a>'
'</td><td>', miner_address,
'</td><td>', format_time(int(nTime)),
'</td><td>', num_tx,
#'</td><td>', format_satoshis(value_out, chain),
#'</td><td>', util.calculate_difficulty(int(nBits)),
#'</td><td>', format_satoshis(satoshis, chain),
#'</td><td>', avg_age,
'</td><td>', '%5g' % (seconds / 86400.0),
#'</td><td>', percent_destroyed,
['</td><td>', '%8g' % ss,
'</td><td>', '%8g' % total_ss] if extra else '',
'</td></tr>\n']
# MULTICHAIN END
body += ['</table>\n<p>', nav, '</p>\n']
def _show_block(abe, page, dotdotblock, chain, **kwargs):
body = page['body']
try:
b = abe.store.export_block(chain, **kwargs)
except DataStore.MalformedHash:
body += ['<p class="error">Not in correct format.</p>']
return
if b is None:
body += ['<p class="error">Block not found.</p>']
return
in_longest = False
for cc in b['chain_candidates']:
if chain is None:
chain = cc['chain']
if chain.id == cc['chain'].id:
in_longest = cc['in_longest']
if in_longest:
# MULTICHAIN START
page['title'] = [escape(chain.name), ' - Block ', b['height']]
page['h1'] = ['<a href="', page['dotdot'], escape(chain.name), '/chain',
'?hi=', b['height'], '">',
escape(chain.name), '</a> ', b['height']]
else:
page['title'] = ['Block ', b['hash'][:4], '...', b['hash'][-10:]]
# body += abe.short_link(page, 'b/' + block_shortlink(b['hash']))
# MULTICHAIN END
is_stake_chain = chain.has_feature('nvc_proof_of_stake')
is_stake_block = is_stake_chain and b['is_proof_of_stake']
# MULTICHAIN START
try:
blockjson = abe.store.get_block_by_hash(chain, b['hash'])
except Exception as e:
body += ['<div class="alert alert-danger" role="warning">', e ,'</div>']
return
if b['hashPrev'] is not None or b['next_block_hashes'] is not None:
body += ['<nav><ul class="pager">']
if b['hashPrev'] is not None:
body += ['<li class="previous"><a href="', dotdotblock,
b['hashPrev'], '"><span aria-hidden="true">←</span> Older</a></li>']
if b['next_block_hashes']:
body += ['<li class="next"><a href="', dotdotblock, b['next_block_hashes'][0], '">Newer<span aria-hidden="true">→</span></a></li>']
body += ['</ul></nav>']
body += ['<h3>Block Summary</h3>\n']
body += ['<table class="table table-bordered table-condensed">']
if is_stake_chain:
body += html_keyvalue_tablerow('Proof of Stake' if is_stake_block else 'Proof of Work', format_satoshis(b['generated'], chain), ' coins generated')
body += html_keyvalue_tablerow('Hash', b['hash'])
if b['hashPrev'] is not None:
body += html_keyvalue_tablerow('Previous Block', '<a href="', dotdotblock,
b['hashPrev'], '">', b['hashPrev'], '</a>')
if b['next_block_hashes']:
body += ['<tr><td>Next Block</td>']
for hash in b['next_block_hashes']:
body += ['<td><a href="', dotdotblock, hash, '">', hash, '</a></td>']
if b['next_block_hashes']:
body += ['</tr>']
body += html_keyvalue_tablerow('Height', b['height'] if b['height'] is not None else '')
miner_txout = b['transactions'][0]['out'][0]
# MULTICHAIN START
if miner_txout['binaddr'] is not None:
miner_address = abe.format_addresses(miner_txout, page['dotdot'], chain)