baseconv.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. baseconv.py: base conversion class for the MMGen suite
  20. """
  21. from hashlib import sha256
  22. from .exception import *
  23. from .util import die
  24. def is_b58_str(s):
  25. return set(list(s)) <= set(baseconv.digits['b58'])
  26. def is_b32_str(s):
  27. return set(list(s)) <= set(baseconv.digits['b32'])
  28. class baseconv(object):
  29. desc = {
  30. 'b58': ('base58', 'base58-encoded data'),
  31. 'b32': ('MMGen base32', 'MMGen base32-encoded data created using simple base conversion'),
  32. 'b16': ('hexadecimal string','base16 (hexadecimal) string data'),
  33. 'b10': ('base10 string', 'base10 (decimal) string data'),
  34. 'b8': ('base8 string', 'base8 (octal) string data'),
  35. 'b6d': ('base6d (die roll)', 'base6 data using the digits from one to six'),
  36. # 'tirosh':('Tirosh mnemonic', 'base1626 mnemonic using truncated Tirosh wordlist'), # not used by wallet
  37. 'mmgen': ('MMGen native mnemonic',
  38. 'MMGen native mnemonic seed phrase created using old Electrum wordlist and simple base conversion'),
  39. }
  40. # https://en.wikipedia.org/wiki/Base32#RFC_4648_Base32_alphabet
  41. # https://tools.ietf.org/html/rfc4648
  42. digits = {
  43. 'b58': tuple('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'),
  44. 'b32': tuple('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), # RFC 4648 alphabet
  45. 'b16': tuple('0123456789abcdef'),
  46. 'b10': tuple('0123456789'),
  47. 'b8': tuple('01234567'),
  48. 'b6d': tuple('123456'),
  49. }
  50. mn_base = 1626
  51. wl_chksums = {
  52. 'mmgen': '5ca31424',
  53. # 'tirosh': '48f05e1f', # tirosh truncated to mn_base
  54. # 'tirosh1633': '1a5faeff' # tirosh list is 1633 words long!
  55. }
  56. seedlen_map = {
  57. 'b58': { 16:22, 24:33, 32:44 },
  58. 'b6d': { 16:50, 24:75, 32:100 },
  59. 'mmgen': { 16:12, 24:18, 32:24 },
  60. }
  61. seedlen_map_rev = {
  62. 'b58': { 22:16, 33:24, 44:32 },
  63. 'b6d': { 50:16, 75:24, 100:32 },
  64. 'mmgen': { 12:16, 18:24, 24:32 },
  65. }
  66. def __init__(self,wl_id):
  67. if wl_id == 'mmgen':
  68. from .mn_electrum import words
  69. self.digits[wl_id] = words
  70. elif wl_id not in self.digits:
  71. raise ValueError(f'{wl_id}: unrecognized mnemonic ID')
  72. self.wl_id = wl_id
  73. def get_wordlist(self):
  74. return self.digits[self.wl_id]
  75. def get_wordlist_chksum(self):
  76. return sha256(' '.join(self.digits[self.wl_id]).encode()).hexdigest()[:8]
  77. def check_wordlist(self):
  78. wl = self.digits[self.wl_id]
  79. from .util import qmsg,compare_chksums
  80. ret = f'Wordlist: {self.wl_id}\nLength: {len(wl)} words'
  81. new_chksum = self.get_wordlist_chksum()
  82. compare_chksums(
  83. new_chksum,
  84. 'generated',
  85. self.wl_chksums[self.wl_id],
  86. 'saved',
  87. die_on_fail = True )
  88. if tuple(sorted(wl)) == wl:
  89. return ret + '\nList is sorted'
  90. else:
  91. die(3,'ERROR: List is not sorted!')
  92. @staticmethod
  93. def get_pad(pad,seed_pad_func):
  94. """
  95. 'pad' argument to baseconv conversion methods must be either None, 'seed' or an integer.
  96. If None, output of minimum (but never zero) length will be produced.
  97. If 'seed', output length will be mapped from input length using data in seedlen_map.
  98. If an integer, the string, hex string or byte output will be padded to this length.
  99. """
  100. if pad == None:
  101. return 0
  102. elif type(pad) == int:
  103. return pad
  104. elif pad == 'seed':
  105. return seed_pad_func()
  106. else:
  107. raise BaseConversionPadError(f"{pad!r}: illegal value for 'pad' (must be None,'seed' or int)")
  108. def tohex(self,words_arg,pad=None):
  109. "convert string or list data of instance base to hex string"
  110. return self.tobytes(words_arg,pad//2 if type(pad)==int else pad).hex()
  111. def tobytes(self,words_arg,pad=None):
  112. "convert string or list data of instance base to byte string"
  113. words = words_arg if isinstance(words_arg,(list,tuple)) else tuple(words_arg.strip())
  114. desc = self.desc[self.wl_id][0]
  115. if len(words) == 0:
  116. raise BaseConversionError(f'empty {desc} data')
  117. def get_seed_pad():
  118. assert self.wl_id in self.seedlen_map_rev, f'seed padding not supported for base {self.wl_id!r}'
  119. d = self.seedlen_map_rev[self.wl_id]
  120. if not len(words) in d:
  121. raise BaseConversionError(
  122. f'{len(words)}: invalid length for seed-padded {desc} data in base conversion' )
  123. return d[len(words)]
  124. pad_val = max(self.get_pad(pad,get_seed_pad),1)
  125. wl = self.digits[self.wl_id]
  126. base = len(wl)
  127. if not set(words) <= set(wl):
  128. raise BaseConversionError(
  129. ( 'seed data' if pad == 'seed' else f'{words_arg!r}:' ) +
  130. f' not in {desc} format' )
  131. ret = sum([wl.index(words[::-1][i])*(base**i) for i in range(len(words))])
  132. bl = ret.bit_length()
  133. return ret.to_bytes(max(pad_val,bl//8+bool(bl%8)),'big')
  134. def fromhex(self,hexstr,pad=None,tostr=False):
  135. "convert hex string to list or string data of instance base"
  136. from .util import is_hex_str
  137. if not is_hex_str(hexstr):
  138. raise HexadecimalStringError(
  139. ( 'seed data' if pad == 'seed' else f'{hexstr!r}:' ) +
  140. ' not a hexadecimal string' )
  141. return self.frombytes( bytes.fromhex(hexstr), pad, tostr )
  142. def frombytes(self,bytestr,pad=None,tostr=False):
  143. "convert byte string to list or string data of instance base"
  144. if not bytestr:
  145. raise BaseConversionError('empty data not allowed in base conversion')
  146. def get_seed_pad():
  147. assert self.wl_id in self.seedlen_map, f'seed padding not supported for base {self.wl_id!r}'
  148. d = self.seedlen_map[self.wl_id]
  149. if not len(bytestr) in d:
  150. raise SeedLengthError(
  151. f'{len(bytestr)}: invalid byte length for seed data in seed-padded base conversion' )
  152. return d[len(bytestr)]
  153. pad = max(self.get_pad(pad,get_seed_pad),1)
  154. wl = self.digits[self.wl_id]
  155. def gen():
  156. num = int.from_bytes(bytestr,'big')
  157. base = len(wl)
  158. while num:
  159. yield num % base
  160. num //= base
  161. ret = list(gen())
  162. o = [wl[n] for n in [0] * (pad-len(ret)) + ret[::-1]]
  163. return (' ' if self.wl_id == 'mmgen' else '').join(o) if tostr else o