msg.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen
  9. # https://gitlab.com/mmgen/mmgen
  10. """
  11. msg: base message signing classes
  12. """
  13. import os,importlib,json
  14. from .globalvars import g
  15. from .objmethods import MMGenObject,Hilite,InitErrors
  16. from .util import msg,die,suf,make_chksum_6,fmt_list,remove_dups
  17. from .color import red,orange,grnbg
  18. from .protocol import init_proto
  19. from .fileutil import get_data_from_file,write_data_to_file
  20. from .addr import MMGenID,CoinAddr
  21. class MMGenIDRange(str,Hilite,InitErrors,MMGenObject):
  22. """
  23. closely based on MMGenID
  24. """
  25. color = 'orange'
  26. width = 0
  27. trunc_ok = False
  28. def __new__(cls,proto,id_str):
  29. from .addrlist import AddrIdxList
  30. from .addr import AddrListID
  31. from .seed import SeedID
  32. try:
  33. ss = str(id_str).split(':')
  34. assert len(ss) in (2,3),'not 2 or 3 colon-separated items'
  35. t = proto.addr_type((ss[1],proto.dfl_mmtype)[len(ss)==2])
  36. me = str.__new__(cls,'{}:{}:{}'.format(ss[0],t,ss[-1]))
  37. me.sid = SeedID(sid=ss[0])
  38. me.idxlist = AddrIdxList(ss[-1])
  39. me.mmtype = t
  40. assert t in proto.mmtypes, f'{t}: invalid address type for {proto.cls_name}'
  41. me.al_id = str.__new__(AddrListID,me.sid+':'+me.mmtype) # checks already done
  42. me.proto = proto
  43. return me
  44. except Exception as e:
  45. return cls.init_fail(e,id_str)
  46. class coin_msg:
  47. class base(MMGenObject):
  48. ext = 'rawmsg.json'
  49. signed = False
  50. chksum_keys = ('addrlists','message','msghash_type','network')
  51. @property
  52. def desc(self):
  53. return ('signed' if self.signed else 'unsigned') + ' message data'
  54. @property
  55. def chksum(self):
  56. return make_chksum_6(
  57. json.dumps(
  58. {k:self.data[k] for k in self.chksum_keys},
  59. sort_keys = True,
  60. separators = (',', ':')
  61. ))
  62. @property
  63. def filename_stem(self):
  64. coin,network = self.data['network'].split('_')
  65. return '{}[{}]{}'.format(
  66. self.chksum.upper(),
  67. coin.upper(),
  68. ('' if network == 'mainnet' else '.'+network) )
  69. @property
  70. def filename(self):
  71. return f'{self.filename_stem}.{self.ext}'
  72. @property
  73. def signed_filename(self):
  74. return f'{self.filename_stem}.{coin_msg.signed.ext}'
  75. def get_proto_from_file(self,filename):
  76. data = json.loads(get_data_from_file(filename))
  77. network_id = data['metadata']['network'] if 'metadata' in data else data['network'].lower()
  78. coin,network = network_id.split('_')
  79. return init_proto( coin=coin, network=network )
  80. def write_to_file(self,outdir=None,ask_overwrite=False):
  81. data = {
  82. 'id': f'{g.proj_name} {self.desc}',
  83. 'metadata': self.data,
  84. 'signatures': self.sigs,
  85. }
  86. write_data_to_file(
  87. outfile = os.path.join(outdir or '',self.filename),
  88. data = json.dumps(data,sort_keys=True,indent=4),
  89. desc = self.desc,
  90. ask_overwrite = ask_overwrite )
  91. class new(base):
  92. def __init__(self,message,addrlists,msghash_type,*args,**kwargs):
  93. msghash_type = msghash_type or self.msg_cls.msghash_types[0]
  94. if msghash_type not in self.msg_cls.msghash_types:
  95. die(2,f'msghash_type {msghash_type!r} not supported for {self.proto.base_proto} protocol')
  96. self.data = {
  97. 'network': '{}_{}'.format( self.proto.coin.lower(), self.proto.network ),
  98. 'addrlists': [MMGenIDRange(self.proto,i) for i in addrlists.split()],
  99. 'message': message,
  100. 'msghash_type': msghash_type,
  101. }
  102. self.sigs = {}
  103. class completed(base):
  104. def __init__(self,data,infile,*args,**kwargs):
  105. if data:
  106. self.__dict__ = data
  107. return
  108. self.data = get_data_from_file(
  109. infile = infile,
  110. desc = self.desc )
  111. d = json.loads(self.data)
  112. self.data = d['metadata']
  113. self.sigs = d['signatures']
  114. self.addrlists = [MMGenIDRange(self.proto,i) for i in self.data['addrlists']]
  115. def format(self,req_addr=None):
  116. labels = {
  117. 'addr': 'address:',
  118. 'addr_p2pkh': 'addr_p2pkh:',
  119. 'pubhash': 'pubkey hash:',
  120. 'sig': 'signature:',
  121. }
  122. def gen_entry(e):
  123. for k in labels:
  124. if e.get(k):
  125. yield fs_sig.format( labels[k], e[k] )
  126. def gen_all():
  127. for k,v in hdr_data.items():
  128. yield fs_hdr.format( v[0], v[1](self.data[k]) )
  129. if self.sigs:
  130. yield ''
  131. yield 'Signatures:'
  132. for n,(k,v) in enumerate(self.sigs.items()):
  133. yield ''
  134. yield '{:>3}) {}'.format(n+1,k)
  135. for res in gen_entry(v):
  136. yield res
  137. def gen_single():
  138. for k,v in hdr_data.items():
  139. yield fs_hdr.format( v[0], v[1](self.data[k]) )
  140. if self.sigs:
  141. yield 'Signature data:'
  142. k = (
  143. CoinAddr(self.proto,req_addr) if type(self).__name__ == 'exported_sigs' else
  144. MMGenID(self.proto,req_addr) )
  145. if k not in self.sigs:
  146. die(1,f'{k}: address not found in signature data')
  147. for res in gen_entry(self.sigs[k]):
  148. yield res
  149. hdr_data = {
  150. 'message': ('Message:', lambda v: grnbg(v) ),
  151. 'network': ('Network:', lambda v: v.replace('_',' ').upper() ),
  152. 'msghash_type': ('Message Hash Type:', lambda v: v ),
  153. 'addrlists': ('Address Ranges:', lambda v: fmt_list(v,fmt='bare') ),
  154. 'failed_sids': ('Failed Seed IDs:', lambda v: red(fmt_list(v,fmt='bare')) ),
  155. }
  156. if len(self.msg_cls.msghash_types) == 1:
  157. del hdr_data['msghash_type']
  158. if req_addr or type(self).__name__ == 'exported_sigs':
  159. del hdr_data['addrlists']
  160. if req_addr or not self.data.get('failed_sids'):
  161. del hdr_data['failed_sids']
  162. fs_hdr = '{:%s} {}' % max(len(v[0]) for v in hdr_data.values())
  163. fs_sig = '%s{:%s} %s{}' % (
  164. ' ' * (2 if req_addr else 5),
  165. max(len(labels[k]) for v in self.sigs.values() for k in v.keys()),
  166. self.msg_cls.sigdata_pfx or ''
  167. ) if self.sigs else None
  168. if req_addr:
  169. return '\n'.join(gen_single())
  170. else:
  171. return (
  172. '{}SIGNED MESSAGE DATA:\n\n '.format('' if self.sigs else 'UN') +
  173. '\n '.join(gen_all()) )
  174. class unsigned(completed):
  175. async def sign(self,wallet_files):
  176. async def sign_list(al_in,seed):
  177. al = KeyAddrList(
  178. proto = self.proto,
  179. seed = seed,
  180. addr_idxs = al_in.idxlist,
  181. mmtype = al_in.mmtype,
  182. skip_chksum = True,
  183. add_p2pkh = al_in.mmtype in ('S','B') )
  184. for e in al.data:
  185. sig = await self.do_sign(
  186. wif = e.sec.wif,
  187. message = self.data['message'],
  188. msghash_type = self.data['msghash_type'] )
  189. mmid = '{}:{}:{}'.format( al_in.sid, al_in.mmtype, e.idx )
  190. data = {
  191. 'addr': e.addr,
  192. 'sig': sig,
  193. }
  194. if self.msg_cls.include_pubhash:
  195. data.update({ 'pubhash': self.proto.parse_addr(e.addr_p2pkh or e.addr).bytes.hex() })
  196. if e.addr_p2pkh:
  197. data.update({'addr_p2pkh': e.addr_p2pkh})
  198. self.sigs[mmid] = data
  199. if self.proto.sign_mode == 'daemon':
  200. from .rpc import rpc_init
  201. self.rpc = await rpc_init(self.proto)
  202. from .wallet import Wallet
  203. from .addrlist import KeyAddrList
  204. wallet_seeds = [Wallet(fn=fn).seed for fn in wallet_files]
  205. need_sids = remove_dups([al.sid for al in self.addrlists], quiet=True)
  206. saved_seeds = list()
  207. # First try wallet seeds:
  208. for sid in need_sids:
  209. for seed in wallet_seeds:
  210. if sid == seed.sid:
  211. saved_seeds.append(seed)
  212. need_sids.remove(sid)
  213. break
  214. # Then subseeds:
  215. for sid in need_sids:
  216. for seed in wallet_seeds:
  217. subseed = seed.subseeds.get_subseed_by_seed_id(sid,print_msg=True)
  218. if subseed:
  219. saved_seeds.append(subseed)
  220. need_sids.remove(sid)
  221. break
  222. for al in self.addrlists:
  223. for seed in saved_seeds:
  224. if al.sid == seed.sid:
  225. await sign_list(al,seed)
  226. break
  227. if need_sids:
  228. msg('Failed Seed IDs: {}'.format(orange(fmt_list(need_sids,fmt='bare'))))
  229. self.data['failed_sids'] = need_sids
  230. class signed(completed):
  231. ext = 'sigmsg.json'
  232. signed = True
  233. class signed_online(signed):
  234. def get_sigs(self,addr):
  235. if addr:
  236. req_addr = (
  237. CoinAddr(self.proto,addr) if type(self).__name__ == 'exported_sigs' else
  238. MMGenID(self.proto,addr) )
  239. sigs = {k:v for k,v in self.sigs.items() if k == req_addr}
  240. else:
  241. sigs = self.sigs
  242. if not sigs:
  243. die(1,'No signatures')
  244. return sigs
  245. async def verify(self,addr=None,summary=False):
  246. sigs = self.get_sigs(addr)
  247. if self.proto.sign_mode == 'daemon':
  248. from .rpc import rpc_init
  249. self.rpc = await rpc_init(self.proto)
  250. for k,v in sigs.items():
  251. ret = await self.do_verify(
  252. addr = v.get('addr_p2pkh') or v['addr'],
  253. sig = v['sig'],
  254. message = self.data['message'],
  255. msghash_type = self.data['msghash_type'] )
  256. if not ret:
  257. die(3,f'Invalid signature for address {k} ({v["addr"]})')
  258. if summary:
  259. msg('{} signature{} verified'.format( len(sigs), suf(sigs) ))
  260. def get_json_for_export(self,addr=None):
  261. sigs = list( self.get_sigs(addr).values() )
  262. pfx = self.msg_cls.sigdata_pfx
  263. if pfx:
  264. sigs = [{k:pfx+v for k,v in e.items()} for e in sigs]
  265. return json.dumps(
  266. {
  267. 'message': self.data['message'],
  268. 'msghash_type': self.data['msghash_type'],
  269. 'network': self.data['network'].upper(),
  270. 'signatures': sigs,
  271. },
  272. sort_keys = True,
  273. indent = 4
  274. )
  275. class exported_sigs(signed_online):
  276. def __init__(self,infile,*args,**kwargs):
  277. self.data = json.loads(
  278. get_data_from_file(
  279. infile = infile,
  280. desc = self.desc )
  281. )
  282. pfx = self.msg_cls.sigdata_pfx
  283. self.sigs = {sig_data['addr']:sig_data for sig_data in (
  284. [{k:v[len(pfx):] for k,v in e.items()} for e in self.data['signatures']]
  285. if pfx else
  286. self.data['signatures']
  287. )}
  288. def _get_obj(clsname,coin=None,network='mainnet',infile=None,data=None,*args,**kwargs):
  289. assert not args, 'msg:_get_obj(): only keyword args allowed'
  290. if clsname == 'signed':
  291. assert data and not (coin or infile), 'msg:_get_obj(): chk2'
  292. else:
  293. assert not data and (coin or infile) and not (coin and infile), 'msg:_get_obj(): chk3'
  294. proto = (
  295. data['proto'] if data else
  296. init_proto( coin=coin, network=network ) if coin else
  297. coin_msg.base().get_proto_from_file(infile) )
  298. try:
  299. msg_cls = getattr(
  300. importlib.import_module(f'mmgen.base_proto.{proto.base_proto.lower()}.msg'),
  301. 'coin_msg' )
  302. except:
  303. die(1,f'Message signing operations not supported for {proto.base_proto} protocol')
  304. me = MMGenObject.__new__(getattr( msg_cls, clsname, getattr(coin_msg,clsname) ))
  305. me.msg_cls = msg_cls
  306. me.proto = proto
  307. me.__init__(infile=infile,data=data,*args,**kwargs)
  308. return me
  309. def _get(clsname):
  310. return lambda *args,**kwargs: _get_obj(clsname,*args,**kwargs)
  311. NewMsg = _get('new')
  312. CompletedMsg = _get('completed')
  313. UnsignedMsg = _get('unsigned')
  314. SignedMsg = _get('signed')
  315. SignedOnlineMsg = _get('signed_online')
  316. ExportedMsgSigs = _get('exported_sigs')