Skip to content

Commit 3c8f63b

Browse files
droarkDouglas Roark
authored andcommitted
Make linearize scripts Python 3-compatible.
1 parent d5aa198 commit 3c8f63b

File tree

3 files changed

+47
-26
lines changed

3 files changed

+47
-26
lines changed

contrib/linearize/README.md

Lines changed: 9 additions & 4 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 Bitcoin 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

@@ -9,28 +10,32 @@ Required configuration file settings for linearize-hashes:
910
* RPC: `rpcuser`, `rpcpassword`
1011

1112
Optional config file setting for linearize-hashes:
12-
* RPC: `host`, `port` (Default: `127.0.0.1:8332`)
13+
* RPC: `host` (Default: `127.0.0.1`)
14+
* RPC: `port` (Default: `8332`)
1315
* Blockchain: `min_height`, `max_height`
1416
* `rev_hash_bytes`: If true, the written block hash list will be
1517
byte-reversed. (In other words, the hash returned by getblockhash will have its
1618
bytes reversed.) False by default. Intended for generation of
1719
standalone hash lists but safe to use with linearize-data.py, which will output
1820
the same data no matter which byte format is chosen.
1921

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.
24+
2025
## Step 2: Copy local block data
2126

2227
$ ./linearize-data.py linearize.cfg
2328

2429
Required configuration file settings:
2530
* `output_file`: The file that will contain the final blockchain.
2631
or
27-
* `output`: Output directory for linearized blocks/blkNNNNN.dat output.
32+
* `output`: Output directory for linearized `blocks/blkNNNNN.dat` output.
2833

2934
Optional config file setting for linearize-data:
3035
* `file_timestamp`: Set each file's last-modified time to that of the most
3136
recent block in that file.
3237
* `genesis`: The hash of the genesis block in the blockchain.
33-
* `input: bitcoind blocks/ directory containing blkNNNNN.dat
38+
* `input`: bitcoind blocks/ directory containing blkNNNNN.dat
3439
* `hashlist`: text file containing list of block hashes created by
3540
linearize-hashes.py.
3641
* `max_out_sz`: Maximum size for files created by the `output_file` option.

contrib/linearize/linearize-data.py

Lines changed: 16 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,29 +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

2630
##### Switch endian-ness #####
2731
def hex_switchEndian(s):
2832
""" Switches the endianness of a hex string (in pairs of hex chars) """
29-
pairList = [s[i]+s[i+1] for i in range(0,len(s),2)]
30-
return ''.join(pairList[::-1])
33+
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
34+
return b''.join(pairList[::-1]).decode()
3135

3236
def uint32(x):
33-
return x & 0xffffffffL
37+
return x & 0xffffffff
3438

3539
def bytereverse(x):
3640
return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) |
@@ -41,14 +45,14 @@ def bufreverse(in_buf):
4145
for i in range(0, len(in_buf), 4):
4246
word = struct.unpack('@I', in_buf[i:i+4])[0]
4347
out_words.append(struct.pack('@I', bytereverse(word)))
44-
return ''.join(out_words)
48+
return b''.join(out_words)
4549

4650
def wordreverse(in_buf):
4751
out_words = []
4852
for i in range(0, len(in_buf), 4):
4953
out_words.append(in_buf[i:i+4])
5054
out_words.reverse()
51-
return ''.join(out_words)
55+
return b''.join(out_words)
5256

5357
def calc_hdr_hash(blk_hdr):
5458
hash1 = hashlib.sha256()
@@ -65,7 +69,7 @@ def calc_hash_str(blk_hdr):
6569
hash = calc_hdr_hash(blk_hdr)
6670
hash = bufreverse(hash)
6771
hash = wordreverse(hash)
68-
hash_str = hash.encode('hex')
72+
hash_str = hexlify(hash).decode('utf-8')
6973
return hash_str
7074

7175
def get_blk_dt(blk_hdr):
@@ -217,7 +221,7 @@ def run(self):
217221

218222
inMagic = inhdr[:4]
219223
if (inMagic != self.settings['netmagic']):
220-
print("Invalid magic: " + inMagic.encode('hex'))
224+
print("Invalid magic: " + hexlify(inMagic).decode('utf-8'))
221225
return
222226
inLenLE = inhdr[4:]
223227
su = struct.unpack("<I", inLenLE)
@@ -294,14 +298,14 @@ def run(self):
294298
if 'split_timestamp' not in settings:
295299
settings['split_timestamp'] = 0
296300
if 'max_out_sz' not in settings:
297-
settings['max_out_sz'] = 1000L * 1000 * 1000
301+
settings['max_out_sz'] = 1000 * 1000 * 1000
298302
if 'out_of_order_cache_sz' not in settings:
299303
settings['out_of_order_cache_sz'] = 100 * 1000 * 1000
300304

301-
settings['max_out_sz'] = long(settings['max_out_sz'])
305+
settings['max_out_sz'] = int(settings['max_out_sz'])
302306
settings['split_timestamp'] = int(settings['split_timestamp'])
303307
settings['file_timestamp'] = int(settings['file_timestamp'])
304-
settings['netmagic'] = settings['netmagic'].decode('hex')
308+
settings['netmagic'] = unhexlify(settings['netmagic'].encode('utf-8'))
305309
settings['out_of_order_cache_sz'] = int(settings['out_of_order_cache_sz'])
306310

307311
if 'output_file' not in settings and 'output' not in settings:

contrib/linearize/linearize-hashes.py

Lines changed: 22 additions & 10 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,38 +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

2023
##### Switch endian-ness #####
2124
def hex_switchEndian(s):
2225
""" Switches the endianness of a hex string (in pairs of hex chars) """
23-
pairList = [s[i]+s[i+1] for i in range(0,len(s),2)]
24-
return ''.join(pairList[::-1])
26+
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
27+
return b''.join(pairList[::-1]).decode()
2528

2629
class BitcoinRPC:
2730
def __init__(self, host, port, username, password):
2831
authpair = "%s:%s" % (username, password)
29-
self.authhdr = "Basic %s" % (base64.b64encode(authpair))
30-
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)
3135

3236
def execute(self, obj):
33-
self.conn.request('POST', '/', json.dumps(obj),
34-
{ 'Authorization' : self.authhdr,
35-
'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
3645

3746
resp = self.conn.getresponse()
3847
if resp is None:
3948
print("JSON-RPC: no response", file=sys.stderr)
4049
return None
4150

42-
body = resp.read()
51+
body = resp.read().decode('utf-8')
4352
resp_obj = json.loads(body)
4453
return resp_obj
4554

@@ -70,6 +79,9 @@ def get_block_hashes(settings, max_blocks_per_call=10000):
7079
batch.append(rpc.build_request(x, 'getblockhash', [height + x]))
7180

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

7486
for x,resp_obj in enumerate(reply):
7587
if rpc.response_is_error(resp_obj):

0 commit comments

Comments
 (0)