The character \x04
Posted: Sat Dec 28, 2013 8:42 pm
I'm currently in the process of porting py bitcointools to lisp. I'm having trouble with this section:
I'm not sure how to express the character \x04 in lisp. On one hand, it seems kind of arbitrary, so I could in theory replace it with something else, but on the other hand I want to maintain consistency. So how do I express it?
...it doesn't just mean '4', does it?
Code: Select all
def get_pubkey_format(pub):
if isinstance(pub,(tuple,list)): return 'decimal'
elif len(pub) == 65 and pub[0] == '\x04': return 'bin'
elif len(pub) == 130 and pub[0:2] == '04': return 'hex'
elif len(pub) == 33 and pub[0] in ['\x02','\x03']: return 'bin_compressed'
elif len(pub) == 66 and pub[0:2] in ['02','03']: return 'hex_compressed'
elif len(pub) == 64: return 'bin_electrum'
elif len(pub) == 128: return 'hex_electrum'
else: raise Exception("Pubkey not in recognized format")
def encode_pubkey(pub,formt):
if not isinstance(pub,(tuple,list)):
pub = decode_pubkey(pub)
if formt == 'decimal': return pub
elif formt == 'bin': return '\x04' + encode(pub[0],256,32) + encode(pub[1],256,32)
elif formt == 'bin_compressed': return chr(2+(pub[1]%2)) + encode(pub[0],256,32)
elif formt == 'hex': return '04' + encode(pub[0],16,64) + encode(pub[1],16,64)
elif formt == 'hex_compressed': return '0'+str(2+(pub[1]%2)) + encode(pub[0],16,64)
elif formt == 'bin_electrum': return encode(pub[0],256,32) + encode(pub[1],256,32)
elif formt == 'hex_electrum': return encode(pub[0],16,64) + encode(pub[1],16,64)
else: raise Exception("Invalid format!")
def decode_pubkey(pub,formt=None):
if not formt: formt = get_pubkey_format(pub)
if formt == 'decimal': return pub
elif formt == 'bin': return (decode(pub[1:33],256),decode(pub[33:65],256))
elif formt == 'bin_compressed':
x = decode(pub[1:33],256)
beta = pow(x*x*x+7,(P+1)/4,P)
y = (P-beta) if ((beta + ord(pub[0])) % 2) else beta
return (x,y)
elif formt == 'hex': return (decode(pub[2:66],16),decode(pub[66:130],16))
elif formt == 'hex_compressed':
return decode_pubkey(pub.decode('hex'),'bin_compressed')
elif formt == 'bin_electrum':
return (decode(pub[:32],256),decode(pub[32:64],256))
elif formt == 'hex_electrum':
return (decode(pub[:64],16),decode(pub[64:128],16))
else: raise Exception("Invalid format!")
...it doesn't just mean '4', does it?