seed.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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. seed.py: Seed-related classes and methods for the MMGen suite
  20. """
  21. import os
  22. from mmgen.common import *
  23. from mmgen.obj import *
  24. from mmgen.crypto import *
  25. pnm = g.proj_name
  26. def check_usr_seed_len(seed_len):
  27. if opt.seed_len != seed_len and 'seed_len' in opt.set_by_user:
  28. m = "ERROR: requested seed length ({}) doesn't match seed length of source ({})"
  29. die(1,m.format((opt.seed_len,seed_len)))
  30. def is_mnemonic(s):
  31. oq_save = opt.quiet
  32. opt.quiet = True
  33. try:
  34. SeedSource(in_data=s,in_fmt='words')
  35. ret = True
  36. except:
  37. ret = False
  38. finally:
  39. opt.quiet = oq_save
  40. return ret
  41. class SeedBase(MMGenObject):
  42. data = MMGenImmutableAttr('data',bytes,typeconv=False)
  43. hexdata = MMGenImmutableAttr('hexdata',str,typeconv=False)
  44. sid = MMGenImmutableAttr('sid',SeedID,typeconv=False)
  45. length = MMGenImmutableAttr('length',int,typeconv=False)
  46. def __init__(self,seed_bin=None):
  47. if not seed_bin:
  48. # Truncate random data for smaller seed lengths
  49. seed_bin = sha256(get_random(1033)).digest()[:opt.seed_len//8]
  50. elif len(seed_bin)*8 not in g.seed_lens:
  51. die(3,'{}: invalid seed length'.format(len(seed_bin)))
  52. self.data = seed_bin
  53. self.hexdata = seed_bin.hex()
  54. self.sid = SeedID(seed=self)
  55. self.length = len(seed_bin) * 8
  56. class Seed(SeedBase):
  57. def __init__(self,seed_bin=None):
  58. from collections import OrderedDict
  59. self.subseeds = { 'long': OrderedDict(), 'short': OrderedDict() }
  60. SeedBase.__init__(self,seed_bin=seed_bin)
  61. def subseed(self,ss_idx_in,print_msg=False):
  62. ss_idx = SubSeedIdx(ss_idx_in)
  63. if print_msg:
  64. msg_r('{} {} of {}...'.format(
  65. green('Generating subseed'),
  66. ss_idx.hl(),
  67. self.sid.hl(),
  68. ))
  69. if ss_idx.idx > len(self.subseeds['long']):
  70. self.gen_subseeds(ss_idx.idx)
  71. sid = list(self.subseeds[ss_idx.type].keys())[ss_idx.idx-1]
  72. idx,nonce = self.subseeds[ss_idx.type][sid]
  73. if print_msg:
  74. msg('\b\b\b => {}'.format(SeedID.hlc(sid)))
  75. assert idx == ss_idx.idx, "{} != {}: subseed list idx does not match subseed idx!".format(idx,ss_idx.idx)
  76. return SubSeed(self,idx,nonce,length=ss_idx.type)
  77. def existing_subseed_by_seed_id(self,sid):
  78. for k in ('long','short'):
  79. if sid in self.subseeds[k]:
  80. idx,nonce = self.subseeds[k][sid]
  81. return SubSeed(self,idx,nonce,length=k)
  82. def subseed_by_seed_id(self,sid,last_idx=None,print_msg=False):
  83. def do_msg(seed):
  84. if print_msg:
  85. qmsg('{} {} ({}:{})'.format(
  86. green('Found subseed'),
  87. seed.sid.hl(),
  88. self.sid.hl(),
  89. seed.ss_idx.hl(),
  90. ))
  91. if last_idx == None:
  92. last_idx = g.subseeds
  93. seed = self.existing_subseed_by_seed_id(sid)
  94. if seed:
  95. do_msg(seed)
  96. return seed
  97. if len(self.subseeds['long']) >= last_idx:
  98. return None
  99. self.gen_subseeds(last_idx,last_sid=sid)
  100. seed = self.existing_subseed_by_seed_id(sid)
  101. if seed:
  102. do_msg(seed)
  103. return seed
  104. def gen_subseeds(self,last_idx=None,last_sid=None):
  105. if last_idx == None:
  106. last_idx = g.subseeds
  107. first_idx = len(self.subseeds['long']) + 1
  108. if first_idx > last_idx:
  109. return None
  110. if last_sid != None:
  111. last_sid = SeedID(sid=last_sid)
  112. def add_subseed(idx,length):
  113. for nonce in range(SubSeed.max_nonce): # use nonce to handle Seed ID collisions
  114. sid = make_chksum_8(SubSeedBase.make_subseed_bin(self,idx,nonce,length))
  115. if not (sid in self.subseeds['long'] or sid in self.subseeds['short'] or sid == self.sid):
  116. self.subseeds[length][sid] = (idx,nonce)
  117. return last_sid == sid
  118. elif g.debug_subseed: # should get ≈450 collisions for first 1,000,000 subseeds
  119. k = ('long','short')[sid in self.subseeds['short']]
  120. m1 = 'add_subseed(idx={},{}):'.format(idx,length)
  121. if sid == self.sid:
  122. m2 = 'collision with parent Seed ID {},'.format(sid)
  123. else:
  124. m2 = 'collision with ID {} (idx={},{}),'.format(sid,self.subseeds[k][sid][0],k)
  125. msg('{:30} {:46} incrementing nonce to {}'.format(m1,m2,nonce+1))
  126. else: # must exit here, as this could leave self.subseeds in inconsistent state
  127. raise SubSeedNonceRangeExceeded('add_subseed(): nonce range exceeded')
  128. for idx in SubSeedIdxRange(first_idx,last_idx).iterate():
  129. if add_subseed(idx,'long') + add_subseed(idx,'short'):
  130. break
  131. def fmt_subseeds(self,first_idx,last_idx):
  132. r = SubSeedIdxRange(first_idx,last_idx)
  133. if len(self.subseeds['long']) < last_idx:
  134. self.gen_subseeds(last_idx)
  135. fs1 = '{:>18} {:>18}\n'
  136. fs2 = '{i:>7}L: {:8} {i:>7}S: {:8}\n'
  137. hdr = '{:>16} {} ({} bits)\n\n'.format('Parent Seed:',self.sid.hl(),self.length)
  138. hdr += fs1.format('Long Subseeds','Short Subseeds')
  139. hdr += fs1.format('-------------','--------------')
  140. sl = tuple(self.subseeds['long'])
  141. ss = tuple(self.subseeds['short'])
  142. body = (fs2.format(sl[n-1],ss[n-1],i=n) for n in r.iterate())
  143. return hdr + ''.join(body)
  144. class SubSeedBase(MMGenObject):
  145. max_nonce = 1000
  146. @staticmethod
  147. def make_subseed_bin(parent,idx:int,nonce:int,length:str):
  148. short = { 'short': True, 'long': False }[length]
  149. # field maximums: idx: 4294967295, nonce: 65535, short (bool): 255
  150. scramble_key = idx.to_bytes(4,'big',signed=False) + \
  151. nonce.to_bytes(2,'big',signed=False) + \
  152. short.to_bytes(1,'big',signed=False)
  153. byte_len = 16 if short else parent.length // 8
  154. return scramble_seed(parent.data,scramble_key,g.scramble_hash_rounds)[:byte_len]
  155. class SubSeed(SeedBase,SubSeedBase):
  156. idx = MMGenImmutableAttr('idx',int,typeconv=False)
  157. nonce = MMGenImmutableAttr('nonce',int,typeconv=False)
  158. ss_idx = MMGenImmutableAttr('ss_idx',SubSeedIdx,typeconv=False)
  159. def __init__(self,parent,idx,nonce,length):
  160. self.idx = idx
  161. self.nonce = nonce
  162. self.ss_idx = SubSeedIdx(str(idx) + { 'long': 'L', 'short': 'S' }[length])
  163. SeedBase.__init__(self,seed_bin=SubSeedBase.make_subseed_bin(parent,idx,nonce,length))
  164. class SeedSource(MMGenObject):
  165. desc = g.proj_name + ' seed source'
  166. file_mode = 'text'
  167. stdin_ok = False
  168. ask_tty = True
  169. no_tty = False
  170. op = None
  171. require_utf8_input = False
  172. _msg = {}
  173. class SeedSourceData(MMGenObject): pass
  174. def __new__(cls,fn=None,ss=None,seed=None,ignore_in_fmt=False,passchg=False,in_data=None,in_fmt=None):
  175. in_fmt = in_fmt or opt.in_fmt
  176. def die_on_opt_mismatch(opt,sstype):
  177. opt_sstype = cls.fmt_code_to_type(opt)
  178. compare_or_die(
  179. opt_sstype.__name__, 'input format requested on command line',
  180. sstype.__name__, 'input file format'
  181. )
  182. if ss:
  183. sstype = ss.__class__ if passchg else cls.fmt_code_to_type(opt.out_fmt)
  184. me = super(cls,cls).__new__(sstype or Wallet) # default: Wallet
  185. me.seed = ss.seed
  186. me.ss_in = ss
  187. me.op = ('conv','pwchg_new')[bool(passchg)]
  188. elif fn or opt.hidden_incog_input_params:
  189. from mmgen.filename import Filename
  190. if fn:
  191. f = Filename(fn)
  192. else:
  193. # permit comma in filename
  194. fn = ','.join(opt.hidden_incog_input_params.split(',')[:-1])
  195. f = Filename(fn,ftype=IncogWalletHidden)
  196. if in_fmt and not ignore_in_fmt:
  197. die_on_opt_mismatch(in_fmt,f.ftype)
  198. me = super(cls,cls).__new__(f.ftype)
  199. me.infile = f
  200. me.op = ('old','pwchg_old')[bool(passchg)]
  201. elif in_fmt: # Input format
  202. sstype = cls.fmt_code_to_type(in_fmt)
  203. me = super(cls,cls).__new__(sstype)
  204. me.op = ('old','pwchg_old')[bool(passchg)]
  205. else: # Called with no inputs - initialize with random seed
  206. sstype = cls.fmt_code_to_type(opt.out_fmt)
  207. me = super(cls,cls).__new__(sstype or Wallet) # default: Wallet
  208. me.seed = Seed(seed_bin=seed or None)
  209. me.op = 'new'
  210. # die(1,me.seed.sid.hl()) # DEBUG
  211. return me
  212. def __init__(self,fn=None,ss=None,seed=None,ignore_in_fmt=False,passchg=False,in_data=None,in_fmt=None):
  213. self.ssdata = self.SeedSourceData()
  214. self.msg = {}
  215. self.in_data = in_data
  216. for c in reversed(self.__class__.__mro__):
  217. if hasattr(c,'_msg'):
  218. self.msg.update(c._msg)
  219. if hasattr(self,'seed'):
  220. self._encrypt()
  221. return
  222. elif hasattr(self,'infile') or self.in_data or not g.stdin_tty:
  223. self._deformat_once()
  224. self._decrypt_retry()
  225. else:
  226. if not self.stdin_ok:
  227. die(1,'Reading from standard input not supported for {} format'.format(self.desc))
  228. self._deformat_retry()
  229. self._decrypt_retry()
  230. m = ('',', seed length {}'.format(self.seed.length))[self.seed.length!=256]
  231. qmsg('Valid {} for Seed ID {}{}'.format(self.desc,self.seed.sid.hl(),m))
  232. def _get_data(self):
  233. if hasattr(self,'infile'):
  234. self.fmt_data = get_data_from_file(self.infile.name,self.desc,binary=self.file_mode=='binary')
  235. elif self.in_data:
  236. self.fmt_data = self.in_data
  237. else:
  238. self.fmt_data = self._get_data_from_user(self.desc)
  239. def _get_data_from_user(self,desc):
  240. return get_data_from_user(desc)
  241. def _deformat_once(self):
  242. self._get_data()
  243. if not self._deformat():
  244. die(2,'Invalid format for input data')
  245. def _deformat_retry(self):
  246. while True:
  247. self._get_data()
  248. if self._deformat(): break
  249. msg('Trying again...')
  250. def _decrypt_retry(self):
  251. while True:
  252. if self._decrypt(): break
  253. if opt.passwd_file:
  254. die(2,'Passphrase from password file, so exiting')
  255. msg('Trying again...')
  256. @classmethod
  257. def get_subclasses_str(cls): # returns name of calling class too
  258. return cls.__name__ + ' ' + ''.join([c.get_subclasses_str() for c in cls.__subclasses__()])
  259. @classmethod
  260. def get_subclasses_easy(cls,acc=[]):
  261. return [globals()[c] for c in cls.get_subclasses_str().split()]
  262. @classmethod
  263. def get_subclasses(cls): # returns calling class too
  264. def GetSubclassesTree(cls,acc):
  265. acc += [cls]
  266. for c in cls.__subclasses__(): GetSubclassesTree(c,acc)
  267. acc = []
  268. GetSubclassesTree(cls,acc)
  269. return acc
  270. @classmethod
  271. def get_extensions(cls):
  272. return [s.ext for s in cls.get_subclasses() if hasattr(s,'ext')]
  273. @classmethod
  274. def fmt_code_to_type(cls,fmt_code):
  275. if not fmt_code: return None
  276. for c in cls.get_subclasses():
  277. if hasattr(c,'fmt_codes') and fmt_code in c.fmt_codes:
  278. return c
  279. return None
  280. @classmethod
  281. def ext_to_type(cls,ext):
  282. if not ext: return None
  283. for c in cls.get_subclasses():
  284. if hasattr(c,'ext') and ext == c.ext:
  285. return c
  286. return None
  287. @classmethod
  288. def format_fmt_codes(cls):
  289. d = [(c.__name__,('.'+c.ext if c.ext else str(c.ext)),','.join(c.fmt_codes))
  290. for c in cls.get_subclasses()
  291. if hasattr(c,'fmt_codes')]
  292. w = max(len(i[0]) for i in d)
  293. ret = ['{:<{w}} {:<9} {}'.format(a,b,c,w=w) for a,b,c in [
  294. ('Format','FileExt','Valid codes'),
  295. ('------','-------','-----------')
  296. ] + sorted(d)]
  297. return '\n'.join(ret) + ('','-α')[g.debug_utf8] + '\n'
  298. def get_fmt_data(self):
  299. self._format()
  300. return self.fmt_data
  301. def write_to_file(self,outdir='',desc=''):
  302. self._format()
  303. kwargs = {
  304. 'desc': desc or self.desc,
  305. 'ask_tty': self.ask_tty,
  306. 'no_tty': self.no_tty,
  307. 'binary': self.file_mode == 'binary'
  308. }
  309. # write_data_to_file(): outfile with absolute path overrides opt.outdir
  310. if outdir:
  311. of = os.path.abspath(os.path.join(outdir,self._filename()))
  312. write_data_to_file(of if outdir else self._filename(),self.fmt_data,**kwargs)
  313. class SeedSourceUnenc(SeedSource):
  314. def _decrypt_retry(self): pass
  315. def _encrypt(self): pass
  316. def _filename(self):
  317. return '{}[{}]{x}.{}'.format(self.seed.sid,self.seed.length,self.ext,x='-α' if g.debug_utf8 else '')
  318. class SeedSourceEnc(SeedSource):
  319. _msg = {
  320. 'choose_passphrase': """
  321. You must choose a passphrase to encrypt your new {} with.
  322. A key will be generated from your passphrase using a hash preset of '{}'.
  323. Please note that no strength checking of passphrases is performed. For
  324. an empty passphrase, just hit ENTER twice.
  325. """.strip()
  326. }
  327. def _get_hash_preset_from_user(self,hp,desc_suf=''):
  328. # hp=a,
  329. n = ('','old ')[self.op=='pwchg_old']
  330. m,n = (('to accept the default',n),('to reuse the old','new '))[
  331. int(self.op=='pwchg_new')]
  332. fs = "Enter {}hash preset for {}{}{},\n or hit ENTER {} value ('{}'): "
  333. p = fs.format(
  334. n,
  335. ('','new ')[self.op=='new'],
  336. self.desc,
  337. ('',' '+desc_suf)[bool(desc_suf)],
  338. m,
  339. hp
  340. )
  341. while True:
  342. ret = my_raw_input(p)
  343. if ret:
  344. if ret in g.hash_presets.keys():
  345. self.ssdata.hash_preset = ret
  346. return ret
  347. else:
  348. msg('Invalid input. Valid choices are {}'.format(', '.join(sorted(g.hash_presets.keys()))))
  349. else:
  350. self.ssdata.hash_preset = hp
  351. return hp
  352. def _get_hash_preset(self,desc_suf=''):
  353. if hasattr(self,'ss_in') and hasattr(self.ss_in.ssdata,'hash_preset'):
  354. old_hp = self.ss_in.ssdata.hash_preset
  355. if opt.keep_hash_preset:
  356. qmsg("Reusing hash preset '{}' at user request".format(old_hp))
  357. self.ssdata.hash_preset = old_hp
  358. elif 'hash_preset' in opt.set_by_user:
  359. hp = self.ssdata.hash_preset = opt.hash_preset
  360. qmsg("Using hash preset '{}' requested on command line".format(opt.hash_preset))
  361. else: # Prompt, using old value as default
  362. hp = self._get_hash_preset_from_user(old_hp,desc_suf)
  363. if (not opt.keep_hash_preset) and self.op == 'pwchg_new':
  364. m = ("changed to '{}'".format(hp),'unchanged')[hp==old_hp]
  365. qmsg('Hash preset {}'.format(m))
  366. elif 'hash_preset' in opt.set_by_user:
  367. self.ssdata.hash_preset = opt.hash_preset
  368. qmsg("Using hash preset '{}' requested on command line".format(opt.hash_preset))
  369. else:
  370. self._get_hash_preset_from_user(opt.hash_preset,desc_suf)
  371. def _get_new_passphrase(self):
  372. desc = '{}passphrase for {}{}'.format(
  373. ('','new ')[self.op=='pwchg_new'],
  374. ('','new ')[self.op in ('new','conv')],
  375. self.desc
  376. )
  377. if opt.passwd_file:
  378. w = pwfile_reuse_warning()
  379. pw = ' '.join(get_words_from_file(opt.passwd_file,desc,quiet=w))
  380. elif opt.echo_passphrase:
  381. pw = ' '.join(get_words_from_user('Enter {}: '.format(desc)))
  382. else:
  383. for i in range(g.passwd_max_tries):
  384. pw = ' '.join(get_words_from_user('Enter {}: '.format(desc)))
  385. pw2 = ' '.join(get_words_from_user('Repeat passphrase: '))
  386. dmsg('Passphrases: [{}] [{}]'.format(pw,pw2))
  387. if pw == pw2:
  388. vmsg('Passphrases match'); break
  389. else: msg('Passphrases do not match. Try again.')
  390. else:
  391. die(2,'User failed to duplicate passphrase in {} attempts'.format(g.passwd_max_tries))
  392. if pw == '': qmsg('WARNING: Empty passphrase')
  393. self.ssdata.passwd = pw
  394. return pw
  395. def _get_passphrase(self,desc_suf=''):
  396. desc = '{}passphrase for {}{}'.format(
  397. ('','old ')[self.op=='pwchg_old'],
  398. self.desc,
  399. ('',' '+desc_suf)[bool(desc_suf)]
  400. )
  401. if opt.passwd_file:
  402. w = pwfile_reuse_warning()
  403. ret = ' '.join(get_words_from_file(opt.passwd_file,desc,quiet=w))
  404. else:
  405. ret = ' '.join(get_words_from_user('Enter {}: '.format(desc)))
  406. self.ssdata.passwd = ret
  407. def _get_first_pw_and_hp_and_encrypt_seed(self):
  408. d = self.ssdata
  409. self._get_hash_preset()
  410. if hasattr(self,'ss_in') and hasattr(self.ss_in.ssdata,'passwd'):
  411. old_pw = self.ss_in.ssdata.passwd
  412. if opt.keep_passphrase:
  413. d.passwd = old_pw
  414. qmsg('Reusing passphrase at user request')
  415. else:
  416. pw = self._get_new_passphrase()
  417. if self.op == 'pwchg_new':
  418. m = ('changed','unchanged')[pw==old_pw]
  419. qmsg('Passphrase {}'.format(m))
  420. else:
  421. qmsg(self.msg['choose_passphrase'].format(self.desc,d.hash_preset))
  422. self._get_new_passphrase()
  423. d.salt = sha256(get_random(128)).digest()[:g.salt_len]
  424. key = make_key(d.passwd, d.salt, d.hash_preset)
  425. d.key_id = make_chksum_8(key)
  426. d.enc_seed = encrypt_seed(self.seed.data,key)
  427. class Mnemonic (SeedSourceUnenc):
  428. stdin_ok = True
  429. fmt_codes = 'mmwords','words','mnemonic','mnem','mn','m'
  430. desc = 'mnemonic data'
  431. ext = 'mmwords'
  432. mn_lens = [i // 32 * 3 for i in g.seed_lens]
  433. wl_id = 'electrum' # or 'tirosh'
  434. def _get_data_from_user(self,desc):
  435. if not g.stdin_tty:
  436. return get_data_from_user(desc)
  437. from mmgen.term import get_char_raw,get_char
  438. def choose_mn_len():
  439. prompt = 'Choose a mnemonic length: 1) 12 words, 2) 18 words, 3) 24 words: '
  440. urange = [str(i+1) for i in range(len(self.mn_lens))]
  441. while True:
  442. r = get_char('\r'+prompt).decode()
  443. if r in urange: break
  444. msg_r('\r' + ' '*len(prompt) + '\r')
  445. return self.mn_lens[int(r)-1]
  446. while True:
  447. mn_len = choose_mn_len()
  448. prompt = 'Mnemonic length of {} words chosen. OK?'.format(mn_len)
  449. if keypress_confirm(prompt,default_yes=True,no_nl=True): break
  450. wl = baseconv.digits[self.wl_id]
  451. longest_word = max(len(w) for w in wl)
  452. from string import ascii_lowercase
  453. m = 'Enter your {}-word mnemonic, hitting ENTER or SPACE after each word.\n'
  454. m += "Optionally, you may use pad characters. Anything you type that's not a\n"
  455. m += 'lowercase letter will be treated as a “pad character”, i.e. it will simply\n'
  456. m += 'be discarded. Pad characters may be typed before, after, or in the middle\n'
  457. m += "of words. For each word, once you've typed {} characters total (including\n"
  458. m += 'pad characters) a pad character will enter the word.'
  459. msg(m.format(mn_len,longest_word))
  460. def get_word():
  461. s,pad = '',0
  462. while True:
  463. ch = get_char_raw('',num_chars=1).decode()
  464. if ch in '\b\x7f':
  465. if s: s = s[:-1]
  466. elif ch in '\n ':
  467. if s: break
  468. elif ch not in ascii_lowercase:
  469. pad += 1
  470. if s and pad + len(s) > longest_word:
  471. break
  472. else:
  473. s += ch
  474. return s
  475. def in_list(w):
  476. from bisect import bisect_left
  477. idx = bisect_left(wl,w)
  478. return(True,False)[idx == len(wl) or w != wl[idx]]
  479. p = ('Enter word #{}: ','Incorrect entry. Repeat word #{}: ')
  480. words,err = [],0
  481. while len(words) < mn_len:
  482. msg_r('{r}{s}{r}'.format(r='\r',s=' '*40))
  483. if err == 1: time.sleep(0.1)
  484. msg_r(p[err].format(len(words)+1))
  485. s = get_word()
  486. if in_list(s): words.append(s)
  487. err = (1,0)[in_list(s)]
  488. msg('')
  489. qmsg('Mnemonic successfully entered')
  490. return ' '.join(words)
  491. @staticmethod
  492. def _mn2hex_pad(mn): return len(mn) * 8 // 3
  493. @staticmethod
  494. def _hex2mn_pad(hexnum): return len(hexnum) * 3 // 8
  495. def _format(self):
  496. hexseed = self.seed.hexdata
  497. mn = baseconv.fromhex(hexseed,self.wl_id,self._hex2mn_pad(hexseed))
  498. ret = baseconv.tohex(mn,self.wl_id,self._mn2hex_pad(mn))
  499. # Internal error, so just die on fail
  500. compare_or_die(ret,'recomputed seed',hexseed,'original',e='Internal error')
  501. self.ssdata.mnemonic = mn
  502. self.fmt_data = ' '.join(mn) + '\n'
  503. def _deformat(self):
  504. mn = self.fmt_data.split()
  505. if len(mn) not in self.mn_lens:
  506. m = 'Invalid mnemonic ({} words). Valid numbers of words: {}'
  507. msg(m.format(len(mn),', '.join(map(str,self.mn_lens))))
  508. return False
  509. for n,w in enumerate(mn,1):
  510. if w not in baseconv.digits[self.wl_id]:
  511. msg('Invalid mnemonic: word #{} is not in the wordlist'.format(n))
  512. return False
  513. hexseed = baseconv.tohex(mn,self.wl_id,self._mn2hex_pad(mn))
  514. ret = baseconv.fromhex(hexseed,self.wl_id,self._hex2mn_pad(hexseed))
  515. if len(hexseed) * 4 not in g.seed_lens:
  516. msg('Invalid mnemonic (produces too large a number)')
  517. return False
  518. # Internal error, so just die
  519. compare_or_die(' '.join(ret),'recomputed mnemonic',' '.join(mn),'original',e='Internal error')
  520. self.seed = Seed(bytes.fromhex(hexseed))
  521. self.ssdata.mnemonic = mn
  522. check_usr_seed_len(self.seed.length)
  523. return True
  524. class SeedFile (SeedSourceUnenc):
  525. stdin_ok = True
  526. fmt_codes = 'mmseed','seed','s'
  527. desc = 'seed data'
  528. ext = 'mmseed'
  529. def _format(self):
  530. b58seed = baseconv.b58encode(self.seed.data,pad=True)
  531. self.ssdata.chksum = make_chksum_6(b58seed)
  532. self.ssdata.b58seed = b58seed
  533. self.fmt_data = '{} {}\n'.format(self.ssdata.chksum,split_into_cols(4,b58seed))
  534. def _deformat(self):
  535. desc = self.desc
  536. ld = self.fmt_data.split()
  537. if not (7 <= len(ld) <= 12): # 6 <= padded b58 data (ld[1:]) <= 11
  538. msg('Invalid data length ({}) in {}'.format(len(ld),desc))
  539. return False
  540. a,b = ld[0],''.join(ld[1:])
  541. if not is_chksum_6(a):
  542. msg("'{}': invalid checksum format in {}".format(a, desc))
  543. return False
  544. if not is_b58_str(b):
  545. msg("'{}': not a base 58 string, in {}".format(b, desc))
  546. return False
  547. vmsg_r('Validating {} checksum...'.format(desc))
  548. if not compare_chksums(a,'file',make_chksum_6(b),'computed',verbose=True):
  549. return False
  550. ret = baseconv.b58decode(b,pad=True)
  551. if ret == False:
  552. msg('Invalid base-58 encoded seed: {}'.format(val))
  553. return False
  554. self.seed = Seed(ret)
  555. self.ssdata.chksum = a
  556. self.ssdata.b58seed = b
  557. check_usr_seed_len(self.seed.length)
  558. return True
  559. class HexSeedFile(SeedSourceUnenc):
  560. stdin_ok = True
  561. fmt_codes = 'seedhex','hexseed','hex','mmhex'
  562. desc = 'hexadecimal seed data'
  563. ext = 'mmhex'
  564. def _format(self):
  565. h = self.seed.hexdata
  566. self.ssdata.chksum = make_chksum_6(h)
  567. self.ssdata.hexseed = h
  568. self.fmt_data = '{} {}\n'.format(self.ssdata.chksum, split_into_cols(4,h))
  569. def _deformat(self):
  570. desc = self.desc
  571. d = self.fmt_data.split()
  572. try:
  573. d[1]
  574. chk,hstr = d[0],''.join(d[1:])
  575. except:
  576. msg("'{}': invalid {}".format(self.fmt_data.strip(),desc))
  577. return False
  578. if not len(hstr)*4 in g.seed_lens:
  579. msg('Invalid data length ({}) in {}'.format(len(hstr),desc))
  580. return False
  581. if not is_chksum_6(chk):
  582. msg("'{}': invalid checksum format in {}".format(chk, desc))
  583. return False
  584. if not is_hex_str(hstr):
  585. msg("'{}': not a hexadecimal string, in {}".format(hstr, desc))
  586. return False
  587. vmsg_r('Validating {} checksum...'.format(desc))
  588. if not compare_chksums(chk,'file',make_chksum_6(hstr),'computed',verbose=True):
  589. return False
  590. self.seed = Seed(bytes.fromhex(hstr))
  591. self.ssdata.chksum = chk
  592. self.ssdata.hexseed = hstr
  593. check_usr_seed_len(self.seed.length)
  594. return True
  595. class Wallet (SeedSourceEnc):
  596. fmt_codes = 'wallet','w'
  597. desc = g.proj_name + ' wallet'
  598. ext = 'mmdat'
  599. require_utf8_input = True # label is UTF-8
  600. def _get_label_from_user(self,old_lbl=''):
  601. d = "to reuse the label '{}'".format(old_lbl.hl()) if old_lbl else 'for no label'
  602. p = 'Enter a wallet label, or hit ENTER {}: '.format(d)
  603. while True:
  604. msg_r(p)
  605. ret = my_raw_input('')
  606. if ret:
  607. self.ssdata.label = MMGenWalletLabel(ret,on_fail='return')
  608. if self.ssdata.label:
  609. break
  610. else:
  611. msg('Invalid label. Trying again...')
  612. else:
  613. self.ssdata.label = old_lbl or MMGenWalletLabel('No Label')
  614. break
  615. return self.ssdata.label
  616. # nearly identical to _get_hash_preset() - factor?
  617. def _get_label(self):
  618. if hasattr(self,'ss_in') and hasattr(self.ss_in.ssdata,'label'):
  619. old_lbl = self.ss_in.ssdata.label
  620. if opt.keep_label:
  621. qmsg("Reusing label '{}' at user request".format(old_lbl.hl()))
  622. self.ssdata.label = old_lbl
  623. elif opt.label:
  624. qmsg("Using label '{}' requested on command line".format(opt.label.hl()))
  625. lbl = self.ssdata.label = opt.label
  626. else: # Prompt, using old value as default
  627. lbl = self._get_label_from_user(old_lbl)
  628. if (not opt.keep_label) and self.op == 'pwchg_new':
  629. m = ("changed to '{}'".format(lbl),'unchanged')[lbl==old_lbl]
  630. qmsg('Label {}'.format(m))
  631. elif opt.label:
  632. qmsg("Using label '{}' requested on command line".format(opt.label.hl()))
  633. self.ssdata.label = opt.label
  634. else:
  635. self._get_label_from_user()
  636. def _encrypt(self):
  637. self._get_first_pw_and_hp_and_encrypt_seed()
  638. self._get_label()
  639. d = self.ssdata
  640. d.pw_status = ('NE','E')[len(d.passwd)==0]
  641. d.timestamp = make_timestamp()
  642. def _format(self):
  643. d = self.ssdata
  644. s = self.seed
  645. slt_fmt = baseconv.b58encode(d.salt,pad=True)
  646. es_fmt = baseconv.b58encode(d.enc_seed,pad=True)
  647. lines = (
  648. d.label,
  649. '{} {} {} {} {}'.format(s.sid.lower(), d.key_id.lower(),
  650. s.length, d.pw_status, d.timestamp),
  651. '{}: {} {} {}'.format(d.hash_preset,*get_hash_params(d.hash_preset)),
  652. '{} {}'.format(make_chksum_6(slt_fmt),split_into_cols(4,slt_fmt)),
  653. '{} {}'.format(make_chksum_6(es_fmt), split_into_cols(4,es_fmt))
  654. )
  655. chksum = make_chksum_6(' '.join(lines).encode())
  656. self.fmt_data = '\n'.join((chksum,)+lines) + '\n'
  657. def _deformat(self):
  658. def check_master_chksum(lines,desc):
  659. if len(lines) != 6:
  660. msg('Invalid number of lines ({}) in {} data'.format(len(lines),desc))
  661. return False
  662. if not is_chksum_6(lines[0]):
  663. msg('Incorrect master checksum ({}) in {} data'.format(lines[0],desc))
  664. return False
  665. chk = make_chksum_6(' '.join(lines[1:]))
  666. if not compare_chksums(lines[0],'master',chk,'computed',
  667. hdr='For wallet master checksum',verbose=True):
  668. return False
  669. return True
  670. lines = self.fmt_data.splitlines()
  671. if not check_master_chksum(lines,self.desc): return False
  672. d = self.ssdata
  673. d.label = MMGenWalletLabel(lines[1])
  674. d1,d2,d3,d4,d5 = lines[2].split()
  675. d.seed_id = d1.upper()
  676. d.key_id = d2.upper()
  677. check_usr_seed_len(int(d3))
  678. d.pw_status,d.timestamp = d4,d5
  679. hpdata = lines[3].split()
  680. d.hash_preset = hp = hpdata[0][:-1] # a string!
  681. qmsg("Hash preset of wallet: '{}'".format(hp))
  682. if 'hash_preset' in opt.set_by_user:
  683. uhp = opt.hash_preset
  684. if uhp != hp:
  685. qmsg("Warning: ignoring user-requested hash preset '{}'".format(uhp))
  686. hash_params = list(map(int,hpdata[1:]))
  687. if hash_params != get_hash_params(d.hash_preset):
  688. msg("Hash parameters '{}' don't match hash preset '{}'".format(' '.join(hash_params),d.hash_preset))
  689. return False
  690. lmin,foo,lmax = [v for k,v in baseconv.b58pad_lens] # 22,33,44
  691. for i,key in (4,'salt'),(5,'enc_seed'):
  692. l = lines[i].split(' ')
  693. chk = l.pop(0)
  694. b58_val = ''.join(l)
  695. if len(b58_val) < lmin or len(b58_val) > lmax:
  696. msg('Invalid format for {} in {}: {}'.format(key,self.desc,l))
  697. return False
  698. if not compare_chksums(chk,key,
  699. make_chksum_6(b58_val),'computed checksum',verbose=True):
  700. return False
  701. val = baseconv.b58decode(b58_val,pad=True)
  702. if val == False:
  703. msg('Invalid base 58 number: {}'.format(b58_val))
  704. return False
  705. setattr(d,key,val)
  706. return True
  707. def _decrypt(self):
  708. d = self.ssdata
  709. # Needed for multiple transactions with {}-txsign
  710. suf = ('',os.path.basename(self.infile.name))[bool(opt.quiet)]
  711. self._get_passphrase(desc_suf=suf)
  712. key = make_key(d.passwd, d.salt, d.hash_preset)
  713. ret = decrypt_seed(d.enc_seed, key, d.seed_id, d.key_id)
  714. if ret:
  715. self.seed = Seed(ret)
  716. return True
  717. else:
  718. return False
  719. def _filename(self):
  720. return '{}-{}[{},{}]{x}.{}'.format(
  721. self.seed.sid,
  722. self.ssdata.key_id,
  723. self.seed.length,
  724. self.ssdata.hash_preset,
  725. self.ext,
  726. x='-α' if g.debug_utf8 else '')
  727. class Brainwallet (SeedSourceEnc):
  728. stdin_ok = True
  729. fmt_codes = 'mmbrain','brainwallet','brain','bw','b'
  730. desc = 'brainwallet'
  731. ext = 'mmbrain'
  732. require_utf8_input = True # brainwallet is user input, so require UTF-8
  733. # brainwallet warning message? TODO
  734. def get_bw_params(self):
  735. # already checked
  736. a = opt.brain_params.split(',')
  737. return int(a[0]),a[1]
  738. def _deformat(self):
  739. self.brainpasswd = ' '.join(self.fmt_data.split())
  740. return True
  741. def _decrypt(self):
  742. d = self.ssdata
  743. # Don't set opt.seed_len! In txsign, BW seed len might differ from other seed srcs
  744. if opt.brain_params:
  745. seed_len,d.hash_preset = self.get_bw_params()
  746. else:
  747. if 'seed_len' not in opt.set_by_user:
  748. m1 = 'Using default seed length of {} bits\n'
  749. m2 = 'If this is not what you want, use the --seed-len option'
  750. qmsg((m1+m2).format(yellow(str(opt.seed_len))))
  751. self._get_hash_preset()
  752. seed_len = opt.seed_len
  753. qmsg_r('Hashing brainwallet data. Please wait...')
  754. # Use buflen arg of scrypt.hash() to get seed of desired length
  755. seed = scrypt_hash_passphrase(self.brainpasswd.encode(),b'',d.hash_preset,buflen=seed_len//8)
  756. qmsg('Done')
  757. self.seed = Seed(seed)
  758. msg('Seed ID: {}'.format(self.seed.sid))
  759. qmsg('Check this value against your records')
  760. return True
  761. class IncogWallet (SeedSourceEnc):
  762. file_mode = 'binary'
  763. fmt_codes = 'mmincog','incog','icg','i'
  764. desc = 'incognito data'
  765. ext = 'mmincog'
  766. no_tty = True
  767. _msg = {
  768. 'check_incog_id': """
  769. Check the generated Incog ID above against your records. If it doesn't
  770. match, then your incognito data is incorrect or corrupted.
  771. """,
  772. 'record_incog_id': """
  773. Make a record of the Incog ID but keep it secret. You will use it to
  774. identify your incog wallet data in the future.
  775. """,
  776. 'incorrect_incog_passphrase_try_again': """
  777. Incorrect passphrase, hash preset, or maybe old-format incog wallet.
  778. Try again? (Y)es, (n)o, (m)ore information:
  779. """.strip(),
  780. 'confirm_seed_id': """
  781. If the Seed ID above is correct but you're seeing this message, then you need
  782. to exit and re-run the program with the '--old-incog-fmt' option.
  783. """.strip(),
  784. 'dec_chk': " {} hash preset"
  785. }
  786. def _make_iv_chksum(self,s): return sha256(s).hexdigest()[:8].upper()
  787. def _get_incog_data_len(self,seed_len):
  788. e = (g.hincog_chk_len,0)[bool(opt.old_incog_fmt)]
  789. return g.aesctr_iv_len + g.salt_len + e + seed_len//8
  790. def _incog_data_size_chk(self):
  791. # valid sizes: 56, 64, 72
  792. dlen = len(self.fmt_data)
  793. valid_dlen = self._get_incog_data_len(opt.seed_len)
  794. if dlen == valid_dlen:
  795. return True
  796. else:
  797. if opt.old_incog_fmt:
  798. msg('WARNING: old-style incognito format requested. Are you sure this is correct?')
  799. m = 'Invalid incognito data size ({} bytes) for this seed length ({} bits)'
  800. msg(m.format(dlen,opt.seed_len))
  801. msg('Valid data size for this seed length: {} bytes'.format(valid_dlen))
  802. for sl in g.seed_lens:
  803. if dlen == self._get_incog_data_len(sl):
  804. die(1,'Valid seed length for this data size: {} bits'.format(sl))
  805. msg('This data size ({} bytes) is invalid for all available seed lengths'.format(dlen))
  806. return False
  807. def _encrypt (self):
  808. self._get_first_pw_and_hp_and_encrypt_seed()
  809. if opt.old_incog_fmt:
  810. die(1,'Writing old-format incog wallets is unsupported')
  811. d = self.ssdata
  812. # IV is used BOTH to initialize counter and to salt password!
  813. d.iv = get_random(g.aesctr_iv_len)
  814. d.iv_id = self._make_iv_chksum(d.iv)
  815. msg('New Incog Wallet ID: {}'.format(d.iv_id))
  816. qmsg('Make a record of this value')
  817. vmsg(self.msg['record_incog_id'])
  818. d.salt = get_random(g.salt_len)
  819. key = make_key(d.passwd, d.salt, d.hash_preset, 'incog wallet key')
  820. chk = sha256(self.seed.data).digest()[:8]
  821. d.enc_seed = encrypt_data(chk+self.seed.data, key, g.aesctr_dfl_iv, 'seed')
  822. d.wrapper_key = make_key(d.passwd, d.iv, d.hash_preset, 'incog wrapper key')
  823. d.key_id = make_chksum_8(d.wrapper_key)
  824. vmsg('Key ID: {}'.format(d.key_id))
  825. d.target_data_len = self._get_incog_data_len(self.seed.length)
  826. def _format(self):
  827. d = self.ssdata
  828. self.fmt_data = d.iv + encrypt_data(d.salt+d.enc_seed, d.wrapper_key, d.iv, self.desc)
  829. def _filename(self):
  830. s = self.seed
  831. d = self.ssdata
  832. return '{}-{}-{}[{},{}]{x}.{}'.format(
  833. s.sid,
  834. d.key_id,
  835. d.iv_id,
  836. s.length,
  837. d.hash_preset,
  838. self.ext,
  839. x='-α' if g.debug_utf8 else '')
  840. def _deformat(self):
  841. if not self._incog_data_size_chk(): return False
  842. d = self.ssdata
  843. d.iv = self.fmt_data[0:g.aesctr_iv_len]
  844. d.incog_id = self._make_iv_chksum(d.iv)
  845. d.enc_incog_data = self.fmt_data[g.aesctr_iv_len:]
  846. msg('Incog Wallet ID: {}'.format(d.incog_id))
  847. qmsg('Check this value against your records')
  848. vmsg(self.msg['check_incog_id'])
  849. return True
  850. def _verify_seed_newfmt(self,data):
  851. chk,seed = data[:8],data[8:]
  852. if sha256(seed).digest()[:8] == chk:
  853. qmsg('Passphrase{} are correct'.format(self.msg['dec_chk'].format('and')))
  854. return seed
  855. else:
  856. msg('Incorrect passphrase{}'.format(self.msg['dec_chk'].format('or')))
  857. return False
  858. def _verify_seed_oldfmt(self,seed):
  859. m = 'Seed ID: {}. Is the Seed ID correct?'.format(make_chksum_8(seed))
  860. if keypress_confirm(m, True):
  861. return seed
  862. else:
  863. return False
  864. def _decrypt(self):
  865. d = self.ssdata
  866. self._get_hash_preset(desc_suf=d.incog_id)
  867. self._get_passphrase(desc_suf=d.incog_id)
  868. # IV is used BOTH to initialize counter and to salt password!
  869. key = make_key(d.passwd, d.iv, d.hash_preset, 'wrapper key')
  870. dd = decrypt_data(d.enc_incog_data, key, d.iv, 'incog data')
  871. d.salt = dd[0:g.salt_len]
  872. d.enc_seed = dd[g.salt_len:]
  873. key = make_key(d.passwd, d.salt, d.hash_preset, 'main key')
  874. qmsg('Key ID: {}'.format(make_chksum_8(key)))
  875. verify_seed = getattr(self,'_verify_seed_'+
  876. ('newfmt','oldfmt')[bool(opt.old_incog_fmt)])
  877. seed = verify_seed(decrypt_seed(d.enc_seed, key, '', ''))
  878. if seed:
  879. self.seed = Seed(seed)
  880. msg('Seed ID: {}'.format(self.seed.sid))
  881. return True
  882. else:
  883. return False
  884. class IncogWalletHex (IncogWallet):
  885. file_mode = 'text'
  886. desc = 'hex incognito data'
  887. fmt_codes = 'mmincox','incox','incog_hex','xincog','ix','xi'
  888. ext = 'mmincox'
  889. no_tty = False
  890. def _deformat(self):
  891. ret = decode_pretty_hexdump(self.fmt_data)
  892. if ret:
  893. self.fmt_data = ret
  894. return IncogWallet._deformat(self)
  895. else:
  896. return False
  897. def _format(self):
  898. IncogWallet._format(self)
  899. self.fmt_data = pretty_hexdump(self.fmt_data)
  900. class IncogWalletHidden (IncogWallet):
  901. desc = 'hidden incognito data'
  902. fmt_codes = 'incog_hidden','hincog','ih','hi'
  903. ext = None
  904. _msg = {
  905. 'choose_file_size': """
  906. You must choose a size for your new hidden incog data. The minimum size is
  907. {} bytes, which puts the incog data right at the end of the file. Since you
  908. probably want to hide your data somewhere in the middle of the file where it's
  909. harder to find, you're advised to choose a much larger file size than this.
  910. """.strip(),
  911. 'check_incog_id': """
  912. Check generated Incog ID above against your records. If it doesn't
  913. match, then your incognito data is incorrect or corrupted, or you
  914. may have specified an incorrect offset.
  915. """,
  916. 'record_incog_id': """
  917. Make a record of the Incog ID but keep it secret. You will used it to
  918. identify the incog wallet data in the future and to locate the offset
  919. where the data is hidden in the event you forget it.
  920. """,
  921. 'dec_chk': ', hash preset, offset {} seed length'
  922. }
  923. def _get_hincog_params(self,wtype):
  924. a = getattr(opt,'hidden_incog_'+ wtype +'_params').split(',')
  925. return ','.join(a[:-1]),int(a[-1]) # permit comma in filename
  926. def _check_valid_offset(self,fn,action):
  927. d = self.ssdata
  928. m = ('Input','Destination')[action=='write']
  929. if fn.size < d.hincog_offset + d.target_data_len:
  930. fs = "{} file '{}' has length {}, too short to {} {} bytes of data at offset {}"
  931. die(1,fs.format(m,fn.name,fn.size,action,d.target_data_len,d.hincog_offset))
  932. def _get_data(self):
  933. d = self.ssdata
  934. d.hincog_offset = self._get_hincog_params('input')[1]
  935. qmsg("Getting hidden incog data from file '{}'".format(self.infile.name))
  936. # Already sanity-checked:
  937. d.target_data_len = self._get_incog_data_len(opt.seed_len)
  938. self._check_valid_offset(self.infile,'read')
  939. flgs = os.O_RDONLY|os.O_BINARY if g.platform == 'win' else os.O_RDONLY
  940. fh = os.open(self.infile.name,flgs)
  941. os.lseek(fh,int(d.hincog_offset),os.SEEK_SET)
  942. self.fmt_data = os.read(fh,d.target_data_len)
  943. os.close(fh)
  944. qmsg("Data read from file '{}' at offset {}".format(self.infile.name,d.hincog_offset))
  945. # overrides method in SeedSource
  946. def write_to_file(self):
  947. d = self.ssdata
  948. self._format()
  949. compare_or_die(d.target_data_len, 'target data length',
  950. len(self.fmt_data),'length of formatted ' + self.desc)
  951. k = ('output','input')[self.op=='pwchg_new']
  952. fn,d.hincog_offset = self._get_hincog_params(k)
  953. if opt.outdir and not os.path.dirname(fn):
  954. fn = os.path.join(opt.outdir,fn)
  955. check_offset = True
  956. try:
  957. os.stat(fn)
  958. except:
  959. if keypress_confirm("Requested file '{}' does not exist. Create?".format(fn),default_yes=True):
  960. min_fsize = d.target_data_len + d.hincog_offset
  961. msg(self.msg['choose_file_size'].format(min_fsize))
  962. while True:
  963. fsize = parse_bytespec(my_raw_input('Enter file size: '))
  964. if fsize >= min_fsize: break
  965. msg('File size must be an integer no less than {}'.format(min_fsize))
  966. from mmgen.tool import MMGenToolCmd
  967. MMGenToolCmd().rand2file(fn,str(fsize))
  968. check_offset = False
  969. else:
  970. die(1,'Exiting at user request')
  971. from mmgen.filename import Filename
  972. f = Filename(fn,ftype=type(self),write=True)
  973. dmsg('{} data len {}, offset {}'.format(capfirst(self.desc),d.target_data_len,d.hincog_offset))
  974. if check_offset:
  975. self._check_valid_offset(f,'write')
  976. if not opt.quiet:
  977. confirm_or_raise('',"alter file '{}'".format(f.name))
  978. flgs = os.O_RDWR|os.O_BINARY if g.platform == 'win' else os.O_RDWR
  979. fh = os.open(f.name,flgs)
  980. os.lseek(fh, int(d.hincog_offset), os.SEEK_SET)
  981. os.write(fh, self.fmt_data)
  982. os.close(fh)
  983. msg("{} written to file '{}' at offset {}".format(capfirst(self.desc),f.name,d.hincog_offset))