Skip to content

Commit 882e2cd

Browse files
laanwjcodablock
authored andcommitted
Merge bitcoin#9373: Linearize script update (hash byte reversal and Python 3 support)
3c8f63b Make linearize scripts Python 3-compatible. (Doug) d5aa198 Allow linearization scripts to support hash byte reversal (Doug)
1 parent 718e622 commit 882e2cd

File tree

4 files changed

+99
-37
lines changed

4 files changed

+99
-37
lines changed

contrib/linearize/README.md

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Linearize
2-
Construct a linear, no-fork, best version of the blockchain.
2+
Construct a linear, no-fork, best version of the Dash blockchain. The scripts
3+
run using Python 3 but are compatible with Python 2.
34

45
## Step 0: Install dash_hash
56

@@ -10,27 +11,42 @@ https://github.com/dashpay/dash_hash
1011
$ ./linearize-hashes.py linearize.cfg > hashlist.txt
1112

1213
Required configuration file settings for linearize-hashes:
13-
* RPC: rpcuser, rpcpassword
14+
* RPC: `rpcuser`, `rpcpassword`
1415

1516
Optional config file setting for linearize-hashes:
16-
* RPC: host, port
17-
* Block chain: min_height, max_height
17+
* RPC: `host` (Default: `127.0.0.1`)
18+
* RPC: `port` (Default: `9998`)
19+
* Blockchain: `min_height`, `max_height`
20+
* `rev_hash_bytes`: If true, the written block hash list will be
21+
byte-reversed. (In other words, the hash returned by getblockhash will have its
22+
bytes reversed.) False by default. Intended for generation of
23+
standalone hash lists but safe to use with linearize-data.py, which will output
24+
the same data no matter which byte format is chosen.
25+
26+
The `linearize-hashes` script requires a connection, local or remote, to a
27+
JSON-RPC server. Running `bitcoind` or `bitcoin-qt -server` will be sufficient.
1828

1929
## Step 2: Copy local block data
2030

2131
$ ./linearize-data.py linearize.cfg
2232

2333
Required configuration file settings:
24-
* "input": bitcoind blocks/ directory containing blkNNNNN.dat
25-
* "hashlist": text file containing list of block hashes, linearized-hashes.py
26-
output.
27-
* "output_file" for bootstrap.dat or "output" for output directory for linearized blocks/blkNNNNN.dat output
34+
* `output_file`: The file that will contain the final blockchain.
35+
or
36+
* `output`: Output directory for linearized `blocks/blkNNNNN.dat` output.
2837

2938
Optional config file setting for linearize-data:
30-
* "netmagic": network magic number (default is 'cee2caff', testnet)
31-
* "genesis": genesis block hash (default is '00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c', testnet)
32-
* "max_out_sz": maximum output file size (default 100 \* 1000 \* 1000)
33-
* "split_timestamp": Split files when a new month is first seen, in addition to
34-
reaching a maximum file size.
35-
* "file_timestamp": Set each file's last-modified time to that of the
36-
most recent block in that file.
39+
* `file_timestamp`: Set each file's last-modified time to that of the most
40+
recent block in that file.
41+
* `genesis`: The hash of the genesis block in the blockchain. (default is '00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c', testnet)
42+
* `input`: bitcoind blocks/ directory containing blkNNNNN.dat
43+
* `hashlist`: text file containing list of block hashes created by
44+
linearize-hashes.py.
45+
* `max_out_sz`: Maximum size for files created by the `output_file` option.
46+
(Default: `1000*1000*1000 bytes`)
47+
* `netmagic`: Network magic number. (default is 'cee2caff', testnet)
48+
* `rev_hash_bytes`: If true, the block hash list written by linearize-hashes.py
49+
will be byte-reversed when read by linearize-data.py. See the linearize-hashes
50+
entry for more information.
51+
* `split_timestamp`: Split blockchain files when a new month is first seen, in
52+
addition to reaching a maximum file size (`max_out_sz`).

contrib/linearize/example-linearize.cfg

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@ netmagic=bf0c6bbd
1313
input=/home/example/.dashcore/blocks
1414
output_file=/home/example/Downloads/bootstrap.dat
1515
hashlist=hashlist.txt
16-
split_year=1
1716
genesis=00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6
1817

1918
# Maxmimum size in bytes of out-of-order blocks cache in memory
2019
out_of_order_cache_sz = 10000000
20+
21+
# Do we want the reverse the hash bytes coming from getblockhash?
22+
rev_hash_bytes = False

contrib/linearize/linearize-data.py

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
#
33
# linearize-data.py: Construct a linear, no-fork version of the chain.
44
#
@@ -8,24 +8,34 @@
88
#
99

1010
from __future__ import print_function, division
11+
try: # Python 3
12+
import http.client as httplib
13+
except ImportError: # Python 2
14+
import httplib
1115
import json
1216
import struct
1317
import re
1418
import os
1519
import os.path
1620
import base64
17-
import httplib
1821
import sys
1922
import hashlib
2023
import dash_hash
2124
import datetime
2225
import time
2326
from collections import namedtuple
27+
from binascii import hexlify, unhexlify
2428

2529
settings = {}
2630

31+
##### Switch endian-ness #####
32+
def hex_switchEndian(s):
33+
""" Switches the endianness of a hex string (in pairs of hex chars) """
34+
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
35+
return b''.join(pairList[::-1]).decode()
36+
2737
def uint32(x):
28-
return x & 0xffffffffL
38+
return x & 0xffffffff
2939

3040
def bytereverse(x):
3141
return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) |
@@ -36,14 +46,14 @@ def bufreverse(in_buf):
3646
for i in range(0, len(in_buf), 4):
3747
word = struct.unpack('@I', in_buf[i:i+4])[0]
3848
out_words.append(struct.pack('@I', bytereverse(word)))
39-
return ''.join(out_words)
49+
return b''.join(out_words)
4050

4151
def wordreverse(in_buf):
4252
out_words = []
4353
for i in range(0, len(in_buf), 4):
4454
out_words.append(in_buf[i:i+4])
4555
out_words.reverse()
46-
return ''.join(out_words)
56+
return b''.join(out_words)
4757

4858
def calc_hdr_hash(blk_hdr):
4959
#hash1 = hashlib.sha256()
@@ -62,7 +72,7 @@ def calc_hash_str(blk_hdr):
6272
hash = calc_hdr_hash(blk_hdr)
6373
hash = bufreverse(hash)
6474
hash = wordreverse(hash)
65-
hash_str = hash.encode('hex')
75+
hash_str = hexlify(hash).decode('utf-8')
6676
return hash_str
6777

6878
def get_blk_dt(blk_hdr):
@@ -72,17 +82,21 @@ def get_blk_dt(blk_hdr):
7282
dt_ym = datetime.datetime(dt.year, dt.month, 1)
7383
return (dt_ym, nTime)
7484

85+
# When getting the list of block hashes, undo any byte reversals.
7586
def get_block_hashes(settings):
7687
blkindex = []
7788
f = open(settings['hashlist'], "r")
7889
for line in f:
7990
line = line.rstrip()
91+
if settings['rev_hash_bytes'] == 'true':
92+
line = hex_switchEndian(line)
8093
blkindex.append(line)
8194

8295
print("Read " + str(len(blkindex)) + " hashes")
8396

8497
return blkindex
8598

99+
# The block map shouldn't give or receive byte-reversed hashes.
86100
def mkblockmap(blkindex):
87101
blkmap = {}
88102
for height,hash in enumerate(blkindex):
@@ -210,7 +224,7 @@ def run(self):
210224

211225
inMagic = inhdr[:4]
212226
if (inMagic != self.settings['netmagic']):
213-
print("Invalid magic: " + inMagic.encode('hex'))
227+
print("Invalid magic: " + hexlify(inMagic).decode('utf-8'))
214228
return
215229
inLenLE = inhdr[4:]
216230
su = struct.unpack("<I", inLenLE)
@@ -268,10 +282,16 @@ def run(self):
268282
settings[m.group(1)] = m.group(2)
269283
f.close()
270284

285+
# Force hash byte format setting to be lowercase to make comparisons easier.
286+
# Also place upfront in case any settings need to know about it.
287+
if 'rev_hash_bytes' not in settings:
288+
settings['rev_hash_bytes'] = 'false'
289+
settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()
290+
271291
if 'netmagic' not in settings:
272292
settings['netmagic'] = 'cee2caff'
273293
if 'genesis' not in settings:
274-
settings['genesis'] = '00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c'
294+
settings['genesis'] = '00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6'
275295
if 'input' not in settings:
276296
settings['input'] = 'input'
277297
if 'hashlist' not in settings:
@@ -281,14 +301,14 @@ def run(self):
281301
if 'split_timestamp' not in settings:
282302
settings['split_timestamp'] = 0
283303
if 'max_out_sz' not in settings:
284-
settings['max_out_sz'] = 1000L * 1000 * 1000
304+
settings['max_out_sz'] = 1000 * 1000 * 1000
285305
if 'out_of_order_cache_sz' not in settings:
286306
settings['out_of_order_cache_sz'] = 100 * 1000 * 1000
287307

288-
settings['max_out_sz'] = long(settings['max_out_sz'])
308+
settings['max_out_sz'] = int(settings['max_out_sz'])
289309
settings['split_timestamp'] = int(settings['split_timestamp'])
290310
settings['file_timestamp'] = int(settings['file_timestamp'])
291-
settings['netmagic'] = settings['netmagic'].decode('hex')
311+
settings['netmagic'] = unhexlify(settings['netmagic'].encode('utf-8'))
292312
settings['out_of_order_cache_sz'] = int(settings['out_of_order_cache_sz'])
293313

294314
if 'output_file' not in settings and 'output' not in settings:
@@ -298,8 +318,8 @@ def run(self):
298318
blkindex = get_block_hashes(settings)
299319
blkmap = mkblockmap(blkindex)
300320

321+
# Block hash map won't be byte-reversed. Neither should the genesis hash.
301322
if not settings['genesis'] in blkmap:
302323
print("Genesis block not found in hashlist")
303324
else:
304325
BlockDataCopier(settings, blkindex, blkmap).run()
305-

contrib/linearize/linearize-hashes.py

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
#
33
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
44
#
@@ -8,32 +8,47 @@
88
#
99

1010
from __future__ import print_function
11+
try: # Python 3
12+
import http.client as httplib
13+
except ImportError: # Python 2
14+
import httplib
1115
import json
1216
import struct
1317
import re
1418
import base64
15-
import httplib
1619
import sys
1720

1821
settings = {}
1922

23+
##### Switch endian-ness #####
24+
def hex_switchEndian(s):
25+
""" Switches the endianness of a hex string (in pairs of hex chars) """
26+
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
27+
return b''.join(pairList[::-1]).decode()
28+
2029
class BitcoinRPC:
2130
def __init__(self, host, port, username, password):
2231
authpair = "%s:%s" % (username, password)
23-
self.authhdr = "Basic %s" % (base64.b64encode(authpair))
24-
self.conn = httplib.HTTPConnection(host, port, False, 30)
32+
authpair = authpair.encode('utf-8')
33+
self.authhdr = b"Basic " + base64.b64encode(authpair)
34+
self.conn = httplib.HTTPConnection(host, port=port, timeout=30)
2535

2636
def execute(self, obj):
27-
self.conn.request('POST', '/', json.dumps(obj),
28-
{ 'Authorization' : self.authhdr,
29-
'Content-type' : 'application/json' })
37+
try:
38+
self.conn.request('POST', '/', json.dumps(obj),
39+
{ 'Authorization' : self.authhdr,
40+
'Content-type' : 'application/json' })
41+
except ConnectionRefusedError:
42+
print('RPC connection refused. Check RPC settings and the server status.',
43+
file=sys.stderr)
44+
return None
3045

3146
resp = self.conn.getresponse()
3247
if resp is None:
3348
print("JSON-RPC: no response", file=sys.stderr)
3449
return None
3550

36-
body = resp.read()
51+
body = resp.read().decode('utf-8')
3752
resp_obj = json.loads(body)
3853
return resp_obj
3954

@@ -64,12 +79,17 @@ def get_block_hashes(settings, max_blocks_per_call=10000):
6479
batch.append(rpc.build_request(x, 'getblockhash', [height + x]))
6580

6681
reply = rpc.execute(batch)
82+
if reply is None:
83+
print('Cannot continue. Program will halt.')
84+
return None
6785

6886
for x,resp_obj in enumerate(reply):
6987
if rpc.response_is_error(resp_obj):
7088
print('JSON-RPC: error at height', height+x, ': ', resp_obj['error'], file=sys.stderr)
7189
exit(1)
7290
assert(resp_obj['id'] == x) # assume replies are in-sequence
91+
if settings['rev_hash_bytes'] == 'true':
92+
resp_obj['result'] = hex_switchEndian(resp_obj['result'])
7393
print(resp_obj['result'])
7494

7595
height += num_blocks
@@ -101,6 +121,8 @@ def get_block_hashes(settings, max_blocks_per_call=10000):
101121
settings['min_height'] = 0
102122
if 'max_height' not in settings:
103123
settings['max_height'] = 313000
124+
if 'rev_hash_bytes' not in settings:
125+
settings['rev_hash_bytes'] = 'false'
104126
if 'rpcuser' not in settings or 'rpcpassword' not in settings:
105127
print("Missing username and/or password in cfg file", file=stderr)
106128
sys.exit(1)
@@ -109,5 +131,7 @@ def get_block_hashes(settings, max_blocks_per_call=10000):
109131
settings['min_height'] = int(settings['min_height'])
110132
settings['max_height'] = int(settings['max_height'])
111133

112-
get_block_hashes(settings)
134+
# Force hash byte format setting to be lowercase to make comparisons easier.
135+
settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()
113136

137+
get_block_hashes(settings)

0 commit comments

Comments
 (0)