subseed.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 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. subseed: Subseed classes and methods for the MMGen suite
  20. """
  21. from .color import green
  22. from .util import msg_r,msg,qmsg,die
  23. from .obj import MMGenRange,IndexedDict
  24. from .seed import *
  25. from .crypto import scramble_seed
  26. class SubSeedIdxRange(MMGenRange):
  27. min_idx = 1
  28. max_idx = 1000000
  29. class SubSeedIdx(str,Hilite,InitErrors):
  30. color = 'red'
  31. trunc_ok = False
  32. def __new__(cls,s):
  33. if type(s) == cls:
  34. return s
  35. try:
  36. assert isinstance(s,str),'not a string or string subclass'
  37. idx = s[:-1] if s[-1] in 'SsLl' else s
  38. from .util import is_int
  39. assert is_int(idx),"valid format: an integer, plus optional letter 'S','s','L' or 'l'"
  40. idx = int(idx)
  41. assert idx >= SubSeedIdxRange.min_idx, f'subseed index < {SubSeedIdxRange.min_idx:,}'
  42. assert idx <= SubSeedIdxRange.max_idx, f'subseed index > {SubSeedIdxRange.max_idx:,}'
  43. sstype,ltr = ('short','S') if s[-1] in 'Ss' else ('long','L')
  44. me = str.__new__(cls,str(idx)+ltr)
  45. me.idx = idx
  46. me.type = sstype
  47. return me
  48. except Exception as e:
  49. return cls.init_fail(e,s)
  50. class SubSeed(SeedBase):
  51. idx = ImmutableAttr(int,typeconv=False)
  52. nonce = ImmutableAttr(int,typeconv=False)
  53. ss_idx = ImmutableAttr(SubSeedIdx)
  54. max_nonce = 1000
  55. def __init__(self,parent_list,idx,nonce,length):
  56. self.idx = idx
  57. self.nonce = nonce
  58. self.ss_idx = str(idx) + { 'long': 'L', 'short': 'S' }[length]
  59. self.parent_list = parent_list
  60. SeedBase.__init__(self,seed_bin=type(self).make_subseed_bin(parent_list,idx,nonce,length))
  61. @staticmethod
  62. def make_subseed_bin(parent_list,idx:int,nonce:int,length:str):
  63. seed = parent_list.parent_seed
  64. short = { 'short': True, 'long': False }[length]
  65. # field maximums: idx: 4294967295 (1000000), nonce: 65535 (1000), short: 255 (1)
  66. scramble_key = idx.to_bytes(4,'big') + nonce.to_bytes(2,'big') + short.to_bytes(1,'big')
  67. return scramble_seed(seed.data,scramble_key)[:16 if short else seed.byte_len]
  68. class SubSeedList(MMGenObject):
  69. have_short = True
  70. nonce_start = 0
  71. debug_last_share_sid_len = 3
  72. dfl_len = 100
  73. def __init__(self,parent_seed,length=None):
  74. self.member_type = SubSeed
  75. self.parent_seed = parent_seed
  76. self.data = { 'long': IndexedDict(), 'short': IndexedDict() }
  77. self.len = length or self.dfl_len
  78. def __len__(self):
  79. return len(self.data['long'])
  80. def get_subseed_by_ss_idx(self,ss_idx_in,print_msg=False):
  81. ss_idx = SubSeedIdx(ss_idx_in)
  82. if print_msg:
  83. msg_r('{} {} of {}...'.format(
  84. green('Generating subseed'),
  85. ss_idx.hl(),
  86. self.parent_seed.sid.hl(),
  87. ))
  88. if ss_idx.idx > len(self):
  89. self._generate(ss_idx.idx)
  90. sid = self.data[ss_idx.type].key(ss_idx.idx-1)
  91. idx,nonce = self.data[ss_idx.type][sid]
  92. if idx != ss_idx.idx:
  93. die(3, "{} != {}: self.data[{t!r}].key(i) does not match self.data[{t!r}][i]!".format(
  94. idx,
  95. ss_idx.idx,
  96. t = ss_idx.type ))
  97. if print_msg:
  98. msg(f'\b\b\b => {SeedID.hlc(sid)}')
  99. seed = self.member_type(self,idx,nonce,length=ss_idx.type)
  100. assert seed.sid == sid, f'{seed.sid} != {sid}: Seed ID mismatch!'
  101. return seed
  102. def get_subseed_by_seed_id(self,sid,last_idx=None,print_msg=False):
  103. def get_existing_subseed_by_seed_id(sid):
  104. for k in ('long','short') if self.have_short else ('long',):
  105. if sid in self.data[k]:
  106. idx,nonce = self.data[k][sid]
  107. return self.member_type(self,idx,nonce,length=k)
  108. def do_msg(subseed):
  109. if print_msg:
  110. qmsg('{} {} ({}:{})'.format(
  111. green('Found subseed'),
  112. subseed.sid.hl(),
  113. self.parent_seed.sid.hl(),
  114. subseed.ss_idx.hl(),
  115. ))
  116. if last_idx == None:
  117. last_idx = self.len
  118. subseed = get_existing_subseed_by_seed_id(sid)
  119. if subseed:
  120. do_msg(subseed)
  121. return subseed
  122. if len(self) >= last_idx:
  123. return None
  124. self._generate(last_idx,last_sid=sid)
  125. subseed = get_existing_subseed_by_seed_id(sid)
  126. if subseed:
  127. do_msg(subseed)
  128. return subseed
  129. def _collision_debug_msg(self,sid,idx,nonce,nonce_desc='nonce',debug_last_share=False):
  130. slen = 'short' if sid in self.data['short'] else 'long'
  131. m1 = f'add_subseed(idx={idx},{slen}):'
  132. if sid == self.parent_seed.sid:
  133. m2 = f'collision with parent Seed ID {sid},'
  134. else:
  135. if debug_last_share:
  136. sl = self.debug_last_share_sid_len
  137. colliding_idx = [d[:sl] for d in self.data[slen].keys].index(sid[:sl]) + 1
  138. sid = sid[:sl]
  139. else:
  140. colliding_idx = self.data[slen][sid][0]
  141. m2 = f'collision with ID {sid} (idx={colliding_idx},{slen}),'
  142. msg(f'{m1:30} {m2:46} incrementing {nonce_desc} to {nonce+1}')
  143. def _generate(self,last_idx=None,last_sid=None):
  144. if last_idx == None:
  145. last_idx = self.len
  146. first_idx = len(self) + 1
  147. if first_idx > last_idx:
  148. return None
  149. if last_sid != None:
  150. last_sid = SeedID(sid=last_sid)
  151. def add_subseed(idx,length):
  152. for nonce in range(self.nonce_start,self.member_type.max_nonce+1): # handle SeedID collisions
  153. sid = make_chksum_8(self.member_type.make_subseed_bin(self,idx,nonce,length))
  154. if sid in self.data['long'] or sid in self.data['short'] or sid == self.parent_seed.sid:
  155. from .globalvars import g
  156. if g.debug_subseed: # should get ≈450 collisions for first 1,000,000 subseeds
  157. self._collision_debug_msg(sid,idx,nonce)
  158. else:
  159. self.data[length][sid] = (idx,nonce)
  160. return last_sid == sid
  161. else: # must exit here, as this could leave self.data in inconsistent state
  162. die( 'SubSeedNonceRangeExceeded', 'add_subseed(): nonce range exceeded' )
  163. for idx in SubSeedIdxRange(first_idx,last_idx).iterate():
  164. match1 = add_subseed(idx,'long')
  165. match2 = add_subseed(idx,'short') if self.have_short else False
  166. if match1 or match2:
  167. break
  168. def format(self,first_idx,last_idx):
  169. r = SubSeedIdxRange(first_idx,last_idx)
  170. if len(self) < last_idx:
  171. self._generate(last_idx)
  172. fs1 = '{:>18} {:>18}\n'
  173. fs2 = '{i:>7}L: {:8} {i:>7}S: {:8}\n'
  174. hdr = f' Parent Seed: {self.parent_seed.sid.hl()} ({self.parent_seed.bitlen} bits)\n\n'
  175. hdr += fs1.format('Long Subseeds','Short Subseeds')
  176. hdr += fs1.format('-------------','--------------')
  177. sl = self.data['long'].keys
  178. ss = self.data['short'].keys
  179. body = (fs2.format( sl[n-1], ss[n-1], i=n ) for n in r.iterate())
  180. return hdr + ''.join(body)