Skip to content

Instantly share code, notes, and snippets.

@sbp
Created March 9, 2014 22:41
Show Gist options
  • Save sbp/9456050 to your computer and use it in GitHub Desktop.
Save sbp/9456050 to your computer and use it in GitHub Desktop.
Parse a BIP32 encoded wallet from stdin
#!/usr/bin/env python3
# Parse a BIP32 encoded wallet from stdin
import sys
import base58
# https://raw.github.com/kylegibson/python-bitcoin-client/master/base58.py
def error(message):
print("E:", message, file=sys.stderr)
sys.exit(1)
def format(octets):
return "".join("%02x" % octet for octet in octets)
def main():
octets = sys.stdin.buffer.read()
while octets[-1] in {b"\r", b"\n"}:
octets = octets[:-1]
if octets[:4] in {b"xprv", b"xpub", b"tprv", b"tpub"}:
octets = base58.b58decode(octets.decode("ascii"), 82)
octets = bytes(ord(c) for c in octets)
octets, checksum = octets[:-4], octets[-4:]
else:
checksum = None
if len(octets) != 78:
message = "Incorrect BIP32 wallet size: expected 78 bytes, got %s bytes"
error(message % len(octets))
version, octets = octets[:4], octets[4:]
node, octets = octets[:1], octets[1:]
fingerprint, octets = octets[:4], octets[4:]
child, octets = octets[:4], octets[4:]
chain, key = octets[:32], octets[32:]
print("version:", format(version))
print("node:", format(node))
print("fingerprint:", format(fingerprint))
print("child:", format(child))
print("chain:", format(chain))
print("key:", format(key))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment