Skip to content

Commit 07ace7e

Browse files
authored
Merge pull request #18 from martinholy/base58_decode_fix
Fix: Incorrect output of Base58 decoding.
2 parents 98b15fd + 749bf8c commit 07ace7e

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

hdwallet/libs/base58.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,15 +67,18 @@ def decode(data):
6767
data = bytes(data, "ascii")
6868

6969
val = 0
70-
for (i, c) in enumerate(data[::-1]):
71-
val += __base58_alphabet_bytes.find(c) * (__base58_radix ** i)
70+
prefix = 0
71+
for c in data:
72+
val = (val * __base58_radix) + __base58_alphabet_bytes.find(c)
73+
if val == 0:
74+
prefix += 1
7275

7376
dec = bytearray()
74-
while val >= 256:
77+
while val > 0:
7578
val, mod = divmod(val, 256)
7679
dec.append(mod)
77-
if val:
78-
dec.append(val)
80+
81+
dec.extend(bytearray(prefix))
7982

8083
return bytes(dec[::-1])
8184

tests/test_base58.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import pytest
88

99
from hdwallet.libs.base58 import (
10-
check_encode, check_decode, string_to_int
10+
check_encode, check_decode, decode, encode, string_to_int
1111
)
1212

1313

@@ -29,3 +29,9 @@ def test_base58():
2929

3030
with pytest.raises(TypeError, match="string argument without an encoding"):
3131
assert string_to_int(str("meherett"))
32+
33+
34+
assert decode("111233QC4") == b'\x00\x00\x00(\x7f\xb4\xcd'
35+
36+
37+
assert encode(decode("111233QC4")) == "111233QC4"

0 commit comments

Comments
 (0)