|
| 1 | +"""Base58 encoding |
| 2 | +
|
| 3 | +Implementations of Base58 and Base58Check encodings that are compatible |
| 4 | +with the bitcoin network. |
| 5 | +
|
| 6 | +This file was copied over and added to the bip32 project from David Keijser's https://github.com/keis/base58 (https://pypi.org/project/base58/). This |
| 7 | +package is released under an MIT licensed. The code was copied in this file and left untouched. Here is a copy of the MIT license accompanying the |
| 8 | +code: |
| 9 | + Copyright (c) 2015 David Keijser |
| 10 | +
|
| 11 | + Permission is hereby granted, free of charge, to any person obtaining a copy |
| 12 | + of this software and associated documentation files (the "Software"), to deal |
| 13 | + in the Software without restriction, including without limitation the rights |
| 14 | + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 15 | + copies of the Software, and to permit persons to whom the Software is |
| 16 | + furnished to do so, subject to the following conditions: |
| 17 | +
|
| 18 | + The above copyright notice and this permission notice shall be included in |
| 19 | + all copies or substantial portions of the Software. |
| 20 | +
|
| 21 | + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 22 | + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 23 | + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 24 | + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 25 | + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 26 | + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 27 | + THE SOFTWARE. |
| 28 | +""" |
| 29 | + |
| 30 | +# This module is based upon base58 snippets found scattered over many bitcoin |
| 31 | +# tools written in python. From what I gather the original source is from a |
| 32 | +# forum post by Gavin Andresen, so direct your praise to him. |
| 33 | +# This module adds shiny packaging and support for python3. |
| 34 | + |
| 35 | +from functools import lru_cache |
| 36 | +from hashlib import sha256 |
| 37 | +from typing import Mapping, Union |
| 38 | + |
| 39 | +# 58 character alphabet used |
| 40 | +BITCOIN_ALPHABET = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" |
| 41 | +RIPPLE_ALPHABET = b"rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz" |
| 42 | +XRP_ALPHABET = RIPPLE_ALPHABET |
| 43 | + |
| 44 | +# Retro compatibility |
| 45 | +alphabet = BITCOIN_ALPHABET |
| 46 | + |
| 47 | + |
| 48 | +def scrub_input(v: Union[str, bytes]) -> bytes: |
| 49 | + if isinstance(v, str): |
| 50 | + v = v.encode("ascii") |
| 51 | + |
| 52 | + return v |
| 53 | + |
| 54 | + |
| 55 | +def b58encode_int( |
| 56 | + i: int, default_one: bool = True, alphabet: bytes = BITCOIN_ALPHABET |
| 57 | +) -> bytes: |
| 58 | + """ |
| 59 | + Encode an integer using Base58 |
| 60 | + """ |
| 61 | + if not i and default_one: |
| 62 | + return alphabet[0:1] |
| 63 | + string = b"" |
| 64 | + base = len(alphabet) |
| 65 | + while i: |
| 66 | + i, idx = divmod(i, base) |
| 67 | + string = alphabet[idx : idx + 1] + string |
| 68 | + return string |
| 69 | + |
| 70 | + |
| 71 | +def b58encode(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET) -> bytes: |
| 72 | + """ |
| 73 | + Encode a string using Base58 |
| 74 | + """ |
| 75 | + v = scrub_input(v) |
| 76 | + |
| 77 | + origlen = len(v) |
| 78 | + v = v.lstrip(b"\0") |
| 79 | + newlen = len(v) |
| 80 | + |
| 81 | + acc = int.from_bytes(v, byteorder="big") # first byte is most significant |
| 82 | + |
| 83 | + result = b58encode_int(acc, default_one=False, alphabet=alphabet) |
| 84 | + return alphabet[0:1] * (origlen - newlen) + result |
| 85 | + |
| 86 | + |
| 87 | +@lru_cache() |
| 88 | +def _get_base58_decode_map(alphabet: bytes, autofix: bool) -> Mapping[int, int]: |
| 89 | + invmap = {char: index for index, char in enumerate(alphabet)} |
| 90 | + |
| 91 | + if autofix: |
| 92 | + groups = [b"0Oo", b"Il1"] |
| 93 | + for group in groups: |
| 94 | + pivots = [c for c in group if c in invmap] |
| 95 | + if len(pivots) == 1: |
| 96 | + for alternative in group: |
| 97 | + invmap[alternative] = invmap[pivots[0]] |
| 98 | + |
| 99 | + return invmap |
| 100 | + |
| 101 | + |
| 102 | +def b58decode_int( |
| 103 | + v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False |
| 104 | +) -> int: |
| 105 | + """ |
| 106 | + Decode a Base58 encoded string as an integer |
| 107 | + """ |
| 108 | + if b" " not in alphabet: |
| 109 | + v = v.rstrip() |
| 110 | + v = scrub_input(v) |
| 111 | + |
| 112 | + map = _get_base58_decode_map(alphabet, autofix=autofix) |
| 113 | + |
| 114 | + decimal = 0 |
| 115 | + base = len(alphabet) |
| 116 | + try: |
| 117 | + for char in v: |
| 118 | + decimal = decimal * base + map[char] |
| 119 | + except KeyError as e: |
| 120 | + raise ValueError("Invalid character {!r}".format(chr(e.args[0]))) from None |
| 121 | + return decimal |
| 122 | + |
| 123 | + |
| 124 | +def b58decode( |
| 125 | + v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False |
| 126 | +) -> bytes: |
| 127 | + """ |
| 128 | + Decode a Base58 encoded string |
| 129 | + """ |
| 130 | + v = v.rstrip() |
| 131 | + v = scrub_input(v) |
| 132 | + |
| 133 | + origlen = len(v) |
| 134 | + v = v.lstrip(alphabet[0:1]) |
| 135 | + newlen = len(v) |
| 136 | + |
| 137 | + acc = b58decode_int(v, alphabet=alphabet, autofix=autofix) |
| 138 | + |
| 139 | + return acc.to_bytes(origlen - newlen + (acc.bit_length() + 7) // 8, "big") |
| 140 | + |
| 141 | + |
| 142 | +def b58encode_check(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET) -> bytes: |
| 143 | + """ |
| 144 | + Encode a string using Base58 with a 4 character checksum |
| 145 | + """ |
| 146 | + v = scrub_input(v) |
| 147 | + |
| 148 | + digest = sha256(sha256(v).digest()).digest() |
| 149 | + return b58encode(v + digest[:4], alphabet=alphabet) |
| 150 | + |
| 151 | + |
| 152 | +def b58decode_check( |
| 153 | + v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False |
| 154 | +) -> bytes: |
| 155 | + """Decode and verify the checksum of a Base58 encoded string""" |
| 156 | + |
| 157 | + result = b58decode(v, alphabet=alphabet, autofix=autofix) |
| 158 | + result, check = result[:-4], result[-4:] |
| 159 | + digest = sha256(sha256(result).digest()).digest() |
| 160 | + |
| 161 | + if check != digest[:4]: |
| 162 | + raise ValueError("Invalid checksum") |
| 163 | + |
| 164 | + return result |
0 commit comments