tool.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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. tool.py: Routines for the 'mmgen-tool' utility
  20. """
  21. from .protocol import hash160
  22. from .common import *
  23. from .crypto import *
  24. from .addr import *
  25. NL = ('\n','\r\n')[g.platform=='win']
  26. def _options_annot_str(l):
  27. return '(valid options: {})'.format(','.join(l))
  28. def _create_call_sig(cmd,parsed=False):
  29. m = MMGenToolCmds[cmd]
  30. if 'varargs_call_sig' in m.__code__.co_varnames: # hack
  31. flag = 'VAR_ARGS'
  32. va = m.__defaults__[0]
  33. args,dfls,ann = va['args'],va['dfls'],va['annots']
  34. else:
  35. flag = None
  36. args = m.__code__.co_varnames[1:m.__code__.co_argcount]
  37. dfls = m.__defaults__ or ()
  38. ann = m.__annotations__
  39. nargs = len(args) - len(dfls)
  40. def get_type_from_ann(arg):
  41. return ann[arg][1:] + (' or STDIN','')[parsed] if ann[arg] == 'sstr' else ann[arg].__name__
  42. if parsed:
  43. c_args = [(a,get_type_from_ann(a)) for a in args[:nargs]]
  44. c_kwargs = [(a,dfls[n]) for n,a in enumerate(args[nargs:])]
  45. return c_args,dict(c_kwargs),'STDIN_OK' if c_args and ann[args[0]] == 'sstr' else flag
  46. else:
  47. c_args = ['{} [{}]'.format(a,get_type_from_ann(a)) for a in args[:nargs]]
  48. c_kwargs = ['"{}" [{}={!r}{}]'.format(
  49. a, type(dfls[n]).__name__, dfls[n],
  50. (' ' + ann[a] if a in ann else ''))
  51. for n,a in enumerate(args[nargs:])]
  52. return ' '.join(c_args + c_kwargs)
  53. def _usage(cmd=None,exit_val=1):
  54. m1=('USAGE INFORMATION FOR MMGEN-TOOL COMMANDS:\n\n'
  55. ' Unquoted arguments are mandatory\n'
  56. ' Quoted arguments are optional, default values will be used\n'
  57. ' Argument types and default values are shown in square brackets\n')
  58. m2=(' To force a command to read from STDIN instead of file (for commands taking\n'
  59. ' a filename as their first argument), substitute "-" for the filename.\n\n'
  60. 'EXAMPLES:\n\n'
  61. ' Generate a random Bech32 public/private keypair for LTC:\n'
  62. ' $ mmgen-tool -r0 --coin=ltc --type=bech32 randpair\n\n'
  63. ' Generate a DASH compressed public key address from the supplied WIF key:\n'
  64. ' $ mmgen-tool --coin=dash --type=compressed wif2addr XJkVRC3eGKurc9Uzx1wfQoio3yqkmaXVqLMTa6y7s3M3jTBnmxfw\n\n'
  65. ' Generate a well-known burn address:\n'
  66. ' $ mmgen-tool hextob58chk 000000000000000000000000000000000000000000\n\n'
  67. ' Generate a random 12-word seed phrase:\n'
  68. ' $ mmgen-tool -r0 mn_rand128\n\n'
  69. ' Same as above, but get additional entropy from user:\n'
  70. ' $ mmgen-tool mn_rand128\n\n'
  71. ' Encode bytes from a file to base 58:\n'
  72. ' $ mmgen-tool bytestob58 /etc/timezone pad=20\n\n'
  73. ' Reverse a hex string:\n'
  74. ' $ mmgen-tool hexreverse "deadbeefcafe"\n\n'
  75. ' Same as above, but use a pipe:\n'
  76. ' $ echo "deadbeefcafe" | mmgen-tool hexreverse -')
  77. if not cmd:
  78. Msg(m1)
  79. for bc in MMGenToolCmds.classes.values():
  80. cls_info = bc.__doc__.strip().split('\n')[0]
  81. Msg(' {}{}\n'.format(cls_info[0].upper(),cls_info[1:]))
  82. max_w = max(map(len,bc.user_commands))
  83. for cmd in sorted(bc.user_commands):
  84. Msg(' {:{w}} {}'.format(cmd,_create_call_sig(cmd),w=max_w))
  85. Msg('')
  86. Msg(m2)
  87. elif cmd in MMGenToolCmds:
  88. msg('{}'.format(capfirst(MMGenToolCmds[cmd].__doc__.strip())))
  89. msg('USAGE: {} {} {}'.format(g.prog_name,cmd,_create_call_sig(cmd)))
  90. else:
  91. die(1,"'{}': no such tool command".format(cmd))
  92. sys.exit(exit_val)
  93. def _process_args(cmd,cmd_args):
  94. c_args,c_kwargs,flag = _create_call_sig(cmd,parsed=True)
  95. have_stdin_input = False
  96. if flag != 'VAR_ARGS':
  97. if len(cmd_args) < len(c_args):
  98. m1 = 'Command requires exactly {} non-keyword argument{}'
  99. msg(m1.format(len(c_args),suf(c_args)))
  100. _usage(cmd)
  101. u_args = cmd_args[:len(c_args)]
  102. # If we're reading from a pipe, replace '-' with output of previous command
  103. if flag == 'STDIN_OK' and u_args and u_args[0] == '-':
  104. if sys.stdin.isatty():
  105. raise BadFilename("Standard input is a TTY. Can't use '-' as a filename")
  106. else:
  107. max_dlen_spec = '10kB' # limit input to 10KB for now
  108. max_dlen = MMGenToolCmdUtil().bytespec(max_dlen_spec)
  109. u_args[0] = os.read(0,max_dlen)
  110. have_stdin_input = True
  111. if len(u_args[0]) >= max_dlen:
  112. die(2,'Maximum data input for this command is {}'.format(max_dlen_spec))
  113. if not u_args[0]:
  114. die(2,'{}: ERROR: no output from previous command in pipe'.format(cmd))
  115. u_nkwargs = len(cmd_args) - len(c_args)
  116. u_kwargs = {}
  117. if flag == 'VAR_ARGS':
  118. t = [a.split('=',1) for a in cmd_args if '=' in a]
  119. tk = [a[0] for a in t]
  120. tk_bad = [a for a in tk if a not in c_kwargs]
  121. if set(tk_bad) != set(tk[:len(tk_bad)]): # permit non-kw args to contain '='
  122. die(1,"'{}': illegal keyword argument".format(tk_bad[-1]))
  123. u_kwargs = dict(t[len(tk_bad):])
  124. u_args = cmd_args[:-len(u_kwargs) or None]
  125. elif u_nkwargs > 0:
  126. u_kwargs = dict([a.split('=',1) for a in cmd_args[len(c_args):] if '=' in a])
  127. if len(u_kwargs) != u_nkwargs:
  128. msg('Command requires exactly {} non-keyword argument{}'.format(len(c_args),suf(c_args)))
  129. _usage(cmd)
  130. if len(u_kwargs) > len(c_kwargs):
  131. msg('Command accepts no more than {} keyword argument{}'.format(len(c_kwargs),suf(c_kwargs)))
  132. _usage(cmd)
  133. for k in u_kwargs:
  134. if k not in c_kwargs:
  135. msg("'{}': invalid keyword argument".format(k))
  136. _usage(cmd)
  137. def conv_type(arg,arg_name,arg_type):
  138. if arg_type == 'bytes' and type(arg) != bytes:
  139. die(1,"'Binary input data must be supplied via STDIN")
  140. if have_stdin_input and arg_type == 'str' and isinstance(arg,bytes):
  141. arg = arg.decode()
  142. if arg[-len(NL):] == NL: # rstrip one newline
  143. arg = arg[:-len(NL)]
  144. if arg_type == 'bool':
  145. if arg.lower() in ('true','yes','1','on'): arg = True
  146. elif arg.lower() in ('false','no','0','off'): arg = False
  147. else:
  148. msg("'{}': invalid boolean value for keyword argument".format(arg))
  149. _usage(cmd)
  150. try:
  151. return __builtins__[arg_type](arg)
  152. except:
  153. die(1,"'{}': Invalid argument for argument {} ('{}' required)".format(arg,arg_name,arg_type))
  154. if flag == 'VAR_ARGS':
  155. args = [conv_type(u_args[i],c_args[0][0],c_args[0][1]) for i in range(len(u_args))]
  156. else:
  157. args = [conv_type(u_args[i],c_args[i][0],c_args[i][1]) for i in range(len(c_args))]
  158. kwargs = {k:conv_type(u_kwargs[k],k,type(c_kwargs[k]).__name__) for k in u_kwargs}
  159. return args,kwargs
  160. def _process_result(ret,pager=False,print_result=False):
  161. """
  162. Convert result to something suitable for output to screen and return it.
  163. If result is bytes and not convertible to utf8, output as binary using os.write().
  164. If 'print_result' is True, send the converted result directly to screen or
  165. pager instead of returning it.
  166. """
  167. def triage_result(o):
  168. return o if not print_result else do_pager(o) if pager else Msg(o)
  169. if ret == True:
  170. return True
  171. elif ret in (False,None):
  172. ydie(1,"tool command returned '{}'".format(ret))
  173. elif isinstance(ret,str):
  174. return triage_result(ret)
  175. elif isinstance(ret,int):
  176. return triage_result(str(ret))
  177. elif isinstance(ret,tuple):
  178. return triage_result('\n'.join([r.decode() if isinstance(r,bytes) else r for r in ret]))
  179. elif isinstance(ret,bytes):
  180. try:
  181. o = ret.decode()
  182. return o if not print_result else do_pager(o) if pager else Msg(o)
  183. except:
  184. # don't add NL to binary data if it can't be converted to utf8
  185. return ret if not print_result else os.write(1,ret)
  186. else:
  187. ydie(1,"tool.py: can't handle return value of type '{}'".format(type(ret).__name__))
  188. from .obj import MMGenAddrType
  189. def init_generators(arg=None):
  190. global at,kg,ag
  191. at = MMGenAddrType((hasattr(opt,'type') and opt.type) or g.proto.dfl_mmtype)
  192. if arg != 'at':
  193. kg = KeyGenerator(at)
  194. ag = AddrGenerator(at)
  195. def conv_cls_bip39():
  196. from .bip39 import bip39
  197. return bip39
  198. dfl_mnemonic_fmt = 'mmgen'
  199. mnemonic_fmts = {
  200. 'mmgen': { 'fmt': 'words', 'conv_cls': lambda: baseconv },
  201. 'bip39': { 'fmt': 'bip39', 'conv_cls': conv_cls_bip39 },
  202. 'xmrseed': { 'fmt': 'xmrseed','conv_cls': lambda: baseconv },
  203. }
  204. mn_opts_disp = "(valid options: '{}')".format("', '".join(mnemonic_fmts))
  205. class MMGenToolCmdMeta(type):
  206. classes = {}
  207. methods = {}
  208. def __new__(mcls,name,bases,namespace):
  209. methods = {k:v for k,v in namespace.items() if k[0] != '_' and callable(v) and v.__doc__}
  210. if g.test_suite:
  211. if name in mcls.classes:
  212. raise ValueError(f'Class {name!r} already defined!')
  213. for m in methods:
  214. if m in mcls.methods:
  215. raise ValueError(f'Method {m!r} already defined!')
  216. if not getattr(m,'__doc__',None):
  217. raise ValueError(f'Method {m!r} has no doc string!')
  218. cls = super().__new__(mcls,name,bases,namespace)
  219. if bases and name != 'tool_api':
  220. mcls.classes[name] = cls
  221. mcls.methods.update(methods)
  222. return cls
  223. def __iter__(cls):
  224. return cls.methods.__iter__()
  225. def __getitem__(cls,val):
  226. return cls.methods.__getitem__(val)
  227. def __contains__(cls,val):
  228. return cls.methods.__contains__(val)
  229. def classname(cls,cmd_name):
  230. return cls.methods[cmd_name].__qualname__.split('.')[0]
  231. def call(cls,cmd_name,*args,**kwargs):
  232. return getattr(cls.classes[cls.classname(cmd_name)](),cmd_name)(*args,**kwargs)
  233. @property
  234. def user_commands(cls):
  235. return {k:v for k,v in cls.__dict__.items() if k in cls.methods}
  236. class MMGenToolCmds(metaclass=MMGenToolCmdMeta): pass
  237. class MMGenToolCmdMisc(MMGenToolCmds):
  238. "miscellaneous commands"
  239. def help(self,command_name=''):
  240. "display usage information for a single command or all commands"
  241. _usage(command_name,exit_val=0)
  242. usage = help
  243. class MMGenToolCmdUtil(MMGenToolCmds):
  244. "general string conversion and hashing utilities"
  245. def bytespec(self,dd_style_byte_specifier:str):
  246. "convert a byte specifier such as '1GB' into an integer"
  247. return parse_bytespec(dd_style_byte_specifier)
  248. def randhex(self,nbytes='32'):
  249. "print 'n' bytes (default 32) of random data in hex format"
  250. return get_random(int(nbytes)).hex()
  251. def hexreverse(self,hexstr:'sstr'):
  252. "reverse bytes of a hexadecimal string"
  253. return bytes.fromhex(hexstr.strip())[::-1].hex()
  254. def hexlify(self,infile:str):
  255. "convert bytes in file to hexadecimal (use '-' for stdin)"
  256. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  257. return data.hex()
  258. def unhexlify(self,hexstr:'sstr'):
  259. "convert hexadecimal value to bytes (warning: outputs binary data)"
  260. return bytes.fromhex(hexstr)
  261. def hexdump(self,infile:str,cols=8,line_nums='hex'):
  262. "create hexdump of data from file (use '-' for stdin)"
  263. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  264. return pretty_hexdump(data,cols=cols,line_nums=line_nums).rstrip()
  265. def unhexdump(self,infile:str):
  266. "decode hexdump from file (use '-' for stdin) (warning: outputs binary data)"
  267. if g.platform == 'win':
  268. import msvcrt
  269. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  270. hexdata = get_data_from_file(infile,dash=True,quiet=True)
  271. return decode_pretty_hexdump(hexdata)
  272. def hash160(self,hexstr:'sstr'):
  273. "compute ripemd160(sha256(data)) (convert hex pubkey to hex addr)"
  274. return hash160(hexstr)
  275. def hash256(self,string_or_bytes:str,file_input=False,hex_input=False): # TODO: handle stdin
  276. "compute sha256(sha256(data)) (double sha256)"
  277. from hashlib import sha256
  278. if file_input: b = get_data_from_file(string_or_bytes,binary=True)
  279. elif hex_input: b = decode_pretty_hexdump(string_or_bytes)
  280. else: b = string_or_bytes
  281. return sha256(sha256(b.encode()).digest()).hexdigest()
  282. def id6(self,infile:str):
  283. "generate 6-character MMGen ID for a file (use '-' for stdin)"
  284. return make_chksum_6(
  285. get_data_from_file(infile,dash=True,quiet=True,binary=True))
  286. def str2id6(self,string:'sstr'): # retain ignoring of space for backwards compat
  287. "generate 6-character MMGen ID for a string, ignoring spaces"
  288. return make_chksum_6(''.join(string.split()))
  289. def id8(self,infile:str):
  290. "generate 8-character MMGen ID for a file (use '-' for stdin)"
  291. return make_chksum_8(
  292. get_data_from_file(infile,dash=True,quiet=True,binary=True))
  293. def randb58(self,nbytes=32,pad=0):
  294. "generate random data (default: 32 bytes) and convert it to base 58"
  295. return baseconv.frombytes(get_random(nbytes),'b58',pad=pad,tostr=True)
  296. def bytestob58(self,infile:str,pad=0):
  297. "convert bytes to base 58 (supply data via STDIN)"
  298. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  299. return baseconv.frombytes(data,'b58',pad=pad,tostr=True)
  300. def b58tobytes(self,b58num:'sstr',pad=0):
  301. "convert a base 58 number to bytes (warning: outputs binary data)"
  302. return baseconv.tobytes(b58num,'b58',pad=pad)
  303. def hextob58(self,hexstr:'sstr',pad=0):
  304. "convert a hexadecimal number to base 58"
  305. return baseconv.fromhex(hexstr,'b58',pad=pad,tostr=True)
  306. def b58tohex(self,b58num:'sstr',pad=0):
  307. "convert a base 58 number to hexadecimal"
  308. return baseconv.tohex(b58num,'b58',pad=pad)
  309. def hextob58chk(self,hexstr:'sstr'):
  310. "convert a hexadecimal number to base58-check encoding"
  311. from .protocol import _b58chk_encode
  312. return _b58chk_encode(bytes.fromhex(hexstr))
  313. def b58chktohex(self,b58chk_num:'sstr'):
  314. "convert a base58-check encoded number to hexadecimal"
  315. from .protocol import _b58chk_decode
  316. return _b58chk_decode(b58chk_num).hex()
  317. def hextob32(self,hexstr:'sstr',pad=0):
  318. "convert a hexadecimal number to MMGen's flavor of base 32"
  319. return baseconv.fromhex(hexstr,'b32',pad,tostr=True)
  320. def b32tohex(self,b32num:'sstr',pad=0):
  321. "convert an MMGen-flavor base 32 number to hexadecimal"
  322. return baseconv.tohex(b32num.upper(),'b32',pad)
  323. def hextob6d(self,hexstr:'sstr',pad=0,add_spaces=True):
  324. "convert a hexadecimal number to die roll base6 (base6d)"
  325. ret = baseconv.fromhex(hexstr,'b6d',pad,tostr=True)
  326. return block_format(ret,gw=5,cols=None).strip() if add_spaces else ret
  327. def b6dtohex(self,b6d_num:'sstr',pad=0):
  328. "convert a die roll base6 (base6d) number to hexadecimal"
  329. return baseconv.tohex(remove_whitespace(b6d_num),'b6d',pad)
  330. class MMGenToolCmdCoin(MMGenToolCmds):
  331. """
  332. cryptocoin key/address utilities
  333. May require use of the '--coin', '--type' and/or '--testnet' options
  334. Examples:
  335. mmgen-tool --coin=ltc --type=bech32 wif2addr <wif key>
  336. mmgen-tool --coin=zec --type=zcash_z randpair
  337. """
  338. def randwif(self):
  339. "generate a random private key in WIF format"
  340. init_generators('at')
  341. return PrivKey(get_random(32),pubkey_type=at.pubkey_type,compressed=at.compressed).wif
  342. def randpair(self):
  343. "generate a random private key/address pair"
  344. init_generators()
  345. privhex = PrivKey(get_random(32),pubkey_type=at.pubkey_type,compressed=at.compressed)
  346. addr = ag.to_addr(kg.to_pubhex(privhex))
  347. return (privhex.wif,addr)
  348. def wif2hex(self,wifkey:'sstr'):
  349. "convert a private key from WIF to hex format"
  350. return PrivKey(wif=wifkey)
  351. def hex2wif(self,privhex:'sstr'):
  352. "convert a private key from hex to WIF format"
  353. init_generators('at')
  354. return PrivKey(bytes.fromhex(privhex),pubkey_type=at.pubkey_type,compressed=at.compressed).wif
  355. def wif2addr(self,wifkey:'sstr'):
  356. "generate a coin address from a key in WIF format"
  357. init_generators()
  358. privhex = PrivKey(wif=wifkey)
  359. addr = ag.to_addr(kg.to_pubhex(privhex))
  360. return addr
  361. def wif2redeem_script(self,wifkey:'sstr'): # new
  362. "convert a WIF private key to a Segwit P2SH-P2WPKH redeem script"
  363. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  364. init_generators()
  365. privhex = PrivKey(wif=wifkey)
  366. return ag.to_segwit_redeem_script(kg.to_pubhex(privhex))
  367. def wif2segwit_pair(self,wifkey:'sstr'):
  368. "generate both a Segwit P2SH-P2WPKH redeem script and address from WIF"
  369. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  370. init_generators()
  371. pubhex = kg.to_pubhex(PrivKey(wif=wifkey))
  372. addr = ag.to_addr(pubhex)
  373. rs = ag.to_segwit_redeem_script(pubhex)
  374. return (rs,addr)
  375. def privhex2addr(self,privhex:'sstr',output_pubhex=False):
  376. "generate coin address from raw private key data in hexadecimal format"
  377. init_generators()
  378. pk = PrivKey(bytes.fromhex(privhex),compressed=at.compressed,pubkey_type=at.pubkey_type)
  379. ph = kg.to_pubhex(pk)
  380. return ph if output_pubhex else ag.to_addr(ph)
  381. def privhex2pubhex(self,privhex:'sstr'): # new
  382. "generate a hex public key from a hex private key"
  383. return self.privhex2addr(privhex,output_pubhex=True)
  384. def pubhex2addr(self,pubkeyhex:'sstr'):
  385. "convert a hex pubkey to an address"
  386. if opt.type == 'segwit':
  387. return g.proto.pubhex2segwitaddr(pubkeyhex)
  388. else:
  389. return self.pubhash2addr(hash160(pubkeyhex))
  390. def pubhex2redeem_script(self,pubkeyhex:'sstr'): # new
  391. "convert a hex pubkey to a Segwit P2SH-P2WPKH redeem script"
  392. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  393. return g.proto.pubhex2redeem_script(pubkeyhex)
  394. def redeem_script2addr(self,redeem_scripthex:'sstr'): # new
  395. "convert a Segwit P2SH-P2WPKH redeem script to an address"
  396. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  397. assert redeem_scripthex[:4] == '0014','{!r}: invalid redeem script'.format(redeem_scripthex)
  398. assert len(redeem_scripthex) == 44,'{} bytes: invalid redeem script length'.format(len(redeem_scripthex)//2)
  399. return self.pubhash2addr(hash160(redeem_scripthex))
  400. def pubhash2addr(self,pubhashhex:'sstr'):
  401. "convert public key hash to address"
  402. if opt.type == 'bech32':
  403. return g.proto.pubhash2bech32addr(pubhashhex)
  404. else:
  405. init_generators('at')
  406. return g.proto.pubhash2addr(pubhashhex,at.addr_fmt=='p2sh')
  407. def addr2pubhash(self,addr:'sstr'):
  408. "convert coin address to public key hash"
  409. from .tx import addr2pubhash
  410. return addr2pubhash(CoinAddr(addr))
  411. def addr2scriptpubkey(self,addr:'sstr'):
  412. "convert coin address to scriptPubKey"
  413. from .tx import addr2scriptPubKey
  414. return addr2scriptPubKey(CoinAddr(addr))
  415. def scriptpubkey2addr(self,hexstr:'sstr'):
  416. "convert scriptPubKey to coin address"
  417. from .tx import scriptPubKey2addr
  418. return scriptPubKey2addr(hexstr)[0]
  419. class MMGenToolCmdMnemonic(MMGenToolCmds):
  420. """
  421. seed phrase utilities (valid formats: 'mmgen' (default), 'bip39', 'xmrseed')
  422. IMPORTANT NOTE: MMGen's default seed phrase format uses the Electrum
  423. wordlist, however seed phrases are computed using a different algorithm
  424. and are NOT Electrum-compatible!
  425. BIP39 support is fully compatible with the standard, allowing users to
  426. import and export seed entropy from BIP39-compatible wallets. However,
  427. users should be aware that BIP39 support does not imply BIP32 support!
  428. MMGen uses its own key derivation scheme differing from the one described
  429. by the BIP32 protocol.
  430. For Monero ('xmrseed') seed phrases, input data is reduced to a spendkey
  431. before conversion so that a canonical seed phrase is produced. This is
  432. required because Monero seeds, unlike ordinary wallet seeds, are tied
  433. to a concrete key/address pair. To manually generate a Monero spendkey,
  434. use the 'hex2wif' command.
  435. """
  436. @staticmethod
  437. def _xmr_reduce(bytestr):
  438. from .protocol import init_proto
  439. proto = init_proto('xmr')
  440. if len(bytestr) != proto.privkey_len:
  441. m = '{!r}: invalid bit length for Monero private key (must be {})'
  442. die(1,m.format(len(bytestr*8),proto.privkey_len*8))
  443. return proto.preprocess_key(bytestr,None)
  444. def _do_random_mn(self,nbytes:int,fmt:str):
  445. assert nbytes in (16,24,32), 'nbytes must be 16, 24 or 32'
  446. randbytes = get_random(nbytes)
  447. if fmt == 'xmrseed':
  448. randbytes = self._xmr_reduce(randbytes)
  449. if opt.verbose:
  450. msg('Seed: {}'.format(randbytes.hex()))
  451. return self.hex2mn(randbytes.hex(),fmt=fmt)
  452. def mn_rand128(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  453. "generate random 128-bit mnemonic seed phrase"
  454. return self._do_random_mn(16,fmt)
  455. def mn_rand192(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  456. "generate random 192-bit mnemonic seed phrase"
  457. return self._do_random_mn(24,fmt)
  458. def mn_rand256(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  459. "generate random 256-bit mnemonic seed phrase"
  460. return self._do_random_mn(32,fmt)
  461. def _get_mnemonic_fmt(self,fmt):
  462. if fmt not in mnemonic_fmts:
  463. m = '{!r}: invalid format (valid options: {})'
  464. die(1,m.format(fmt,', '.join(mnemonic_fmts)))
  465. return mnemonic_fmts[fmt]['fmt']
  466. def hex2mn( self, hexstr:'sstr', fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  467. "convert a 16, 24 or 32-byte hexadecimal number to a mnemonic seed phrase"
  468. if fmt == 'bip39':
  469. from .bip39 import bip39
  470. return ' '.join(bip39.fromhex(hexstr,fmt))
  471. else:
  472. bytestr = bytes.fromhex(hexstr)
  473. if fmt == 'xmrseed':
  474. bytestr = self._xmr_reduce(bytestr)
  475. return baseconv.frombytes(bytestr,fmt,'seed',tostr=True)
  476. def mn2hex( self, seed_mnemonic:'sstr', fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  477. "convert a mnemonic seed phrase to a hexadecimal number"
  478. if fmt == 'bip39':
  479. from .bip39 import bip39
  480. return bip39.tohex(seed_mnemonic.split(),fmt)
  481. else:
  482. return baseconv.tohex(seed_mnemonic.split(),fmt,'seed')
  483. def mn2hex_interactive( self, fmt:mn_opts_disp=dfl_mnemonic_fmt, mn_len=24, print_mn=False ):
  484. "convert an interactively supplied mnemonic seed phrase to a hexadecimal number"
  485. from .mn_entry import mn_entry
  486. mn = mn_entry(fmt).get_mnemonic_from_user(25 if fmt == 'xmrseed' else mn_len,validate=False)
  487. if print_mn:
  488. msg(mn)
  489. return self.mn2hex(seed_mnemonic=mn,fmt=fmt)
  490. def mn_stats(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  491. "show stats for mnemonic wordlist"
  492. conv_cls = mnemonic_fmts[fmt]['conv_cls']()
  493. return conv_cls.check_wordlist(fmt)
  494. def mn_printlist( self, fmt:mn_opts_disp = dfl_mnemonic_fmt, enum=False, pager=False ):
  495. "print mnemonic wordlist"
  496. conv_cls = mnemonic_fmts[fmt]['conv_cls']()
  497. ret = conv_cls.get_wordlist(fmt)
  498. if enum:
  499. ret = ['{:>4} {}'.format(n,e) for n,e in enumerate(ret)]
  500. return '\n'.join(ret)
  501. class MMGenToolCmdFile(MMGenToolCmds):
  502. "utilities for viewing/checking MMGen address and transaction files"
  503. def _file_chksum(self,mmgen_addrfile,objname):
  504. opt.yes = True
  505. opt.quiet = True
  506. from .addr import AddrList,KeyAddrList,PasswordList
  507. ret = locals()[objname](mmgen_addrfile)
  508. if opt.verbose:
  509. if ret.al_id.mmtype.name == 'password':
  510. fs = 'Passwd fmt: {}\nPasswd len: {}\nID string: {}'
  511. msg(fs.format(capfirst(ret.pw_info[ret.pw_fmt].desc),ret.pw_len,ret.pw_id_str))
  512. else:
  513. msg('Base coin: {} {}'.format(ret.base_coin,('Mainnet','Testnet')[ret.is_testnet]))
  514. msg('MMType: {}'.format(capfirst(ret.al_id.mmtype.name)))
  515. msg('List length: {}'.format(len(ret.data)))
  516. return ret.chksum
  517. def addrfile_chksum(self,mmgen_addrfile:str):
  518. "compute checksum for MMGen address file"
  519. return self._file_chksum(mmgen_addrfile,'AddrList')
  520. def keyaddrfile_chksum(self,mmgen_keyaddrfile:str):
  521. "compute checksum for MMGen key-address file"
  522. return self._file_chksum(mmgen_keyaddrfile,'KeyAddrList')
  523. def passwdfile_chksum(self,mmgen_passwdfile:str):
  524. "compute checksum for MMGen password file"
  525. return self._file_chksum(mmgen_passwdfile,'PasswordList')
  526. def txview( varargs_call_sig = { # hack to allow for multiple filenames
  527. 'args': (
  528. 'mmgen_tx_file(s)',
  529. 'pager',
  530. 'terse',
  531. 'sort',
  532. 'filesort' ),
  533. 'dfls': ( False, False, 'addr', 'mtime' ),
  534. 'annots': {
  535. 'mmgen_tx_file(s)': str,
  536. 'sort': '(valid options: addr,raw)',
  537. 'filesort': '(valid options: mtime,ctime,atime)'
  538. } },
  539. *infiles,**kwargs):
  540. "show raw/signed MMGen transaction in human-readable form"
  541. terse = bool(kwargs.get('terse'))
  542. tx_sort = kwargs.get('sort') or 'addr'
  543. file_sort = kwargs.get('filesort') or 'mtime'
  544. from .filename import MMGenFileList
  545. from .tx import MMGenTX,MMGenTxForSigning
  546. flist = MMGenFileList(infiles,ftype=MMGenTX)
  547. flist.sort_by_age(key=file_sort) # in-place sort
  548. def gen():
  549. for fn in flist.names():
  550. yield (MMGenTxForSigning,MMGenTX)[fn.endswith('.sigtx')](fn).format_view(terse=terse,sort=tx_sort)
  551. return ('—'*77+'\n').join(gen()).rstrip()
  552. class MMGenToolCmdFileCrypt(MMGenToolCmds):
  553. """
  554. file encryption and decryption
  555. MMGen encryption suite:
  556. * Key: Scrypt (user-configurable hash parameters, 32-byte salt)
  557. * Enc: AES256_CTR, 16-byte rand IV, sha256 hash + 32-byte nonce + data
  558. * The encrypted file is indistinguishable from random data
  559. """
  560. def encrypt(self,infile:str,outfile='',hash_preset=''):
  561. "encrypt a file"
  562. data = get_data_from_file(infile,'data for encryption',binary=True)
  563. enc_d = mmgen_encrypt(data,'user data',hash_preset)
  564. if not outfile:
  565. outfile = '{}.{}'.format(os.path.basename(infile),g.mmenc_ext)
  566. write_data_to_file(outfile,enc_d,'encrypted data',binary=True)
  567. return True
  568. def decrypt(self,infile:str,outfile='',hash_preset=''):
  569. "decrypt a file"
  570. enc_d = get_data_from_file(infile,'encrypted data',binary=True)
  571. while True:
  572. dec_d = mmgen_decrypt(enc_d,'user data',hash_preset)
  573. if dec_d: break
  574. msg('Trying again...')
  575. if not outfile:
  576. o = os.path.basename(infile)
  577. outfile = remove_extension(o,g.mmenc_ext)
  578. if outfile == o: outfile += '.dec'
  579. write_data_to_file(outfile,dec_d,'decrypted data',binary=True)
  580. return True
  581. class MMGenToolCmdFileUtil(MMGenToolCmds):
  582. "file utilities"
  583. def find_incog_data(self,filename:str,incog_id:str,keep_searching=False):
  584. "Use an Incog ID to find hidden incognito wallet data"
  585. ivsize,bsize,mod = g.aesctr_iv_len,4096,4096*8
  586. n,carry = 0,b' '*ivsize
  587. flgs = os.O_RDONLY|os.O_BINARY if g.platform == 'win' else os.O_RDONLY
  588. f = os.open(filename,flgs)
  589. for ch in incog_id:
  590. if ch not in '0123456789ABCDEF':
  591. die(2,"'{}': invalid Incog ID".format(incog_id))
  592. while True:
  593. d = os.read(f,bsize)
  594. if not d: break
  595. d = carry + d
  596. for i in range(bsize):
  597. if sha256(d[i:i+ivsize]).hexdigest()[:8].upper() == incog_id:
  598. if n+i < ivsize: continue
  599. msg('\rIncog data for ID {} found at offset {}'.format(incog_id,n+i-ivsize))
  600. if not keep_searching: sys.exit(0)
  601. carry = d[len(d)-ivsize:]
  602. n += bsize
  603. if not n % mod:
  604. msg_r('\rSearched: {} bytes'.format(n))
  605. msg('')
  606. os.close(f)
  607. return True
  608. def rand2file(self,outfile:str,nbytes:str,threads=4,silent=False):
  609. "write 'n' bytes of random data to specified file"
  610. from threading import Thread
  611. from queue import Queue
  612. from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
  613. from cryptography.hazmat.backends import default_backend
  614. def encrypt_worker(wid):
  615. ctr_init_val = os.urandom(g.aesctr_iv_len)
  616. c = Cipher(algorithms.AES(key),modes.CTR(ctr_init_val),backend=default_backend())
  617. encryptor = c.encryptor()
  618. while True:
  619. q2.put(encryptor.update(q1.get()))
  620. q1.task_done()
  621. def output_worker():
  622. while True:
  623. f.write(q2.get())
  624. q2.task_done()
  625. nbytes = parse_bytespec(nbytes)
  626. if opt.outdir:
  627. outfile = make_full_path(opt.outdir,outfile)
  628. f = open(outfile,'wb')
  629. key = get_random(32)
  630. q1,q2 = Queue(),Queue()
  631. for i in range(max(1,threads-2)):
  632. t = Thread(target=encrypt_worker,args=[i])
  633. t.daemon = True
  634. t.start()
  635. t = Thread(target=output_worker)
  636. t.daemon = True
  637. t.start()
  638. blk_size = 1024 * 1024
  639. for i in range(nbytes // blk_size):
  640. if not i % 4:
  641. msg_r('\rRead: {} bytes'.format(i * blk_size))
  642. q1.put(os.urandom(blk_size))
  643. if nbytes % blk_size:
  644. q1.put(os.urandom(nbytes % blk_size))
  645. q1.join()
  646. q2.join()
  647. f.close()
  648. fsize = os.stat(outfile).st_size
  649. if fsize != nbytes:
  650. die(3,'{}: incorrect random file size (should be {})'.format(fsize,nbytes))
  651. if not silent:
  652. msg('\rRead: {} bytes'.format(nbytes))
  653. qmsg("\r{} byte{} of random data written to file '{}'".format(nbytes,suf(nbytes),outfile))
  654. return True
  655. class MMGenToolCmdWallet(MMGenToolCmds):
  656. "key, address or subseed generation from an MMGen wallet"
  657. def get_subseed(self,subseed_idx:str,wallet=''):
  658. "get the Seed ID of a single subseed by Subseed Index for default or specified wallet"
  659. opt.quiet = True
  660. sf = get_seed_file([wallet] if wallet else [],1)
  661. from .wallet import Wallet
  662. return Wallet(sf).seed.subseed(subseed_idx).sid
  663. def get_subseed_by_seed_id(self,seed_id:str,wallet='',last_idx=g.subseeds):
  664. "get the Subseed Index of a single subseed by Seed ID for default or specified wallet"
  665. opt.quiet = True
  666. sf = get_seed_file([wallet] if wallet else [],1)
  667. from .wallet import Wallet
  668. ret = Wallet(sf).seed.subseed_by_seed_id(seed_id,last_idx)
  669. return ret.ss_idx if ret else None
  670. def list_subseeds(self,subseed_idx_range:str,wallet=''):
  671. "list a range of subseed Seed IDs for default or specified wallet"
  672. opt.quiet = True
  673. sf = get_seed_file([wallet] if wallet else [],1)
  674. from .wallet import Wallet
  675. return Wallet(sf).seed.subseeds.format(*SubSeedIdxRange(subseed_idx_range))
  676. def list_shares(self,
  677. share_count:int,
  678. id_str='default',
  679. master_share:"(min:1, max:{}, 0=no master share)".format(MasterShareIdx.max_val)=0,
  680. wallet=''):
  681. "list the Seed IDs of the shares resulting from a split of default or specified wallet"
  682. opt.quiet = True
  683. sf = get_seed_file([wallet] if wallet else [],1)
  684. from .wallet import Wallet
  685. return Wallet(sf).seed.split(share_count,id_str,master_share).format()
  686. def gen_key(self,mmgen_addr:str,wallet=''):
  687. "generate a single MMGen WIF key from default or specified wallet"
  688. return self.gen_addr(mmgen_addr,wallet,target='wif')
  689. def gen_addr(self,mmgen_addr:str,wallet='',target='addr'):
  690. "generate a single MMGen address from default or specified wallet"
  691. addr = MMGenID(mmgen_addr)
  692. opt.quiet = True
  693. sf = get_seed_file([wallet] if wallet else [],1)
  694. from .wallet import Wallet
  695. ss = Wallet(sf)
  696. if ss.seed.sid != addr.sid:
  697. m = 'Seed ID of requested address ({}) does not match wallet ({})'
  698. die(1,m.format(addr.sid,ss.seed.sid))
  699. al = AddrList(seed=ss.seed,addr_idxs=AddrIdxList(str(addr.idx)),mmtype=addr.mmtype)
  700. d = al.data[0]
  701. ret = d.sec.wif if target=='wif' else d.addr
  702. return ret
  703. from .tw import TwAddrList,TwUnspentOutputs
  704. class MMGenToolCmdRPC(MMGenToolCmds):
  705. "tracking wallet commands using the JSON-RPC interface"
  706. async def getbalance(self,minconf=1,quiet=False,pager=False):
  707. "list confirmed/unconfirmed, spendable/unspendable balances in tracking wallet"
  708. from .tw import TwGetBalance
  709. return (await TwGetBalance(minconf,quiet)).format()
  710. async def listaddress(self,
  711. mmgen_addr:str,
  712. minconf = 1,
  713. pager = False,
  714. showempty = True,
  715. showbtcaddr = True,
  716. age_fmt: _options_annot_str(TwAddrList.age_fmts) = 'confs',
  717. ):
  718. "list the specified MMGen address and its balance"
  719. return await self.listaddresses( mmgen_addrs = mmgen_addr,
  720. minconf = minconf,
  721. pager = pager,
  722. showempty = showempty,
  723. showbtcaddrs = showbtcaddr,
  724. age_fmt = age_fmt,
  725. )
  726. async def listaddresses( self,
  727. mmgen_addrs:'(range or list)' = '',
  728. minconf = 1,
  729. showempty = False,
  730. pager = False,
  731. showbtcaddrs = True,
  732. all_labels = False,
  733. sort:'(valid options: reverse,age)' = '',
  734. age_fmt: _options_annot_str(TwAddrList.age_fmts) = 'confs',
  735. ):
  736. "list MMGen addresses and their balances"
  737. show_age = bool(age_fmt)
  738. if sort:
  739. sort = set(sort.split(','))
  740. sort_params = {'reverse','age'}
  741. if not sort.issubset(sort_params):
  742. die(1,"The sort option takes the following parameters: '{}'".format("','".join(sort_params)))
  743. usr_addr_list = []
  744. if mmgen_addrs:
  745. a = mmgen_addrs.rsplit(':',1)
  746. if len(a) != 2:
  747. m = "'{}': invalid address list argument (must be in form <seed ID>:[<type>:]<idx list>)"
  748. die(1,m.format(mmgen_addrs))
  749. usr_addr_list = [MMGenID('{}:{}'.format(a[0],i)) for i in AddrIdxList(a[1])]
  750. al = await TwAddrList(usr_addr_list,minconf,showempty,showbtcaddrs,all_labels)
  751. if not al:
  752. die(0,('No tracked addresses with balances!','No tracked addresses!')[showempty])
  753. return await al.format(showbtcaddrs,sort,show_age,age_fmt or 'confs')
  754. async def twview( self,
  755. pager = False,
  756. reverse = False,
  757. wide = False,
  758. minconf = 1,
  759. sort = 'age',
  760. age_fmt: _options_annot_str(TwUnspentOutputs.age_fmts) = 'confs',
  761. show_mmid = True,
  762. wide_show_confs = True):
  763. "view tracking wallet"
  764. twuo = await TwUnspentOutputs(minconf=minconf)
  765. await twuo.get_unspent_data(reverse_sort=reverse)
  766. twuo.age_fmt = age_fmt
  767. twuo.show_mmid = show_mmid
  768. if wide:
  769. ret = twuo.format_for_printing(color=True,show_confs=wide_show_confs)
  770. else:
  771. ret = twuo.format_for_display()
  772. del twuo.wallet
  773. return await ret
  774. async def add_label(self,mmgen_or_coin_addr:str,label:str):
  775. "add descriptive label for address in tracking wallet"
  776. from .tw import TrackingWallet
  777. await (await TrackingWallet(mode='w')).add_label(mmgen_or_coin_addr,label,on_fail='raise')
  778. return True
  779. async def remove_label(self,mmgen_or_coin_addr:str):
  780. "remove descriptive label for address in tracking wallet"
  781. await self.add_label(mmgen_or_coin_addr,'')
  782. return True
  783. async def remove_address(self,mmgen_or_coin_addr:str):
  784. "remove an address from tracking wallet"
  785. from .tw import TrackingWallet
  786. ret = await (await TrackingWallet(mode='w')).remove_address(mmgen_or_coin_addr) # returns None on failure
  787. if ret:
  788. msg("Address '{}' deleted from tracking wallet".format(ret))
  789. return ret
  790. class MMGenToolCmdMonero(MMGenToolCmds):
  791. """
  792. Monero wallet utilities
  793. Note that the use of these commands requires private data to be exposed on
  794. a network-connected machine in order to unlock the Monero wallets. This is
  795. a violation of good security practice.
  796. """
  797. _monero_chain_height = None
  798. monerod_args = []
  799. @property
  800. def monero_chain_height(self):
  801. if self._monero_chain_height == None:
  802. from .daemon import CoinDaemon
  803. port = CoinDaemon('xmr',test_suite=g.test_suite).rpc_port
  804. cmd = ['monerod','--rpc-bind-port={}'.format(port)] + self.monerod_args + ['status']
  805. from subprocess import run,PIPE,DEVNULL
  806. cp = run(cmd,stdout=PIPE,stderr=DEVNULL,check=True)
  807. import re
  808. m = re.search(r'Height: (\d+)/\d+ ',cp.stdout.decode())
  809. if not m:
  810. die(1,'Unable to connect to monerod!')
  811. self._monero_chain_height = int(m.group(1))
  812. msg('Chain height: {}'.format(self._monero_chain_height))
  813. return self._monero_chain_height
  814. def keyaddrlist2monerowallets( self,
  815. xmr_keyaddrfile:str,
  816. blockheight:'(default: current height)' = 0,
  817. addrs:'(integer range or list)' = ''):
  818. "create Monero wallets from a key-address list"
  819. return self.monero_wallet_ops( infile = xmr_keyaddrfile,
  820. op = 'create',
  821. blockheight = blockheight,
  822. addrs = addrs)
  823. def syncmonerowallets(self,xmr_keyaddrfile:str,addrs:'(integer range or list)'=''):
  824. "sync Monero wallets from a key-address list"
  825. return self.monero_wallet_ops(infile=xmr_keyaddrfile,op='sync',addrs=addrs)
  826. def monero_wallet_ops(self,infile:str,op:str,blockheight=0,addrs='',monerod_args=[]):
  827. if monerod_args:
  828. self.monerod_args = monerod_args
  829. async def create(n,d,fn,c,m):
  830. try: os.stat(fn)
  831. except: pass
  832. else:
  833. ymsg("Wallet '{}' already exists!".format(fn))
  834. return False
  835. gmsg(m)
  836. from .baseconv import baseconv
  837. ret = await c.call(
  838. 'restore_deterministic_wallet',
  839. filename = os.path.basename(fn),
  840. password = d.wallet_passwd,
  841. seed = baseconv.fromhex(d.sec,'xmrseed',tostr=True),
  842. restore_height = blockheight,
  843. language = 'English' )
  844. pp_msg(ret) if opt.debug else msg(' Address: {}'.format(ret['address']))
  845. return True
  846. async def sync(n,d,fn,c,m):
  847. try:
  848. os.stat(fn)
  849. except:
  850. ymsg("Wallet '{}' does not exist!".format(fn))
  851. return False
  852. chain_height = self.monero_chain_height
  853. gmsg(m)
  854. import time
  855. t_start = time.time()
  856. msg_r(' Opening wallet...')
  857. await c.call(
  858. 'open_wallet',
  859. filename=os.path.basename(fn),
  860. password=d.wallet_passwd )
  861. msg('done')
  862. msg_r(' Getting wallet height...')
  863. wallet_height = (await c.call('get_height'))['height']
  864. msg('\r Wallet height: {} '.format(wallet_height))
  865. behind = chain_height - wallet_height
  866. if behind > 1000:
  867. m = ' Wallet is {} blocks behind chain tip. Please be patient. Syncing...'
  868. msg_r(m.format(behind))
  869. ret = await c.call('refresh')
  870. if behind > 1000:
  871. msg('done')
  872. if ret['received_money']:
  873. msg(' Wallet has received funds')
  874. t_elapsed = int(time.time() - t_start)
  875. ret = await c.call('get_balance') # account_index=0, address_indices=[0,1]
  876. from .obj import XMRAmt
  877. bals[fn] = tuple([XMRAmt(ret[k],from_unit='min_coin_unit') for k in ('balance','unlocked_balance')])
  878. if opt.debug:
  879. pp_msg(ret)
  880. else:
  881. msg(' Balance: {} Unlocked balance: {}'.format(*[b.hl() for b in bals[fn]]))
  882. msg(' Wallet height: {}'.format((await c.call('get_height'))['height']))
  883. msg(' Sync time: {:02}:{:02}'.format(t_elapsed//60,t_elapsed%60))
  884. await c.call('close_wallet')
  885. return True
  886. async def process_wallets(op):
  887. opt.accept_defaults = opt.accept_defaults or op.accept_defaults
  888. from .protocol import init_coin
  889. init_coin('xmr')
  890. from .addr import AddrList
  891. al = KeyAddrList(infile)
  892. data = [d for d in al.data if addrs == '' or d.idx in AddrIdxList(addrs)]
  893. dl = len(data)
  894. assert dl,"No addresses in addrfile within range '{}'".format(addrs)
  895. gmsg('\n{}ing {} wallet{}'.format(op.desc,dl,suf(dl)))
  896. from .daemon import MoneroWalletDaemon
  897. wd = MoneroWalletDaemon(opt.outdir or '.',test_suite=g.test_suite)
  898. wd.restart()
  899. from .rpc import MoneroWalletRPCClient
  900. c = MoneroWalletRPCClient(
  901. host = g.monero_wallet_rpc_host,
  902. port = wd.rpc_port,
  903. user = g.monero_wallet_rpc_user,
  904. passwd = g.monero_wallet_rpc_password)
  905. wallets_processed = 0
  906. for n,d in enumerate(data): # [d.sec,d.wallet_passwd,d.viewkey,d.addr]
  907. fn = os.path.join(
  908. opt.outdir or '.','{}-{}-MoneroWallet{}'.format(
  909. al.al_id.sid,
  910. d.idx,
  911. '-α' if g.debug_utf8 else ''))
  912. info = '\n{}ing wallet {}/{} ({})'.format(op.action,n+1,dl,fn)
  913. wallets_processed += await op.func(n,d,fn,c,info)
  914. wd.stop()
  915. gmsg('\n{} wallet{} {}ed'.format(wallets_processed,suf(wallets_processed),op.desc.lower()))
  916. if wallets_processed and op.name == 'sync':
  917. col1_w = max(map(len,bals)) + 1
  918. fs = '{:%s} {} {}' % col1_w
  919. msg('\n'+fs.format('Wallet','Balance ','Unlocked Balance '))
  920. from .obj import XMRAmt
  921. tbals = [XMRAmt('0'),XMRAmt('0')]
  922. for bal in bals:
  923. for i in (0,1): tbals[i] += bals[bal][i]
  924. msg(fs.format(bal+':',*[XMRAmt(b).fmt(fs='5.12',color=True) for b in bals[bal]]))
  925. msg(fs.format('-'*col1_w,'-'*18,'-'*18))
  926. msg(fs.format('TOTAL:',*[XMRAmt(b).fmt(fs='5.12',color=True) for b in tbals]))
  927. if blockheight < 0:
  928. blockheight = 0 # TODO: handle the non-zero case
  929. bals = {} # locked,unlocked
  930. from collections import namedtuple
  931. wo = namedtuple('mwo',['name','desc','action','func','accept_defaults'])
  932. op = { # reusing name!
  933. 'create': wo('create', 'Creat', 'Generat', create, False),
  934. 'sync': wo('sync', 'Sync', 'Sync', sync, True) }[op]
  935. try:
  936. run_session(process_wallets(op),do_rpc_init=False)
  937. except KeyboardInterrupt:
  938. rdie(1,'\nUser interrupt\n')
  939. except EOFError:
  940. rdie(2,'\nEnd of file\n')
  941. except Exception as e:
  942. try:
  943. die(1,'Error: {}'.format(e.args[0]))
  944. except:
  945. rdie(1,'Error: {!r}'.format(e.args[0]))
  946. return True
  947. class tool_api(
  948. MMGenToolCmdUtil,
  949. MMGenToolCmdCoin,
  950. MMGenToolCmdMnemonic,
  951. ):
  952. """
  953. API providing access to a subset of methods from the mmgen.tool module
  954. Example:
  955. from mmgen.tool import tool_api
  956. tool = tool_api()
  957. # Set the coin and network:
  958. tool.init_coin('btc','mainnet')
  959. # Print available address types:
  960. tool.print_addrtypes()
  961. # Set the address type:
  962. tool.addrtype = 'segwit'
  963. # Disable user entropy gathering (optional, reduces security):
  964. tool.usr_randchars = 0
  965. # Generate a random BTC segwit keypair:
  966. wif,addr = tool.randpair()
  967. # Set coin, network and address type:
  968. tool.init_coin('ltc','testnet')
  969. tool.addrtype = 'bech32'
  970. # Generate a random LTC testnet Bech32 keypair:
  971. wif,addr = tool.randpair()
  972. """
  973. def __init__(self):
  974. """
  975. Initializer - takes no arguments
  976. """
  977. if not hasattr(opt,'version'):
  978. opts.init({'text': { 'desc': '', 'usage':'', 'options':'' }})
  979. opt.use_old_ed25519 = None
  980. opt.type = None
  981. def init_coin(self,coinsym,network):
  982. """
  983. Initialize a coin/network pair
  984. Valid choices for coins: one of the symbols returned by the 'coins' attribute
  985. Valid choices for network: 'mainnet','testnet','regtest'
  986. """
  987. from .protocol import init_coin,init_genonly_altcoins
  988. altcoin_trust_level = init_genonly_altcoins(coinsym,testnet=network in ('testnet','regtest'))
  989. warn_altcoins(coinsym,altcoin_trust_level)
  990. return init_coin(coinsym,{'mainnet':False,'testnet':True,'regtest':True}[network])
  991. @property
  992. def coins(self):
  993. """The available coins"""
  994. from .protocol import CoinProtocol
  995. from .altcoin import CoinInfo
  996. return sorted(set(
  997. [c.upper() for c in CoinProtocol.coins]
  998. + [c.symbol for c in CoinInfo.get_supported_coins(g.proto.network)]
  999. ))
  1000. @property
  1001. def coin(self):
  1002. """The currently configured coin"""
  1003. return g.coin
  1004. @property
  1005. def network(self):
  1006. """The currently configured network"""
  1007. return g.proto.network
  1008. @property
  1009. def addrtypes(self):
  1010. """
  1011. The available address types for current coin/network pair. The
  1012. first-listed is the default
  1013. """
  1014. return [MMGenAddrType(t).name for t in g.proto.mmtypes]
  1015. def print_addrtypes(self):
  1016. """
  1017. Print the available address types for current coin/network pair along with
  1018. a description. The first-listed is the default
  1019. """
  1020. for t in [MMGenAddrType(s) for s in g.proto.mmtypes]:
  1021. print('{:<12} - {}'.format(t.name,t.desc))
  1022. @property
  1023. def addrtype(self):
  1024. """The currently configured address type (is assignable)"""
  1025. return opt.type
  1026. @addrtype.setter
  1027. def addrtype(self,val):
  1028. opt.type = val
  1029. @property
  1030. def usr_randchars(self):
  1031. """
  1032. The number of keystrokes of entropy to be gathered from the user.
  1033. Setting to zero disables user entropy gathering.
  1034. """
  1035. return opt.usr_randchars
  1036. @usr_randchars.setter
  1037. def usr_randchars(self,val):
  1038. opt.usr_randchars = val