Skip to content

Commit 406f35d

Browse files
committed
Merge #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)
2 parents cfe41d7 + 3c8f63b commit 406f35d

File tree

4 files changed

+97
-37
lines changed

4 files changed

+97
-37
lines changed

contrib/linearize/README.md

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

45
## Step 1: Download hash list
56

67
$ ./linearize-hashes.py linearize.cfg > hashlist.txt
78

89
Required configuration file settings for linearize-hashes:
9-
* RPC: rpcuser, rpcpassword
10+
* RPC: `rpcuser`, `rpcpassword`
1011

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

1525
## Step 2: Copy local block data
1626

1727
$ ./linearize-data.py linearize.cfg
1828

1929
Required configuration file settings:
20-
* "input": bitcoind blocks/ directory containing blkNNNNN.dat
21-
* "hashlist": text file containing list of block hashes, linearized-hashes.py
22-
output.
23-
* "output_file": bootstrap.dat
30+
* `output_file`: The file that will contain the final blockchain.
2431
or
25-
* "output": output directory for linearized blocks/blkNNNNN.dat output
32+
* `output`: Output directory for linearized `blocks/blkNNNNN.dat` output.
2633

2734
Optional config file setting for linearize-data:
28-
* "netmagic": network magic number
29-
* "max_out_sz": maximum output file size (default `1000*1000*1000`)
30-
* "split_timestamp": Split files when a new month is first seen, in addition to
31-
reaching a maximum file size.
32-
* "file_timestamp": Set each file's last-modified time to that of the
33-
most recent block in that file.
35+
* `file_timestamp`: Set each file's last-modified time to that of the most
36+
recent block in that file.
37+
* `genesis`: The hash of the genesis block in the blockchain.
38+
* `input`: bitcoind blocks/ directory containing blkNNNNN.dat
39+
* `hashlist`: text file containing list of block hashes created by
40+
linearize-hashes.py.
41+
* `max_out_sz`: Maximum size for files created by the `output_file` option.
42+
(Default: `1000*1000*1000 bytes`)
43+
* `netmagic`: Network magic number.
44+
* `rev_hash_bytes`: If true, the block hash list written by linearize-hashes.py
45+
will be byte-reversed when read by linearize-data.py. See the linearize-hashes
46+
entry for more information.
47+
* `split_timestamp`: Split blockchain files when a new month is first seen, in
48+
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
@@ -23,7 +23,9 @@ input=/home/example/.bitcoin/blocks
2323

2424
output_file=/home/example/Downloads/bootstrap.dat
2525
hashlist=hashlist.txt
26-
split_year=1
2726

2827
# Maxmimum size in bytes of out-of-order blocks cache in memory
2928
out_of_order_cache_sz = 100000000
29+
30+
# Do we want the reverse the hash bytes coming from getblockhash?
31+
rev_hash_bytes = False

contrib/linearize/linearize-data.py

Lines changed: 31 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,23 +8,33 @@
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 datetime
2124
import time
2225
from collections import namedtuple
26+
from binascii import hexlify, unhexlify
2327

2428
settings = {}
2529

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

2939
def bytereverse(x):
3040
return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) |
@@ -35,14 +45,14 @@ def bufreverse(in_buf):
3545
for i in range(0, len(in_buf), 4):
3646
word = struct.unpack('@I', in_buf[i:i+4])[0]
3747
out_words.append(struct.pack('@I', bytereverse(word)))
38-
return ''.join(out_words)
48+
return b''.join(out_words)
3949

4050
def wordreverse(in_buf):
4151
out_words = []
4252
for i in range(0, len(in_buf), 4):
4353
out_words.append(in_buf[i:i+4])
4454
out_words.reverse()
45-
return ''.join(out_words)
55+
return b''.join(out_words)
4656

4757
def calc_hdr_hash(blk_hdr):
4858
hash1 = hashlib.sha256()
@@ -59,7 +69,7 @@ def calc_hash_str(blk_hdr):
5969
hash = calc_hdr_hash(blk_hdr)
6070
hash = bufreverse(hash)
6171
hash = wordreverse(hash)
62-
hash_str = hash.encode('hex')
72+
hash_str = hexlify(hash).decode('utf-8')
6373
return hash_str
6474

6575
def get_blk_dt(blk_hdr):
@@ -69,17 +79,21 @@ def get_blk_dt(blk_hdr):
6979
dt_ym = datetime.datetime(dt.year, dt.month, 1)
7080
return (dt_ym, nTime)
7181

82+
# When getting the list of block hashes, undo any byte reversals.
7283
def get_block_hashes(settings):
7384
blkindex = []
7485
f = open(settings['hashlist'], "r")
7586
for line in f:
7687
line = line.rstrip()
88+
if settings['rev_hash_bytes'] == 'true':
89+
line = hex_switchEndian(line)
7790
blkindex.append(line)
7891

7992
print("Read " + str(len(blkindex)) + " hashes")
8093

8194
return blkindex
8295

96+
# The block map shouldn't give or receive byte-reversed hashes.
8397
def mkblockmap(blkindex):
8498
blkmap = {}
8599
for height,hash in enumerate(blkindex):
@@ -207,7 +221,7 @@ def run(self):
207221

208222
inMagic = inhdr[:4]
209223
if (inMagic != self.settings['netmagic']):
210-
print("Invalid magic: " + inMagic.encode('hex'))
224+
print("Invalid magic: " + hexlify(inMagic).decode('utf-8'))
211225
return
212226
inLenLE = inhdr[4:]
213227
su = struct.unpack("<I", inLenLE)
@@ -265,6 +279,12 @@ def run(self):
265279
settings[m.group(1)] = m.group(2)
266280
f.close()
267281

282+
# Force hash byte format setting to be lowercase to make comparisons easier.
283+
# Also place upfront in case any settings need to know about it.
284+
if 'rev_hash_bytes' not in settings:
285+
settings['rev_hash_bytes'] = 'false'
286+
settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()
287+
268288
if 'netmagic' not in settings:
269289
settings['netmagic'] = 'f9beb4d9'
270290
if 'genesis' not in settings:
@@ -278,14 +298,14 @@ def run(self):
278298
if 'split_timestamp' not in settings:
279299
settings['split_timestamp'] = 0
280300
if 'max_out_sz' not in settings:
281-
settings['max_out_sz'] = 1000L * 1000 * 1000
301+
settings['max_out_sz'] = 1000 * 1000 * 1000
282302
if 'out_of_order_cache_sz' not in settings:
283303
settings['out_of_order_cache_sz'] = 100 * 1000 * 1000
284304

285-
settings['max_out_sz'] = long(settings['max_out_sz'])
305+
settings['max_out_sz'] = int(settings['max_out_sz'])
286306
settings['split_timestamp'] = int(settings['split_timestamp'])
287307
settings['file_timestamp'] = int(settings['file_timestamp'])
288-
settings['netmagic'] = settings['netmagic'].decode('hex')
308+
settings['netmagic'] = unhexlify(settings['netmagic'].encode('utf-8'))
289309
settings['out_of_order_cache_sz'] = int(settings['out_of_order_cache_sz'])
290310

291311
if 'output_file' not in settings and 'output' not in settings:
@@ -295,9 +315,8 @@ def run(self):
295315
blkindex = get_block_hashes(settings)
296316
blkmap = mkblockmap(blkindex)
297317

318+
# Block hash map won't be byte-reversed. Neither should the genesis hash.
298319
if not settings['genesis'] in blkmap:
299320
print("Genesis block not found in hashlist")
300321
else:
301322
BlockDataCopier(settings, blkindex, blkmap).run()
302-
303-

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)