Last active
April 5, 2021 13:39
-
-
Save smlu/021103bcc1da9c621998980a31086ce9 to your computer and use it in GitHub Desktop.
Encode public key and signature to EOSIO string format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from binascii import hexlify, unhexlify | |
b58_digits = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' | |
def b58_encode(b): | |
"""Encode bytes to a base58-encoded string""" | |
# Convert big-endian bytes to integer | |
n = int(b, 16) | |
# Divide that integer into bas58 | |
res = [] | |
while n > 0: | |
n, r = divmod (n, 58) | |
res.append(b58_digits[r]) | |
res = ''.join(res[::-1]) | |
# Encode leading zeros as base58 zeros | |
import sys | |
czero = b'\x00' | |
if sys.version > '3': | |
# In Python3 indexing a bytes returns numbers, not characters. | |
czero = 0 | |
pad = 0 | |
for c in b: | |
if c == czero: pad += 1 | |
else: break | |
return b58_digits[0] * pad + res | |
def b58_decode(s): | |
"""Decode a base58-encoding string, returning bytes""" | |
if not s: | |
return b'' | |
# Convert the string to an integer | |
n = 0 | |
for c in s: | |
n *= 58 | |
if c not in b58_digits: | |
raise InvalidBase58Error('Character %r is not a valid base58 character' % c) | |
digit = b58_digits.index(c) | |
n += digit | |
# Convert the integer to bytes | |
h = '%x' % n | |
if len(h) % 2: | |
h = '0' + h | |
res = unhexlify(h.encode('utf8')) | |
# Add padding back. | |
pad = 0 | |
for c in s[:-1]: | |
if c == b58_digits[0]: pad += 1 | |
else: break | |
return hexlify(b'\x00' * pad + res).decode('utf8') | |
def checksum(hexstr): | |
h = hashlib.new('ripemd160') | |
h.update(binascii.unhexlify(hexstr)) | |
return h.hexdigest()[0:8] | |
def make_address_legacy(pubkey): | |
chksum = checksum(pubkey) | |
addr = base58_encoder.encode(pubkey + chksum) | |
return 'EOS' + addr | |
def make_address(key_type, pubkey): | |
if key_type != 'K1' and key_type != 'R1'and key_type != 'WA': | |
raise "Invalid key type" | |
chksum = checksum(pubkey + bytes(key_type, 'utf-8').hex()) | |
return "PUB_{}_{}".format(key_type, base58_encoder.encode(pubkey + chksum)) | |
def encode_sig(sig_type, sig): | |
if sig_type != 'K1' and sig_type != 'R1'and sig_type != 'WA' | |
raise "Invalid sig type" | |
chksum = checksum(sig + bytes(sig_type, 'utf-8').hex()) | |
return "SIG_{}_{}".format(sig_type, base58_encoder.encode(sig + chksum)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment