Skip to content

Instantly share code, notes, and snippets.

@ymgve
Created May 26, 2019 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymgve/12fd16e7330aa508368377194aff6376 to your computer and use it in GitHub Desktop.
Save ymgve/12fd16e7330aa508368377194aff6376 to your computer and use it in GitHub Desktop.
import hashlib
b58ab = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def b58csum(s):
return hashlib.sha256(hashlib.sha256(s).digest()).digest()[0:4]
def b58decode(s, checksum=True):
idx = 0
while s[idx] == "1":
idx += 1
n = 0
for c in s[idx:]:
n = n * 58 + b58ab.index(c)
res = long2byte(n)
res = idx * "\x00" + res
if checksum:
res, cs = res[:-4], res[-4:]
assert cs == b58csum(res), "base58 checksum failed"
return res
def b58encode(s, checksum=True):
if checksum:
s += b58csum(s)
idx = 0
while s[idx] == "\x00":
idx += 1
n = byte2long(s)
res = ""
while n > 0:
res = b58ab[n % 58] + res
n /= 58
return "1" * idx + res
def byte2long(s):
res = 0
for c in s:
res = (res << 8) | ord(c)
return res
def long2byte(n, sz=None):
res = ""
while n > 0:
res = chr(n & 0xff) + res
n >>= 8
if sz is not None:
res = res.rjust(sz, "\x00")
return res
uncompressed = "5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss"
key = b58decode(uncompressed) # also removes checksum bytes
key += "\x01"
compressed = b58encode(key) # adds checksum
assert compressed == "L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1"
print compressed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment