Skip to content

Commit 737380e

Browse files
Martino Salvettidgpv
authored andcommitted
Add python2 support to bech32
1 parent 01083b7 commit 737380e

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

bitcoin/segwit_addr.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@
2020

2121
"""Reference implementation for Bech32 and segwit addresses."""
2222

23+
import sys
24+
_bchr = chr
25+
_bord = lambda x: ord(x) if isinstance(x, str) else x
26+
if sys.version > '3':
27+
long = int
28+
_bchr = lambda x: bytes([x])
29+
_bord = lambda x: x
2330

2431
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
2532

@@ -85,6 +92,7 @@ def convertbits(data, frombits, tobits, pad=True):
8592
maxv = (1 << tobits) - 1
8693
max_acc = (1 << (frombits + tobits - 1)) - 1
8794
for value in data:
95+
value = _bord(value)
8896
if value < 0 or (value >> frombits):
8997
return None
9098
acc = ((acc << frombits) | value) & max_acc

bitcoin/tests/test_bech32.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@
1414
import json
1515
import os
1616
import unittest
17+
import array
18+
import sys
19+
_bchr = chr
20+
_bord = ord
21+
_tobytes = lambda x: array.array('B', x).tostring()
22+
if sys.version > '3':
23+
long = int
24+
_bchr = lambda x: bytes([x])
25+
_bord = lambda x: x
26+
_tobytes = bytes
1727

1828
from binascii import unhexlify
1929

@@ -28,7 +38,7 @@ def load_test_vectors(name):
2838

2939
def to_scriptPubKey(witver, witprog):
3040
"""Decoded bech32 address to script"""
31-
return CScript([witver]) + CScript(bytes(witprog))
41+
return CScript([witver]) + CScript(_tobytes(witprog))
3242

3343
class Test_bech32(unittest.TestCase):
3444

@@ -42,15 +52,15 @@ def op_decode(self, witver):
4252

4353
def test_encode_decode(self):
4454
for exp_bin, exp_bech32 in load_test_vectors('bech32_encode_decode.json'):
45-
exp_bin = unhexlify(exp_bin.encode('utf8'))
55+
exp_bin = [_bord(y) for y in unhexlify(exp_bin.encode('utf8'))]
4656
witver = self.op_decode(exp_bin[0])
4757
hrp = exp_bech32[:exp_bech32.rindex('1')].lower()
4858
self.assertEqual(exp_bin[1], len(exp_bin[2:]))
4959
act_bech32 = encode(hrp, witver, exp_bin[2:])
5060
act_bin = decode(hrp, exp_bech32)
5161

5262
self.assertEqual(act_bech32.lower(), exp_bech32.lower())
53-
self.assertEqual(to_scriptPubKey(*act_bin), exp_bin)
63+
self.assertEqual(to_scriptPubKey(*act_bin), _tobytes(exp_bin))
5464

5565
class Test_CBech32Data(unittest.TestCase):
5666
def test_from_data(self):

0 commit comments

Comments
 (0)