protocol.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 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. protocol: Coin protocol base classes and initializer
  20. """
  21. from collections import namedtuple
  22. from .cfg import gc
  23. from .base_obj import Lockable
  24. from .objmethods import MMGenObject
  25. decoded_wif = namedtuple('decoded_wif', ['sec', 'pubkey_type', 'compressed'])
  26. decoded_addr = namedtuple('decoded_addr', ['bytes', 'ver_bytes', 'fmt'])
  27. decoded_addr_multiview = namedtuple('mv_decoded_addr', ['bytes', 'ver_bytes', 'fmt', 'addr', 'views', 'view_pref'])
  28. parsed_addr = namedtuple('parsed_addr', ['ver_bytes', 'data'])
  29. _finfo = namedtuple('fork_info', ['height', 'hash', 'name', 'replayable'])
  30. _nw = namedtuple('coin_networks', ['mainnet', 'testnet', 'regtest'])
  31. class CoinProtocol(MMGenObject):
  32. proto_info = namedtuple('proto_info', ['name', 'trust_level']) # trust levels: see altcoin/params.py
  33. # keys are mirrored in gc.core_coins:
  34. coins = {
  35. 'btc': proto_info('Bitcoin', 5),
  36. 'bch': proto_info('BitcoinCash', 5),
  37. 'ltc': proto_info('Litecoin', 5),
  38. 'eth': proto_info('Ethereum', 4),
  39. 'etc': proto_info('EthereumClassic', 4),
  40. 'zec': proto_info('Zcash', 2),
  41. 'xmr': proto_info('Monero', 4)
  42. }
  43. class Base(Lockable):
  44. base_proto = None
  45. base_proto_coin = None
  46. base_coin = None
  47. is_fork_of = None
  48. chain_names = None
  49. is_evm = False
  50. networks = ('mainnet', 'testnet', 'regtest')
  51. decimal_prec = 28
  52. _set_ok = ('tokensym',)
  53. def __init__(self, cfg, coin, *, name, network, tokensym=None, need_amt=False):
  54. self.cfg = cfg
  55. self.coin = coin.upper()
  56. self.coin_id = self.coin
  57. self.name = name
  58. self.network = network
  59. self.tokensym = tokensym
  60. self.cls_name = type(self).__name__
  61. self.testnet = network in ('testnet', 'regtest')
  62. self.regtest = network == 'regtest'
  63. self.networks = tuple(k for k, v in self.network_names._asdict().items() if v)
  64. self.network_id = coin.lower() + {
  65. 'mainnet': '',
  66. 'testnet': '_tn',
  67. 'regtest': '_rt',
  68. }[network]
  69. if hasattr(self, 'wif_ver_num'):
  70. self.wif_ver_bytes = {k:bytes.fromhex(v) for k, v in self.wif_ver_num.items()}
  71. self.wif_ver_bytes_to_pubkey_type = {v:k for k, v in self.wif_ver_bytes.items()}
  72. vbs = list(self.wif_ver_bytes.values())
  73. self.wif_ver_bytes_len = len(vbs[0]) if len(set(len(b) for b in vbs)) == 1 else None
  74. if hasattr(self, 'addr_ver_info'):
  75. self.addr_ver_bytes = {bytes.fromhex(k):v for k, v in self.addr_ver_info.items()}
  76. self.addr_fmt_to_ver_bytes = {v:k for k, v in self.addr_ver_bytes.items()}
  77. self.addr_ver_bytes_len = len(list(self.addr_ver_bytes)[0])
  78. if gc.cmd_caps:
  79. for cap in gc.cmd_caps.caps:
  80. if cap not in self.mmcaps:
  81. from .util import die
  82. die(2, f'Command {gc.prog_name!r} not supported for coin {self.coin}')
  83. if self.chain_names:
  84. self.chain_name = self.chain_names[0] # first chain name is default
  85. else:
  86. self.chain_names = [self.network]
  87. self.chain_name = self.network
  88. if self.tokensym:
  89. assert self.name.startswith('Ethereum'), 'CoinProtocol.Base_chk1'
  90. if self.base_coin in ('ETH', 'XMR'):
  91. from .util2 import get_keccak
  92. self.keccak_256 = get_keccak(cfg)
  93. if need_amt:
  94. from . import amt
  95. from decimal import getcontext
  96. self.coin_amt = getattr(amt, self.coin_amt)
  97. self.max_tx_fee = self.coin_amt(str(self.max_tx_fee)) if hasattr(self, 'max_tx_fee') else None
  98. getcontext().prec = self.decimal_prec
  99. else:
  100. self.coin_amt = None
  101. self.max_tx_fee = None
  102. self.set_cfg_opts()
  103. def set_cfg_opts(self):
  104. pass
  105. @property
  106. def dcoin(self):
  107. return self.coin
  108. @classmethod
  109. def chain_name_to_network(cls, cfg, coin, chain_name):
  110. """
  111. The generic networks 'mainnet', 'testnet' and 'regtest' are required for all coins
  112. that support transaction operations.
  113. For protocols that have specific names for chains corresponding to these networks,
  114. the attribute 'chain_name' is used, while 'network' retains the generic name.
  115. For Bitcoin and Bitcoin forks, 'network' and 'chain_name' are equivalent.
  116. """
  117. for network in ('mainnet', 'testnet', 'regtest'):
  118. proto = init_proto(cfg, coin, network=network)
  119. for proto_chain_name in proto.chain_names:
  120. if chain_name == proto_chain_name:
  121. return network
  122. raise ValueError(f'{chain_name}: unrecognized chain name for coin {coin}')
  123. @staticmethod
  124. def parse_network_id(network_id):
  125. nid = namedtuple('parsed_network_id', ['coin', 'network'])
  126. if network_id.endswith('_tn'):
  127. return nid(network_id[:-3], 'testnet')
  128. elif network_id.endswith('_rt'):
  129. return nid(network_id[:-3], 'regtest')
  130. else:
  131. return nid(network_id, 'mainnet')
  132. @staticmethod
  133. def create_network_id(coin, network):
  134. return coin.lower() + {'mainnet':'', 'testnet':'_tn', 'regtest':'_rt'}[network]
  135. def cap(self, s):
  136. return s in self.caps
  137. def get_addr_len(self, addr_fmt):
  138. return self.addr_len
  139. def decode_addr_bytes(self, addr_bytes):
  140. vlen = self.addr_ver_bytes_len
  141. return decoded_addr(
  142. addr_bytes[vlen:],
  143. addr_bytes[:vlen],
  144. self.addr_ver_bytes[addr_bytes[:vlen]])
  145. def coin_addr(self, addr):
  146. from .addr import CoinAddr
  147. return CoinAddr(proto=self, addr=addr)
  148. def addr_type(self, id_str):
  149. from .addr import MMGenAddrType
  150. return MMGenAddrType(proto=self, id_str=id_str)
  151. def viewkey(self, viewkey_str):
  152. raise NotImplementedError(f'{self.name} protocol does not support view keys')
  153. def base_proto_subclass(self, cls, modname, *, sub_clsname=None, is_token=False):
  154. """
  155. magic module loading and class selection
  156. """
  157. modpath = f'mmgen.proto.{self.base_proto_coin.lower()}.{modname}'
  158. clsname = (
  159. self.mod_clsname
  160. + ('Token' if self.tokensym or is_token else '')
  161. + cls.__name__)
  162. import importlib
  163. if sub_clsname:
  164. return getattr(getattr(importlib.import_module(modpath), clsname), sub_clsname)
  165. else:
  166. return getattr(importlib.import_module(modpath), clsname)
  167. class RPC:
  168. # prefixed with coin, e.g. ‘ltc_rpc_host’: refvals taken from proto class
  169. coin_cfg_opts = ()
  170. # prefixed with coin + network, e.g. ‘eth_mainnet_chain_names’: refvals taken from proto class
  171. proto_cfg_opts = ()
  172. # default vals (refvals): bool(val) must be False (val = None -> option takes no parameter)
  173. ignore_daemon_version = None
  174. rpc_host = ''
  175. rpc_port = 0
  176. rpc_user = ''
  177. rpc_password = ''
  178. tw_name = ''
  179. daemon_id = ''
  180. @classmethod
  181. def get_opt_clsval(cls, cfg, opt):
  182. coin, *rem = opt.split('_', 2)
  183. network = rem[0] if rem[0] in init_proto(cfg, coin, return_cls=True).network_names else None
  184. opt_name = '_'.join(rem[bool(network):])
  185. if ((network is None and opt_name in cls.coin_cfg_opts) or
  186. (network and opt_name in cls.proto_cfg_opts)):
  187. # raises AttributeError on failure:
  188. return getattr(init_proto(cfg, coin, network=network, return_cls=True), opt_name)
  189. else:
  190. raise AttributeError(f'{opt_name}: unrecognized attribute')
  191. def set_cfg_opts(self):
  192. for opt in self.cfg.__dict__:
  193. if opt.startswith(self.coin.lower() + '_'):
  194. res = opt.split('_', 2)[1:]
  195. network = res[0] if res[0] in self.network_names else None
  196. if network is None or network == self.network:
  197. setattr(self, '_'.join(res[bool(network):]), getattr(self.cfg, opt))
  198. class Secp256k1(RPC, Base):
  199. """
  200. Bitcoin and Ethereum protocols inherit from this class
  201. """
  202. secp256k1_group_order = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
  203. privkey_len = 32
  204. pubkey_types = ('std',)
  205. def parse_addr(self, ver_bytes, addr_bytes, fmt):
  206. return parsed_addr(
  207. ver_bytes = ver_bytes,
  208. data = addr_bytes,
  209. )
  210. def preprocess_key(self, sec, pubkey_type):
  211. # Key must be non-zero and less than group order of secp256k1 curve
  212. if 0 < int.from_bytes(sec, 'big') < self.secp256k1_group_order:
  213. return sec
  214. else: # chance of this is less than 1 in 2^127
  215. from .util import die, ymsg
  216. pk = int.from_bytes(sec, 'big')
  217. if pk == 0: # chance of this is 1 in 2^256
  218. die(4, 'Private key is zero!')
  219. elif pk == self.secp256k1_group_order: # ditto
  220. die(4, 'Private key == secp256k1_group_order!')
  221. else: # return key mod group order as the key
  222. if not self.cfg.test_suite:
  223. ymsg(f'Warning: private key is greater than secp256k1 group order!:\n {sec.hex()}')
  224. return (pk % self.secp256k1_group_order).to_bytes(self.privkey_len, 'big')
  225. class DummyWIF:
  226. """
  227. Ethereum and Monero protocols inherit from this class
  228. """
  229. def encode_wif(self, privbytes, pubkey_type, compressed):
  230. assert pubkey_type == self.pubkey_type, f'{pubkey_type}: invalid pubkey_type for {self.name} protocol!'
  231. assert compressed is False, f'{self.name} protocol does not support compressed pubkeys!'
  232. return privbytes.hex()
  233. def decode_wif(self, wif):
  234. return decoded_wif(
  235. sec = bytes.fromhex(wif),
  236. pubkey_type = self.pubkey_type,
  237. compressed = False)
  238. def init_proto(
  239. cfg,
  240. coin = None,
  241. *,
  242. testnet = False,
  243. regtest = False,
  244. network = None,
  245. network_id = None,
  246. tokensym = None,
  247. need_amt = False,
  248. return_cls = False):
  249. assert type(testnet) is bool, 'init_proto_chk1'
  250. assert type(regtest) is bool, 'init_proto_chk2'
  251. assert coin or network_id, 'init_proto_chk3'
  252. assert not (coin and network_id), 'init_proto_chk4'
  253. if network_id:
  254. coin, network = CoinProtocol.Base.parse_network_id(network_id)
  255. elif network:
  256. assert network in CoinProtocol.Base.networks, f'init_proto_chk5 - {network!r}: invalid network'
  257. assert testnet is False, 'init_proto_chk6'
  258. assert regtest is False, 'init_proto_chk7'
  259. else:
  260. network = 'regtest' if regtest else 'testnet' if testnet else 'mainnet'
  261. coin = coin.lower()
  262. if coin not in CoinProtocol.coins:
  263. from .altcoin.params import init_genonly_altcoins
  264. init_genonly_altcoins(coin, testnet=testnet) # raises exception on failure
  265. name = CoinProtocol.coins[coin].name
  266. proto_name = name + ('' if network == 'mainnet' else network.capitalize())
  267. if not hasattr(CoinProtocol, proto_name):
  268. import importlib
  269. setattr(
  270. CoinProtocol,
  271. proto_name,
  272. getattr(importlib.import_module(f'mmgen.proto.{coin}.params'), network)
  273. )
  274. if return_cls:
  275. return getattr(CoinProtocol, proto_name)
  276. return getattr(CoinProtocol, proto_name)(
  277. cfg = cfg,
  278. coin = coin,
  279. name = name,
  280. network = network,
  281. tokensym = tokensym,
  282. need_amt = need_amt)
  283. def init_proto_from_cfg(cfg, need_amt):
  284. return init_proto(
  285. cfg = cfg,
  286. coin = cfg.coin,
  287. network = cfg.network,
  288. tokensym = cfg.token,
  289. need_amt = need_amt)
  290. def warn_trustlevel(cfg):
  291. coinsym = cfg.coin
  292. if coinsym.lower() in CoinProtocol.coins:
  293. trust_level = CoinProtocol.coins[coinsym.lower()].trust_level
  294. else:
  295. from .altcoin.params import CoinInfo
  296. e = CoinInfo.get_entry(coinsym, 'mainnet')
  297. trust_level = e.trust_level if e else None
  298. if trust_level in (None, -1):
  299. from .util import die
  300. die(1, f'Coin {coinsym} is not supported by {gc.proj_name}')
  301. if trust_level > 3:
  302. return
  303. m = """
  304. Support for coin {c!r} is EXPERIMENTAL. The {p} project
  305. assumes no responsibility for any loss of funds you may incur.
  306. This coin’s {p} testing status: {t}
  307. Are you sure you want to continue?
  308. """
  309. from .util import fmt
  310. from .color import red, yellow, green
  311. warning = fmt(m).strip().format(
  312. c = coinsym.upper(),
  313. t = {
  314. 0: red('COMPLETELY UNTESTED'),
  315. 1: red('LOW'),
  316. 2: yellow('MEDIUM'),
  317. 3: green('OK'),
  318. }[trust_level],
  319. p = gc.proj_name)
  320. if cfg.test_suite:
  321. cfg._util.qmsg(warning)
  322. return
  323. from .ui import keypress_confirm
  324. if not keypress_confirm(cfg, warning, default_yes=True):
  325. import sys
  326. sys.exit(0)