baseconv.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 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 mmgen.exception import *
  23. def is_b58_str(s): return set(list(s)) <= set(baseconv.digits['b58'])
  24. def is_b32_str(s): return set(list(s)) <= set(baseconv.digits['b32'])
  25. class baseconv(object):
  26. desc = {
  27. 'b58': ('base58', 'base58-encoded data'),
  28. 'b32': ('MMGen base32', 'MMGen base32-encoded data created using simple base conversion'),
  29. 'b16': ('hexadecimal string','base16 (hexadecimal) string data'),
  30. 'b10': ('base10 string', 'base10 (decimal) string data'),
  31. 'b8': ('base8 string', 'base8 (octal) string data'),
  32. 'b6d': ('base6d (die roll)', 'base6 data using the digits from one to six'),
  33. 'tirosh':('Tirosh mnemonic', 'base1626 mnemonic using truncated Tirosh wordlist'), # not used by wallet
  34. 'mmgen': ('MMGen native mnemonic',
  35. 'MMGen native mnemonic seed phrase data created using old Electrum wordlist and simple base conversion'),
  36. }
  37. # https://en.wikipedia.org/wiki/Base32#RFC_4648_Base32_alphabet
  38. # https://tools.ietf.org/html/rfc4648
  39. digits = {
  40. 'b58': tuple('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'),
  41. 'b32': tuple('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), # RFC 4648 alphabet
  42. 'b16': tuple('0123456789abcdef'),
  43. 'b10': tuple('0123456789'),
  44. 'b8': tuple('01234567'),
  45. 'b6d': tuple('123456'),
  46. }
  47. mn_base = 1626 # tirosh list is 1633 words long!
  48. wl_chksums = {
  49. 'mmgen': '5ca31424',
  50. 'tirosh': '48f05e1f', # tirosh truncated to mn_base (1626)
  51. # 'tirosh1633': '1a5faeff'
  52. }
  53. seedlen_map = {
  54. 'b58': { 16:22, 24:33, 32:44 },
  55. 'b6d': { 16:50, 24:75, 32:100 },
  56. 'mmgen': { 16:12, 24:18, 32:24 },
  57. }
  58. seedlen_map_rev = {
  59. 'b58': { 22:16, 33:24, 44:32 },
  60. 'b6d': { 50:16, 75:24, 100:32 },
  61. 'mmgen': { 12:16, 18:24, 24:32 },
  62. }
  63. @classmethod
  64. def init_mn(cls,mn_id):
  65. if mn_id in cls.digits:
  66. return
  67. if mn_id == 'mmgen':
  68. from mmgen.mn_electrum import words
  69. cls.digits[mn_id] = words
  70. elif mn_id == 'tirosh':
  71. from mmgen.mn_tirosh import words
  72. cls.digits[mn_id] = words[:cls.mn_base]
  73. else:
  74. raise ValueError('{}: unrecognized mnemonic ID'.format(mn_id))
  75. @classmethod
  76. def get_wordlist(cls,wl_id):
  77. cls.init_mn(wl_id)
  78. return cls.digits[wl_id]
  79. @classmethod
  80. def get_wordlist_chksum(cls,wl_id):
  81. cls.init_mn(wl_id)
  82. return sha256(' '.join(cls.digits[wl_id]).encode()).hexdigest()[:8]
  83. @classmethod
  84. def check_wordlists(cls):
  85. for k,v in list(cls.wl_chksums.items()):
  86. res = cls.get_wordlist_chksum(k)
  87. assert res == v,'{}: checksum mismatch for {} (should be {})'.format(res,k,v)
  88. @classmethod
  89. def check_wordlist(cls,wl_id):
  90. cls.init_mn(wl_id)
  91. wl = cls.digits[wl_id]
  92. from mmgen.util import qmsg,compare_chksums
  93. qmsg('Wordlist: {}\nLength: {} words'.format(wl_id,len(wl)))
  94. new_chksum = cls.get_wordlist_chksum(wl_id)
  95. a,b = 'generated','saved'
  96. compare_chksums(new_chksum,a,cls.wl_chksums[wl_id],b,die_on_fail=True)
  97. qmsg('List is sorted') if tuple(sorted(wl)) == wl else die(3,'ERROR: List is not sorted!')
  98. @classmethod
  99. def get_pad(cls,pad,seed_pad_func):
  100. """
  101. 'pad' argument to baseconv conversion methods must be either None, 'seed' or an integer.
  102. If None, output of minimum (but never zero) length will be produced.
  103. If 'seed', output length will be mapped from input length using data in seedlen_map.
  104. If an integer, the string, hex string or byte output will be padded to this length.
  105. """
  106. if pad == None:
  107. return 0
  108. elif type(pad) == int:
  109. return pad
  110. elif pad == 'seed':
  111. return seed_pad_func()
  112. else:
  113. m = "{!r}: illegal value for 'pad' (must be None,'seed' or int)"
  114. raise BaseConversionPadError(m.format(pad))
  115. @classmethod
  116. def tohex(cls,words_arg,wl_id,pad=None):
  117. "convert string or list data of base 'wl_id' to hex string"
  118. return cls.tobytes(words_arg,wl_id,pad//2 if type(pad)==int else pad).hex()
  119. @classmethod
  120. def tobytes(cls,words_arg,wl_id,pad=None):
  121. "convert string or list data of base 'wl_id' to byte string"
  122. if wl_id not in cls.digits:
  123. cls.init_mn(wl_id)
  124. words = words_arg if isinstance(words_arg,(list,tuple)) else tuple(words_arg.strip())
  125. desc = cls.desc[wl_id][0]
  126. if len(words) == 0:
  127. raise BaseConversionError('empty {} data'.format(desc))
  128. def get_seed_pad():
  129. assert wl_id in cls.seedlen_map_rev,'seed padding not supported for base {!r}'.format(wl_id)
  130. d = cls.seedlen_map_rev[wl_id]
  131. if not len(words) in d:
  132. m = '{}: invalid length for seed-padded {} data in base conversion'
  133. raise BaseConversionError(m.format(len(words),desc))
  134. return d[len(words)]
  135. pad_val = max(cls.get_pad(pad,get_seed_pad),1)
  136. wl = cls.digits[wl_id]
  137. base = len(wl)
  138. if not set(words) <= set(wl):
  139. m = ('{w!r}:','seed data')[pad=='seed'] + ' not in {d} format'
  140. raise BaseConversionError(m.format(w=words_arg,d=desc))
  141. ret = sum([wl.index(words[::-1][i])*(base**i) for i in range(len(words))])
  142. bl = ret.bit_length()
  143. return ret.to_bytes(max(pad_val,bl//8+bool(bl%8)),'big')
  144. @classmethod
  145. def fromhex(cls,hexstr,wl_id,pad=None,tostr=False):
  146. "convert hex string to list or string data of base 'wl_id'"
  147. from mmgen.util import is_hex_str
  148. if not is_hex_str(hexstr):
  149. m = ('{h!r}:','seed data')[pad=='seed'] + ' not a hexadecimal string'
  150. raise HexadecimalStringError(m.format(h=hexstr))
  151. return cls.frombytes(bytes.fromhex(hexstr),wl_id,pad,tostr)
  152. @classmethod
  153. def frombytes(cls,bytestr,wl_id,pad=None,tostr=False):
  154. "convert byte string to list or string data of base 'wl_id'"
  155. if wl_id not in cls.digits:
  156. cls.init_mn(wl_id)
  157. if not bytestr:
  158. raise BaseConversionError('empty data not allowed in base conversion')
  159. def get_seed_pad():
  160. assert wl_id in cls.seedlen_map,'seed padding not supported for base {!r}'.format(wl_id)
  161. d = cls.seedlen_map[wl_id]
  162. if not len(bytestr) in d:
  163. m = '{}: invalid byte length for seed data in seed-padded base conversion'
  164. raise SeedLengthError(m.format(len(bytestr)))
  165. return d[len(bytestr)]
  166. pad = max(cls.get_pad(pad,get_seed_pad),1)
  167. wl = cls.digits[wl_id]
  168. base = len(wl)
  169. num = int.from_bytes(bytestr,'big')
  170. ret = []
  171. while num:
  172. ret.append(num % base)
  173. num //= base
  174. o = [wl[n] for n in [0] * (pad-len(ret)) + ret[::-1]]
  175. return ''.join(o) if tostr else o