tool.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  5. # Copyright (C)2013-2017 Philemon <mmgen-py@yandex.com>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. tool.py: Routines and data for the 'mmgen-tool' utility
  21. """
  22. import binascii
  23. from mmgen.protocol import hash160
  24. from mmgen.common import *
  25. from mmgen.crypto import *
  26. from mmgen.tx import *
  27. from mmgen.addr import *
  28. pnm = g.proj_name
  29. from collections import OrderedDict
  30. cmd_data = OrderedDict([
  31. ('Help', ['<tool command> [str]']),
  32. ('Usage', ['<tool command> [str]']),
  33. ('Strtob58', ['<string> [str-]','pad [int=0]']),
  34. ('B58tostr', ['<b58 number> [str-]']),
  35. ('Hextob58', ['<hex number> [str-]','pad [int=0]']),
  36. ('B58tohex', ['<b58 number> [str-]','pad [int=0]']),
  37. ('B58randenc', []),
  38. ('B32tohex', ['<b32 num> [str-]','pad [int=0]']),
  39. ('Hextob32', ['<hex num> [str-]','pad [int=0]']),
  40. ('Randhex', ['nbytes [int=32]']),
  41. ('Id8', ['<infile> [str]']),
  42. ('Id6', ['<infile> [str]']),
  43. ('Hash160', ['<hexadecimal string> [str-]']),
  44. ('Hash256', ['<str, hexstr or filename> [str]', # TODO handle stdin
  45. 'hex_input [bool=False]','file_input [bool=False]']),
  46. ('Str2id6', ['<string (spaces are ignored)> [str-]']),
  47. ('Hexdump', ['<infile> [str]', 'cols [int=8]', 'line_nums [bool=True]']),
  48. ('Unhexdump', ['<infile> [str]']),
  49. ('Hexreverse', ['<hexadecimal string> [str-]']),
  50. ('Hexlify', ['<string> [str-]']),
  51. ('Rand2file', ['<outfile> [str]','<nbytes> [str]','threads [int=4]','silent [bool=False]']),
  52. ('Randwif', []),
  53. ('Randpair', []),
  54. ('Hex2wif', ['<private key in hex format> [str-]']),
  55. ('Wif2hex', ['<wif> [str-]']),
  56. ('Wif2addr', ['<wif> [str-]']),
  57. ('Wif2segwit_pair',['<wif> [str-]']),
  58. ('Pubhash2addr', ['<coin address in hex format> [str-]']),
  59. ('Addr2hexaddr', ['<coin address> [str-]']),
  60. ('Privhex2addr', ['<private key in hex format> [str-]']),
  61. ('Privhex2pubhex',['<private key in hex format> [str-]']),
  62. ('Pubhex2addr', ['<public key in hex format> [str-]']), # new
  63. ('Pubhex2redeem_script',['<public key in hex format> [str-]']), # new
  64. ('Wif2redeem_script', ['<private key in WIF format> [str-]']), # new
  65. ('Hex2mn', ['<hexadecimal string> [str-]',"wordlist [str='electrum']"]),
  66. ('Mn2hex', ['<mnemonic> [str-]', "wordlist [str='electrum']"]),
  67. ('Mn_rand128', ["wordlist [str='electrum']"]),
  68. ('Mn_rand192', ["wordlist [str='electrum']"]),
  69. ('Mn_rand256', ["wordlist [str='electrum']"]),
  70. ('Mn_stats', ["wordlist [str='electrum']"]),
  71. ('Mn_printlist', ["wordlist [str='electrum']"]),
  72. ('Listaddress',['<{} address> [str]'.format(pnm),'minconf [int=1]','pager [bool=False]','showempty [bool=True]''showbtcaddr [bool=True]']),
  73. ('Listaddresses',["addrs [str='']",'minconf [int=1]','showempty [bool=False]','pager [bool=False]','showbtcaddrs [bool=True]','all_labels [bool=False]',"sort [str=''] (options: reverse, age)"]),
  74. ('Getbalance', ['minconf [int=1]','quiet [bool=False]']),
  75. ('Txview', ['<{} TX file(s)> [str]'.format(pnm),'pager [bool=False]','terse [bool=False]',"sort [str='mtime'] (options: ctime, atime)",'MARGS']),
  76. ('Twview', ["sort [str='age']",'reverse [bool=False]','show_days [bool=True]','show_mmid [bool=True]','minconf [int=1]','wide [bool=False]','pager [bool=False]']),
  77. ('Add_label', ['<{} address> [str]'.format(pnm),'<label> [str]']),
  78. ('Remove_label', ['<{} address> [str]'.format(pnm)]),
  79. ('Addrfile_chksum', ['<{} addr file> [str]'.format(pnm),"mmtype [str='']"]),
  80. ('Keyaddrfile_chksum', ['<{} addr file> [str]'.format(pnm),"mmtype [str='']"]),
  81. ('Passwdfile_chksum', ['<{} password file> [str]'.format(pnm)]),
  82. ('Find_incog_data', ['<file or device name> [str]','<Incog ID> [str]','keep_searching [bool=False]']),
  83. ('Encrypt', ['<infile> [str]',"outfile [str='']","hash_preset [str='']"]),
  84. ('Decrypt', ['<infile> [str]',"outfile [str='']","hash_preset [str='']"]),
  85. ('Bytespec', ['<bytespec> [str]']),
  86. ('Regtest_setup',[]),
  87. ])
  88. def usage(command):
  89. for v in cmd_data.values():
  90. if v and v[0][-2:] == '-]':
  91. v[0] = v[0][:-2] + ' or STDIN]'
  92. if 'MARGS' in v: v.remove('MARGS')
  93. if not command:
  94. Msg('Usage information for mmgen-tool commands:')
  95. for k,v in cmd_data.items():
  96. Msg(' {:18} {}'.format(k.lower(),' '.join(v)))
  97. from mmgen.main_tool import stdin_msg
  98. Msg('\n '+'\n '.join(stdin_msg.split('\n')))
  99. sys.exit(0)
  100. Command = command.capitalize()
  101. if Command in cmd_data:
  102. import re
  103. from mmgen.main_tool import cmd_help
  104. for line in cmd_help.split('\n'):
  105. if re.match(r'\s+{}\s+'.format(command),line):
  106. c,h = line.split('-',1)
  107. Msg('MMGEN-TOOL {}: {}'.format(c.strip().upper(),h.strip()))
  108. cd = cmd_data[Command]
  109. msg('USAGE: {} {} {}'.format(g.prog_name,command,' '.join(cd)))
  110. else:
  111. msg("'{}': no such tool command".format(command))
  112. sys.exit(1)
  113. Help = usage
  114. def process_args(command,cmd_args):
  115. if 'MARGS' in cmd_data[command]:
  116. cmd_data[command].remove('MARGS')
  117. margs = True
  118. else:
  119. margs = False
  120. c_args = [[i.split(' [')[0],i.split(' [')[1][:-1]]
  121. for i in cmd_data[command] if '=' not in i]
  122. c_kwargs = dict([[
  123. i.split(' [')[0],
  124. [i.split(' [')[1].split('=')[0],i.split(' [')[1].split('=')[1][:-1]]
  125. ] for i in cmd_data[command] if '=' in i])
  126. if not margs:
  127. u_args = [a for a in cmd_args[:len(c_args)]]
  128. if c_args and c_args[0][1][-1] == '-':
  129. c_args[0][1] = c_args[0][1][:-1] # [str-] -> [str]
  130. # If we're reading from a pipe, replace '-' with output of previous command
  131. if u_args and u_args[0] == '-':
  132. if not sys.stdin.isatty():
  133. u_args[0] = sys.stdin.read().strip()
  134. if not u_args[0]:
  135. die(2,'{}: ERROR: no output from previous command in pipe'.format(command.lower()))
  136. if not margs and len(u_args) < len(c_args):
  137. m1 = 'Command requires exactly {} non-keyword argument{}'
  138. msg(m1.format(len(c_args),suf(c_args,'s')))
  139. usage(command)
  140. extra_args = len(cmd_args) - len(c_args)
  141. u_kwargs = {}
  142. if margs:
  143. t = [a.split('=') for a in cmd_args if '=' in a]
  144. tk = [a[0] for a in t]
  145. tk_bad = [a for a in tk if a not in c_kwargs]
  146. if set(tk_bad) != set(tk[:len(tk_bad)]):
  147. die(1,"'{}': illegal keyword argument".format(tk_bad[-1]))
  148. u_kwargs = dict(t[len(tk_bad):])
  149. u_args = cmd_args[:-len(u_kwargs) or None]
  150. elif extra_args > 0:
  151. u_kwargs = dict([a.split('=') for a in cmd_args[len(c_args):] if '=' in a])
  152. if len(u_kwargs) != extra_args:
  153. msg('Command requires exactly {} non-keyword argument{}'.format(len(c_args),suf(c_args,'s')))
  154. usage(command)
  155. if len(u_kwargs) > len(c_kwargs):
  156. msg('Command requires exactly {} keyword argument{}'.format(len(c_kwargs),suf(c_kwargs,'s')))
  157. usage(command)
  158. # mdie(c_args,c_kwargs,u_args,u_kwargs)
  159. for k in u_kwargs:
  160. if k not in c_kwargs:
  161. msg("'{}': invalid keyword argument".format(k))
  162. usage(command)
  163. def conv_type(arg,arg_name,arg_type):
  164. if arg_type == 'str': arg_type = 'unicode'
  165. if arg_type == 'bool':
  166. if arg.lower() in ('true','yes','1','on'): arg = True
  167. elif arg.lower() in ('false','no','0','off'): arg = False
  168. else:
  169. msg("'{}': invalid boolean value for keyword argument".format(arg))
  170. usage(command)
  171. try:
  172. return __builtins__[arg_type](arg)
  173. except:
  174. die(1,"'{}': Invalid argument for argument {} ('{}' required)".format(arg,arg_name,arg_type))
  175. if margs:
  176. args = [conv_type(u_args[i],c_args[0][0],c_args[0][1]) for i in range(len(u_args))]
  177. else:
  178. args = [conv_type(u_args[i],c_args[i][0],c_args[i][1]) for i in range(len(c_args))]
  179. kwargs = dict([(k,conv_type(u_kwargs[k],k,c_kwargs[k][0])) for k in u_kwargs])
  180. return args,kwargs
  181. # Individual cmd_data
  182. def are_equal(a,b,dtype=''):
  183. if dtype == 'str': return a.lstrip('\0') == b.lstrip('\0')
  184. if dtype == 'hex': return a.lstrip('0') == b.lstrip('0')
  185. if dtype == 'b58': return a.lstrip('1') == b.lstrip('1')
  186. else: return a == b
  187. def print_convert_results(indata,enc,dec,dtype):
  188. error = (True,False)[are_equal(indata,dec,dtype)]
  189. if error or opt.verbose:
  190. Msg('Input: {}'.format(repr(indata)))
  191. Msg('Encoded data: {}'.format(repr(enc)))
  192. Msg('Recoded data: {}'.format(repr(dec)))
  193. else: Msg(enc)
  194. if error:
  195. die(3,"Error! Recoded data doesn't match input!")
  196. from mmgen.obj import MMGenAddrType
  197. at = MMGenAddrType((hasattr(opt,'type') and opt.type) or g.proto.dfl_mmtype)
  198. kg = KeyGenerator(at.pubkey_type)
  199. ag = AddrGenerator(at.gen_method)
  200. def Hexdump(infile,cols=8,line_nums=True):
  201. Msg(pretty_hexdump(
  202. get_data_from_file(infile,dash=True,silent=True,binary=True),
  203. cols=cols,line_nums=line_nums))
  204. def Unhexdump(infile):
  205. if g.platform == 'win':
  206. import msvcrt
  207. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  208. sys.stdout.write(decode_pretty_hexdump(
  209. get_data_from_file(infile,dash=True,silent=True)))
  210. def B58randenc():
  211. r = get_random(32)
  212. enc = baseconv.b58encode(r,pad=True)
  213. dec = baseconv.b58decode(enc,pad=True)
  214. print_convert_results(r,enc,dec,'str')
  215. def Randhex(nbytes='32'):
  216. Msg(binascii.hexlify(get_random(int(nbytes))))
  217. def Randwif():
  218. Msg(PrivKey(get_random(32),pubkey_type=at.pubkey_type,compressed=at.compressed).wif)
  219. def Randpair():
  220. privhex = PrivKey(get_random(32),pubkey_type=at.pubkey_type,compressed=at.compressed)
  221. addr = ag.to_addr(kg.to_pubhex(privhex))
  222. Vmsg('Key (hex): {}'.format(privhex))
  223. Vmsg_r('Key (WIF): '); Msg(privhex.wif)
  224. Vmsg_r('Addr: '); Msg(addr)
  225. def Wif2addr(wif):
  226. privhex = PrivKey(wif=wif)
  227. addr = ag.to_addr(kg.to_pubhex(privhex))
  228. Vmsg_r('Addr: '); Msg(addr)
  229. def Wif2segwit_pair(wif):
  230. pubhex = kg.to_pubhex(PrivKey(wif=wif))
  231. addr = ag.to_addr(pubhex)
  232. rs = ag.to_segwit_redeem_script(pubhex)
  233. Msg('{}\n{}'.format(rs,addr))
  234. def Pubhash2addr(pubhash):
  235. Msg(g.proto.pubhash2addr(pubhash,at.addr_fmt=='p2sh'))
  236. def Addr2hexaddr(addr): Msg(g.proto.verify_addr(addr,CoinAddr.hex_width,return_dict=True)['hex'])
  237. def Hash160(pubkeyhex): Msg(hash160(pubkeyhex))
  238. def Pubhex2addr(pubkeyhex): Pubhash2addr(hash160(pubkeyhex))
  239. def Wif2hex(wif): Msg(PrivKey(wif=wif))
  240. def Hex2wif(hexpriv):
  241. Msg(g.proto.hex2wif(hexpriv,pubkey_type=at.pubkey_type,compressed=at.compressed))
  242. def Privhex2addr(privhex,output_pubhex=False):
  243. pk = PrivKey(binascii.unhexlify(privhex),compressed=at.compressed,pubkey_type=at.pubkey_type)
  244. ph = kg.to_pubhex(pk)
  245. Msg(ph if output_pubhex else ag.to_addr(ph))
  246. def Privhex2pubhex(privhex): # new
  247. Privhex2addr(privhex,output_pubhex=True)
  248. def Pubhex2redeem_script(pubhex): # new
  249. Msg(g.proto.pubhex2redeem_script(pubhex))
  250. def Wif2redeem_script(wif): # new
  251. privhex = PrivKey(wif=wif)
  252. Msg(ag.to_segwit_redeem_script(kg.to_pubhex(privhex)))
  253. wordlists = 'electrum','tirosh'
  254. dfl_wl_id = 'electrum'
  255. def do_random_mn(nbytes,wordlist):
  256. hexrand = binascii.hexlify(get_random(nbytes))
  257. Vmsg('Seed: {}'.format(hexrand))
  258. for wl_id in ([wordlist],wordlists)[wordlist=='all']:
  259. if wordlist == 'all':
  260. Msg('{} mnemonic:'.format(capfirst(wl_id)))
  261. mn = baseconv.fromhex(hexrand,wl_id)
  262. Msg(' '.join(mn))
  263. def Mn_rand128(wordlist=dfl_wl_id): do_random_mn(16,wordlist)
  264. def Mn_rand192(wordlist=dfl_wl_id): do_random_mn(24,wordlist)
  265. def Mn_rand256(wordlist=dfl_wl_id): do_random_mn(32,wordlist)
  266. def Hex2mn(s,wordlist=dfl_wl_id): Msg(' '.join(baseconv.fromhex(s,wordlist)))
  267. def Mn2hex(s,wordlist=dfl_wl_id): Msg(baseconv.tohex(s.split(),wordlist))
  268. def Strtob58(s,pad=None): Msg(''.join(baseconv.fromhex(binascii.hexlify(s),'b58',pad)))
  269. def Hextob58(s,pad=None): Msg(''.join(baseconv.fromhex(s,'b58',pad)))
  270. def Hextob32(s,pad=None): Msg(''.join(baseconv.fromhex(s,'b32',pad)))
  271. def B58tostr(s): Msg(binascii.unhexlify(baseconv.tohex(s,'b58')))
  272. def B58tohex(s,pad=None): Msg(baseconv.tohex(s,'b58',pad))
  273. def B32tohex(s,pad=None): Msg(baseconv.tohex(s.upper(),'b32',pad))
  274. from mmgen.seed import Mnemonic
  275. def Mn_stats(wordlist=dfl_wl_id):
  276. wordlist in baseconv.digits or die(1,"'{}': not a valid wordlist".format(wordlist))
  277. baseconv.check_wordlist(wordlist)
  278. def Mn_printlist(wordlist=dfl_wl_id):
  279. wordlist in baseconv.digits or die(1,"'{}': not a valid wordlist".format(wordlist))
  280. Msg('\n'.join(baseconv.digits[wordlist]))
  281. def Id8(infile):
  282. Msg(make_chksum_8(
  283. get_data_from_file(infile,dash=True,silent=True,binary=True)
  284. ))
  285. def Id6(infile):
  286. Msg(make_chksum_6(
  287. get_data_from_file(infile,dash=True,silent=True,binary=True)
  288. ))
  289. def Str2id6(s): # retain ignoring of space for backwards compat
  290. Msg(make_chksum_6(''.join(s.split())))
  291. def Addrfile_chksum(infile,mmtype=''):
  292. from mmgen.addr import AddrList
  293. mmtype = None if not mmtype else MMGenAddrType(mmtype)
  294. AddrList(infile,chksum_only=True,mmtype=mmtype)
  295. def Keyaddrfile_chksum(infile,mmtype=''):
  296. from mmgen.addr import KeyAddrList
  297. mmtype = None if not mmtype else MMGenAddrType(mmtype)
  298. KeyAddrList(infile,chksum_only=True,mmtype=mmtype)
  299. def Passwdfile_chksum(infile):
  300. from mmgen.addr import PasswordList
  301. PasswordList(infile=infile,chksum_only=True)
  302. def Hexreverse(s):
  303. Msg(binascii.hexlify(binascii.unhexlify(s.strip())[::-1]))
  304. def Hexlify(s):
  305. Msg(binascii.hexlify(s))
  306. def Hash256(s,file_input=False,hex_input=False):
  307. from hashlib import sha256
  308. if file_input: b = get_data_from_file(s,binary=True)
  309. elif hex_input: b = decode_pretty_hexdump(s)
  310. else: b = s
  311. Msg(sha256(sha256(b).digest()).hexdigest())
  312. def Encrypt(infile,outfile='',hash_preset=''):
  313. data = get_data_from_file(infile,'data for encryption',binary=True)
  314. enc_d = mmgen_encrypt(data,'user data',hash_preset)
  315. if not outfile:
  316. outfile = '{}.{}'.format(os.path.basename(infile),g.mmenc_ext)
  317. write_data_to_file(outfile,enc_d,'encrypted data',binary=True)
  318. def Decrypt(infile,outfile='',hash_preset=''):
  319. enc_d = get_data_from_file(infile,'encrypted data',binary=True)
  320. while True:
  321. dec_d = mmgen_decrypt(enc_d,'user data',hash_preset)
  322. if dec_d: break
  323. msg('Trying again...')
  324. if not outfile:
  325. o = os.path.basename(infile)
  326. outfile = remove_extension(o,g.mmenc_ext)
  327. if outfile == o: outfile += '.dec'
  328. write_data_to_file(outfile,dec_d,'decrypted data',binary=True)
  329. def Find_incog_data(filename,iv_id,keep_searching=False):
  330. ivsize,bsize,mod = g.aesctr_iv_len,4096,4096*8
  331. n,carry = 0,' '*ivsize
  332. flgs = os.O_RDONLY|os.O_BINARY if g.platform == 'win' else os.O_RDONLY
  333. f = os.open(filename,flgs)
  334. for ch in iv_id:
  335. if ch not in '0123456789ABCDEF':
  336. die(2,"'{}': invalid Incog ID".format(iv_id))
  337. while True:
  338. d = os.read(f,bsize)
  339. if not d: break
  340. d = carry + d
  341. for i in range(bsize):
  342. if sha256(d[i:i+ivsize]).hexdigest()[:8].upper() == iv_id:
  343. if n+i < ivsize: continue
  344. msg('\rIncog data for ID {} found at offset {}'.format(iv_id,n+i-ivsize))
  345. if not keep_searching: sys.exit(0)
  346. carry = d[len(d)-ivsize:]
  347. n += bsize
  348. if not n % mod:
  349. msg_r('\rSearched: {} bytes'.format(n))
  350. msg('')
  351. os.close(f)
  352. def Rand2file(outfile,nbytes,threads=4,silent=False):
  353. nbytes = parse_nbytes(nbytes)
  354. from Crypto import Random
  355. rh = Random.new()
  356. from Queue import Queue
  357. from threading import Thread
  358. bsize = 2**20
  359. roll = bsize * 4
  360. if opt.outdir: outfile = make_full_path(opt.outdir,outfile)
  361. f = open(outfile,'wb')
  362. from Crypto.Cipher import AES
  363. from Crypto.Util import Counter
  364. key = get_random(32)
  365. def encrypt_worker(wid):
  366. while True:
  367. i,d = q1.get()
  368. c = AES.new(key,AES.MODE_CTR,counter=Counter.new(g.aesctr_iv_len*8,initial_value=i))
  369. enc_data = c.encrypt(d)
  370. q2.put(enc_data)
  371. q1.task_done()
  372. def output_worker():
  373. while True:
  374. data = q2.get()
  375. f.write(data)
  376. q2.task_done()
  377. q1 = Queue()
  378. for i in range(max(1,threads-2)):
  379. t = Thread(target=encrypt_worker,args=(i,))
  380. t.daemon = True
  381. t.start()
  382. q2 = Queue()
  383. t = Thread(target=output_worker)
  384. t.daemon = True
  385. t.start()
  386. i = 1; rbytes = nbytes
  387. while rbytes > 0:
  388. d = rh.read(min(bsize,rbytes))
  389. q1.put((i,d))
  390. rbytes -= bsize
  391. i += 1
  392. if not (bsize*i) % roll:
  393. msg_r('\rRead: {} bytes'.format(bsize*i))
  394. if not silent:
  395. msg('\rRead: {} bytes'.format(nbytes))
  396. qmsg("\r{} bytes of random data written to file '{}'".format(nbytes,outfile))
  397. q1.join()
  398. q2.join()
  399. f.close()
  400. def Bytespec(s): Msg(str(parse_nbytes(s)))
  401. def Regtest_setup():
  402. print 'ok'
  403. return
  404. import subprocess as sp
  405. sp.check_output()
  406. pass
  407. # ================ RPC commands ================== #
  408. def Listaddress(addr,minconf=1,pager=False,showempty=True,showbtcaddr=True):
  409. return Listaddresses(addrs=addr,minconf=minconf,pager=pager,showempty=showempty,showbtcaddrs=showbtcaddr)
  410. # List MMGen addresses and their balances. TODO: move this code to AddrList
  411. def Listaddresses(addrs='',minconf=1,showempty=False,pager=False,showbtcaddrs=True,all_labels=False,sort=None):
  412. if sort:
  413. sort = set(sort.split(','))
  414. sort_params = set(['reverse','age'])
  415. if not sort.issubset(sort_params):
  416. die(1,"The sort option takes the following parameters: '{}'".format("','".join(sort_params)))
  417. rpc_init()
  418. def check_dup_mmid(acct_labels):
  419. mmid_prev,err = None,False
  420. for mmid in sorted(a.mmid for a in acct_labels if a):
  421. if mmid == mmid_prev:
  422. err = True
  423. msg('Duplicate MMGen ID ({}) discovered in tracking wallet!\n'.format(mmid))
  424. mmid_prev = mmid
  425. if err: rdie(3,'Tracking wallet is corrupted!')
  426. def check_addr_array_lens(acct_pairs):
  427. err = False
  428. for label,addrs in acct_pairs:
  429. if not label: continue
  430. if len(addrs) != 1:
  431. err = True
  432. if len(addrs) == 0:
  433. msg("Label '{}': has no associated address!".format(label))
  434. else:
  435. msg("'{}': more than one {} address in account!".format(addrs,g.coin))
  436. if err: rdie(3,'Tracking wallet is corrupted!')
  437. usr_addr_list = []
  438. if addrs:
  439. a = addrs.rsplit(':',1)
  440. if len(a) != 2:
  441. m = "'{}': invalid address list argument (must be in form <seed ID>:[<type>:]<idx list>)"
  442. die(1,m.format(addrs))
  443. usr_addr_list = [MMGenID('{}:{}'.format(a[0],i)) for i in AddrIdxList(a[1])]
  444. class TwAddrList(dict,MMGenObject): pass
  445. addrs = TwAddrList() # reusing name!
  446. total = g.proto.coin_amt('0')
  447. for d in g.rpch.listunspent(0):
  448. if not 'account' in d: continue # skip coinbase outputs with missing account
  449. if d['confirmations'] < minconf: continue
  450. label = TwLabel(d['account'],on_fail='silent')
  451. if label:
  452. if usr_addr_list and (label.mmid not in usr_addr_list): continue
  453. if label.mmid in addrs:
  454. if addrs[label.mmid]['addr'] != d['address']:
  455. die(2,'duplicate {} address ({}) for this MMGen address! ({})'.format(
  456. g.coin,d['address'],addrs[label.mmid]['addr']))
  457. else:
  458. addrs[label.mmid] = {'amt': g.proto.coin_amt('0'),
  459. 'lbl': label,
  460. 'addr': CoinAddr(d['address'])}
  461. addrs[label.mmid]['lbl'].mmid.confs = d['confirmations']
  462. addrs[label.mmid]['amt'] += d['amount']
  463. total += d['amount']
  464. # We use listaccounts only for empty addresses, as it shows false positive balances
  465. if showempty or all_labels:
  466. # for compatibility with old mmids, must use raw RPC rather than native data for matching
  467. # args: minconf,watchonly, MUST use keys() so we get list, not dict
  468. acct_list = g.rpch.listaccounts(0,True).keys() # raw list, no 'L'
  469. acct_labels = MMGenList([TwLabel(a,on_fail='silent') for a in acct_list])
  470. check_dup_mmid(acct_labels)
  471. acct_addrs = g.rpch.getaddressesbyaccount([[a] for a in acct_list],batch=True) # use raw list here
  472. assert len(acct_list) == len(acct_addrs),'listaccounts() and getaddressesbyaccount() not equal in length'
  473. addr_pairs = zip(acct_labels,acct_addrs)
  474. check_addr_array_lens(addr_pairs)
  475. for label,addr_arr in addr_pairs:
  476. if not label: continue
  477. if all_labels and not showempty and not label.comment: continue
  478. if usr_addr_list and (label.mmid not in usr_addr_list): continue
  479. if label.mmid not in addrs:
  480. addrs[label.mmid] = { 'amt':g.proto.coin_amt('0'), 'lbl':label, 'addr':'' }
  481. if showbtcaddrs:
  482. addrs[label.mmid]['addr'] = CoinAddr(addr_arr[0])
  483. if not addrs:
  484. die(0,('No tracked addresses with balances!','No tracked addresses!')[showempty])
  485. out = ([],[green('Chain: {}'.format(g.chain.upper()))])[g.chain in ('testnet','regtest')]
  486. fs = ('{mid} {cmt} {amt}','{mid} {addr} {cmt} {amt}')[showbtcaddrs]
  487. mmaddrs = [k for k in addrs.keys() if k.type == 'mmgen']
  488. max_mmid_len = max(len(k) for k in mmaddrs) + 2 if mmaddrs else 10
  489. max_cmt_len = max(max(len(addrs[k]['lbl'].comment) for k in addrs),7)
  490. out += [fs.format(
  491. mid=MMGenID.fmtc('MMGenID',width=max_mmid_len),
  492. addr=CoinAddr.fmtc('ADDRESS'),
  493. cmt=TwComment.fmtc('COMMENT',width=max_cmt_len),
  494. amt='BALANCE'
  495. )]
  496. def sort_algo(j):
  497. if sort and 'age' in sort:
  498. return '{}_{:>012}_{}'.format(
  499. j.obj.rsplit(':',1)[0],
  500. (1000000000-j.confs if hasattr(j,'confs') else 0), # Hack, but OK for the foreseeable future
  501. j.sort_key)
  502. else:
  503. return j.sort_key
  504. al_id_save = None
  505. for mmid in sorted(addrs,key=sort_algo,reverse=bool(sort and 'reverse' in sort)):
  506. if mmid.type == 'mmgen':
  507. if al_id_save and al_id_save != mmid.obj.al_id:
  508. out.append('')
  509. al_id_save = mmid.obj.al_id
  510. mmid_disp = mmid
  511. else:
  512. if al_id_save:
  513. out.append('')
  514. al_id_save = None
  515. mmid_disp = 'Non-MMGen'
  516. out.append(fs.format(
  517. mid = MMGenID.fmtc(mmid_disp,width=max_mmid_len,color=True),
  518. addr=(addrs[mmid]['addr'].fmt(color=True) if showbtcaddrs else None),
  519. cmt=addrs[mmid]['lbl'].comment.fmt(width=max_cmt_len,color=True,nullrepl='-'),
  520. amt=addrs[mmid]['amt'].fmt('3.0',color=True)))
  521. out.append('\nTOTAL: {} {}'.format(total.hl(color=True),g.coin))
  522. o = '\n'.join(out)
  523. return do_pager(o) if pager else Msg(o)
  524. def Getbalance(minconf=1,quiet=False,return_val=False):
  525. rpc_init()
  526. accts = {}
  527. for d in g.rpch.listunspent(0):
  528. ma = split2(d['account'] if 'account' in d else '')[0] # include coinbase outputs if spendable
  529. keys = ['TOTAL']
  530. if d['spendable']: keys += ['SPENDABLE']
  531. if is_mmgen_id(ma): keys += [ma.split(':')[0]]
  532. confs = d['confirmations']
  533. i = (1,2)[confs >= minconf]
  534. for key in keys:
  535. if key not in accts: accts[key] = [g.proto.coin_amt('0')] * 3
  536. for j in ([],[0])[confs==0] + [i]:
  537. accts[key][j] += d['amount']
  538. if quiet:
  539. o = ['{}'.format(accts['TOTAL'][2] if accts else g.proto.coin_amt('0'))]
  540. else:
  541. fs = '{:13} {} {} {}'
  542. mc,lbl = str(minconf),'confirms'
  543. o = [fs.format(
  544. 'Wallet',
  545. *[s.ljust(16) for s in ' Unconfirmed',' <{} {}'.format(mc,lbl),' >={} {}'.format(mc,lbl)])]
  546. for key in sorted(accts.keys()):
  547. o += [fs.format(key+':', *[a.fmt(color=True,suf=' '+g.coin) for a in accts[key]])]
  548. if 'SPENDABLE' in accts:
  549. Msg(red('Warning: this wallet contains PRIVATE KEYS for the SPENDABLE balance!'))
  550. o = '\n'.join(o)
  551. if return_val: return o
  552. else: Msg(o)
  553. def Txview(*infiles,**kwargs):
  554. from mmgen.filename import MMGenFileList
  555. pager = 'pager' in kwargs and kwargs['pager']
  556. terse = 'terse' in kwargs and kwargs['terse']
  557. sort_key = kwargs['sort'] if 'sort' in kwargs else 'mtime'
  558. flist = MMGenFileList(infiles,ftype=MMGenTX)
  559. flist.sort_by_age(key=sort_key) # in-place sort
  560. from mmgen.term import get_terminal_size
  561. sep = u'—'*77+'\n'
  562. out = sep.join([MMGenTX(fn).format_view(terse=terse) for fn in flist.names()])
  563. (Msg,do_pager)[pager](out.rstrip())
  564. def Twview(pager=False,reverse=False,wide=False,minconf=1,sort='age',show_days=True,show_mmid=True):
  565. rpc_init()
  566. from mmgen.tw import MMGenTrackingWallet
  567. tw = MMGenTrackingWallet(minconf=minconf)
  568. tw.do_sort(sort,reverse=reverse)
  569. tw.show_days = show_days
  570. tw.show_mmid = show_mmid
  571. out = tw.format_for_printing(color=True) if wide else tw.format_for_display()
  572. (Msg_r,do_pager)[pager](out)
  573. def Add_label(mmaddr,label):
  574. rpc_init()
  575. from mmgen.tw import MMGenTrackingWallet
  576. MMGenTrackingWallet.add_label(mmaddr,label) # dies on failure
  577. def Remove_label(mmaddr): Add_label(mmaddr,'')