protocol.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. protocol.py: Coin protocol functions, classes and methods
  20. """
  21. import sys,os,hashlib
  22. from mmgen.util import msg,pmsg,ymsg,Msg,pdie,ydie
  23. from mmgen.obj import MMGenObject,BTCAmt,LTCAmt,BCHAmt,B2XAmt,ETHAmt
  24. from mmgen.globalvars import g
  25. import mmgen.bech32 as bech32
  26. def hash160(hexnum): # take hex, return hex - OP_HASH160
  27. return hashlib.new('ripemd160',hashlib.sha256(bytes.fromhex(hexnum)).digest()).hexdigest()
  28. def hash256(hexnum): # take hex, return hex - OP_HASH256
  29. return hashlib.sha256(hashlib.sha256(bytes.fromhex(hexnum)).digest()).hexdigest()
  30. _b58a='123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  31. # From en.bitcoin.it:
  32. # The Base58 encoding used is home made, and has some differences.
  33. # Especially, leading zeroes are kept as single zeroes when conversion happens.
  34. # Test: 5JbQQTs3cnoYN9vDYaGY6nhQ1DggVsY4FJNBUfEfpSQqrEp3srk
  35. # The 'zero address':
  36. # 1111111111111111111114oLvT2 (pubkeyhash = '\0'*20)
  37. def _b58chk_encode(hexstr):
  38. lzeroes = (len(hexstr) - len(hexstr.lstrip('0'))) // 2
  39. def b58enc(n):
  40. while n:
  41. yield _b58a[n % 58]
  42. n //= 58
  43. return ('1' * lzeroes) + ''.join(b58enc(int(hexstr+hash256(hexstr)[:8],16)))[::-1]
  44. def _b58chk_decode(s):
  45. lzeroes = len(s) - len(s.lstrip('1'))
  46. hexstr = '{}{:x}'.format(
  47. '00' * lzeroes,
  48. sum(_b58a.index(ch) * 58**n for n,ch in enumerate(s[::-1])) )
  49. if len(hexstr) % 2: hexstr = '0' + hexstr
  50. if hexstr[-8:] != hash256(hexstr[:-8])[:8]:
  51. fs = '_b58chk_decode(): {}: incorrect checksum for {!r}, expected {}'
  52. raise ValueError(fs.format(hexstr[-8:],hexstr[:-8],hash256(hexstr[:-8])[:8]))
  53. return hexstr[:-8]
  54. # chainparams.cpp
  55. class BitcoinProtocol(MMGenObject):
  56. name = 'bitcoin'
  57. daemon_name = 'bitcoind'
  58. daemon_family = 'bitcoind'
  59. addr_ver_num = { 'p2pkh': ('00','1'), 'p2sh': ('05','3') }
  60. wif_ver_num = { 'std': '80' }
  61. mmtypes = ('L','C','S','B')
  62. dfl_mmtype = 'L'
  63. data_subdir = ''
  64. rpc_port = 8332
  65. secs_per_block = 600
  66. coin_amt = BTCAmt
  67. max_tx_fee = BTCAmt('0.003')
  68. daemon_data_dir = os.path.join(os.getenv('APPDATA'),'Bitcoin') if g.platform == 'win' \
  69. else os.path.join(g.home_dir,'.bitcoin')
  70. daemon_data_subdir = ''
  71. sighash_type = 'ALL'
  72. block0 = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
  73. forks = [ # height, hash, name, replayable
  74. (478559,'00000000000000000019f112ec0a9982926f1258cdcc558dd7c3b7e5dc7fa148','bch',False),
  75. (None,'','b2x',True)
  76. ]
  77. caps = ('rbf','segwit')
  78. mmcaps = ('key','addr','rpc','tx')
  79. base_coin = 'BTC'
  80. base_proto = 'Bitcoin'
  81. # From BIP173: witness version 'n' is stored as 'OP_n'. OP_0 is encoded as 0x00,
  82. # but OP_1 through OP_16 are encoded as 0x51 though 0x60 (81 to 96 in decimal).
  83. witness_vernum_hex = '00'
  84. witness_vernum = int(witness_vernum_hex,16)
  85. bech32_hrp = 'bc'
  86. sign_mode = 'daemon'
  87. secp256k1_ge = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
  88. privkey_len = 32
  89. @classmethod
  90. def is_testnet(cls):
  91. return cls.__name__[-15:] == 'TestnetProtocol'
  92. @staticmethod
  93. def get_protocol_by_chain(chain):
  94. return CoinProtocol(g.coin,{'mainnet':False,'testnet':True,'regtest':True}[chain])
  95. @classmethod
  96. def cap(cls,s): return s in cls.caps
  97. @classmethod
  98. def preprocess_key(cls,hexpriv,pubkey_type):
  99. # Key must be non-zero and less than group order of secp256k1 curve
  100. if 0 < int(hexpriv,16) < cls.secp256k1_ge:
  101. return hexpriv
  102. else: # chance of this is less than 1 in 2^127
  103. pk = int(hexpriv,16)
  104. if pk == 0: # chance of this is 1 in 2^256
  105. ydie(3,'Private key is zero!')
  106. elif pk == cls.secp256k1_ge: # ditto
  107. ydie(3,'Private key == secp256k1_ge!')
  108. else:
  109. ymsg('Warning: private key is greater than secp256k1 group order!:\n {}'.format(hexpriv))
  110. return '{:064x}'.format(pk % cls.secp256k1_ge).encode()
  111. @classmethod
  112. def hex2wif(cls,hexpriv,pubkey_type,compressed): # PrivKey
  113. assert len(hexpriv) == cls.privkey_len*2, '{} bytes: incorrect private key length!'.format(len(hexpriv)//2)
  114. assert pubkey_type in cls.wif_ver_num, '{!r}: invalid pubkey_type'.format(pubkey_type)
  115. return _b58chk_encode(cls.wif_ver_num[pubkey_type] + hexpriv + ('','01')[bool(compressed)])
  116. @classmethod
  117. def wif2hex(cls,wif):
  118. key = _b58chk_decode(wif)
  119. pubkey_type = None
  120. for k,v in list(cls.wif_ver_num.items()):
  121. if key[:len(v)] == v:
  122. pubkey_type = k
  123. key = key[len(v):]
  124. assert pubkey_type,'invalid WIF version number'
  125. if len(key) == 66:
  126. assert key[-2:] == '01','invalid compressed key suffix'
  127. compressed = True
  128. else:
  129. assert len(key) == 64,'invalid key length'
  130. compressed = False
  131. assert 0 < int(key[:64],16) < cls.secp256k1_ge,(
  132. "'{}': invalid WIF (produces key outside allowable range)".format(wif))
  133. return { 'hex':key[:64], 'pubkey_type':pubkey_type, 'compressed':compressed }
  134. @classmethod
  135. def verify_addr(cls,addr,hex_width,return_dict=False):
  136. if 'B' in cls.mmtypes and addr[:len(cls.bech32_hrp)] == cls.bech32_hrp:
  137. ret = bech32.decode(cls.bech32_hrp,addr)
  138. if ret[0] != cls.witness_vernum:
  139. msg('{}: Invalid witness version number'.format(ret[0]))
  140. elif ret[1]:
  141. return {
  142. 'hex': bytes(ret[1]).hex(),
  143. 'format': 'bech32'
  144. } if return_dict else True
  145. return False
  146. for addr_fmt in cls.addr_ver_num:
  147. ver_num,pfx = cls.addr_ver_num[addr_fmt]
  148. if type(pfx) == tuple:
  149. if addr[0] not in pfx: continue
  150. elif addr[:len(pfx)] != pfx: continue
  151. addr_hex = _b58chk_decode(addr)
  152. if addr_hex[:len(ver_num)] != ver_num: continue
  153. return {
  154. 'hex': addr_hex[len(ver_num):],
  155. 'format': { 'p2pkh':'p2pkh',
  156. 'p2sh':'p2sh',
  157. 'p2sh2':'p2sh',
  158. 'zcash_z':'zcash_z',
  159. 'viewkey':'viewkey'}[addr_fmt]
  160. } if return_dict else True
  161. return False
  162. @classmethod
  163. def pubhash2addr(cls,pubkey_hash,p2sh):
  164. assert len(pubkey_hash) == 40,'{}: invalid length for pubkey hash'.format(len(pubkey_hash))
  165. s = cls.addr_ver_num[('p2pkh','p2sh')[p2sh]][0] + pubkey_hash
  166. return _b58chk_encode(s)
  167. # Segwit:
  168. @classmethod
  169. def pubhex2redeem_script(cls,pubhex):
  170. # https://bitcoincore.org/en/segwit_wallet_dev/
  171. # The P2SH redeemScript is always 22 bytes. It starts with a OP_0, followed
  172. # by a canonical push of the keyhash (i.e. 0x0014{20-byte keyhash})
  173. return cls.witness_vernum_hex + '14' + hash160(pubhex)
  174. @classmethod
  175. def pubhex2segwitaddr(cls,pubhex):
  176. return cls.pubhash2addr(hash160(cls.pubhex2redeem_script(pubhex)),p2sh=True)
  177. @classmethod
  178. def pubhash2bech32addr(cls,pubhash):
  179. d = list(bytes.fromhex(pubhash))
  180. return bech32.bech32_encode(cls.bech32_hrp,[cls.witness_vernum]+bech32.convertbits(d,8,5))
  181. class BitcoinTestnetProtocol(BitcoinProtocol):
  182. addr_ver_num = { 'p2pkh': ('6f',('m','n')), 'p2sh': ('c4','2') }
  183. wif_ver_num = { 'std': 'ef' }
  184. data_subdir = 'testnet'
  185. daemon_data_subdir = 'testnet3'
  186. rpc_port = 18332
  187. bech32_hrp = 'tb'
  188. bech32_hrp_rt = 'bcrt'
  189. class BitcoinCashProtocol(BitcoinProtocol):
  190. # TODO: assumes MSWin user installs in custom dir 'Bitcoin_ABC'
  191. daemon_name = 'bitcoind-abc'
  192. daemon_data_dir = os.path.join(os.getenv('APPDATA'),'Bitcoin_ABC') if g.platform == 'win' \
  193. else os.path.join(g.home_dir,'.bitcoin-abc')
  194. rpc_port = 8442
  195. mmtypes = ('L','C')
  196. sighash_type = 'ALL|FORKID'
  197. forks = [
  198. (478559,'000000000000000000651ef99cb9fcbe0dadde1d424bd9f15ff20136191a5eec','btc',False)
  199. ]
  200. caps = ()
  201. coin_amt = BCHAmt
  202. max_tx_fee = BCHAmt('0.1')
  203. @classmethod
  204. def pubhex2redeem_script(cls,pubhex): raise NotImplementedError
  205. @classmethod
  206. def pubhex2segwitaddr(cls,pubhex): raise NotImplementedError
  207. class BitcoinCashTestnetProtocol(BitcoinCashProtocol):
  208. rpc_port = 18442
  209. addr_ver_num = { 'p2pkh': ('6f',('m','n')), 'p2sh': ('c4','2') }
  210. wif_ver_num = { 'std': 'ef' }
  211. data_subdir = 'testnet'
  212. daemon_data_subdir = 'testnet3'
  213. class B2XProtocol(BitcoinProtocol):
  214. daemon_name = 'bitcoind-2x'
  215. daemon_data_dir = os.path.join(os.getenv('APPDATA'),'Bitcoin_2X') if g.platform == 'win' \
  216. else os.path.join(g.home_dir,'.bitcoin-2x')
  217. rpc_port = 8338
  218. coin_amt = B2XAmt
  219. max_tx_fee = B2XAmt('0.1')
  220. forks = [
  221. (None,'','btc',True) # activation: 494784
  222. ]
  223. class B2XTestnetProtocol(B2XProtocol):
  224. addr_ver_num = { 'p2pkh': ('6f',('m','n')), 'p2sh': ('c4','2') }
  225. wif_ver_num = { 'std': 'ef' }
  226. data_subdir = 'testnet'
  227. daemon_data_subdir = 'testnet5'
  228. rpc_port = 18338
  229. class LitecoinProtocol(BitcoinProtocol):
  230. block0 = '12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2'
  231. name = 'litecoin'
  232. daemon_name = 'litecoind'
  233. daemon_data_dir = os.path.join(os.getenv('APPDATA'),'Litecoin') if g.platform == 'win' \
  234. else os.path.join(g.home_dir,'.litecoin')
  235. addr_ver_num = { 'p2pkh': ('30','L'), 'p2sh': ('32','M'), 'p2sh2': ('05','3') } # 'p2sh' is new fmt
  236. wif_ver_num = { 'std': 'b0' }
  237. mmtypes = ('L','C','S','B')
  238. secs_per_block = 150
  239. rpc_port = 9332
  240. coin_amt = LTCAmt
  241. max_tx_fee = LTCAmt('0.3')
  242. base_coin = 'LTC'
  243. forks = []
  244. bech32_hrp = 'ltc'
  245. class LitecoinTestnetProtocol(LitecoinProtocol):
  246. # addr ver nums same as Bitcoin testnet, except for 'p2sh'
  247. addr_ver_num = { 'p2pkh': ('6f',('m','n')), 'p2sh': ('3a','Q'), 'p2sh2': ('c4','2') }
  248. wif_ver_num = { 'std': 'ef' } # same as Bitcoin testnet
  249. data_subdir = 'testnet'
  250. daemon_data_subdir = 'testnet4'
  251. rpc_port = 19332
  252. bech32_hrp = 'tltc'
  253. bech32_hrp_rt = 'rltc'
  254. class BitcoinProtocolAddrgen(BitcoinProtocol): mmcaps = ('key','addr')
  255. class BitcoinTestnetProtocolAddrgen(BitcoinTestnetProtocol): mmcaps = ('key','addr')
  256. class DummyWIF(object):
  257. @classmethod
  258. def hex2wif(cls,hexpriv,pubkey_type,compressed):
  259. n = cls.name.capitalize()
  260. assert pubkey_type == cls.pubkey_type,'{}: invalid pubkey_type for {}!'.format(pubkey_type,n)
  261. assert compressed == False,'{} does not support compressed pubkeys!'.format(n)
  262. return hexpriv
  263. @classmethod
  264. def wif2hex(cls,wif):
  265. return { 'hex':wif, 'pubkey_type':cls.pubkey_type, 'compressed':False }
  266. class EthereumProtocol(DummyWIF,BitcoinProtocol):
  267. addr_width = 40
  268. mmtypes = ('E',)
  269. dfl_mmtype = 'E'
  270. name = 'ethereum'
  271. base_coin = 'ETH'
  272. pubkey_type = 'std' # required by DummyWIF
  273. data_subdir = ''
  274. daemon_name = 'parity'
  275. daemon_family = 'parity'
  276. rpc_port = 8545
  277. mmcaps = ('key','addr','rpc')
  278. coin_amt = ETHAmt
  279. max_tx_fee = ETHAmt('0.005')
  280. chain_name = 'foundation'
  281. sign_mode = 'standalone'
  282. caps = ('token',)
  283. base_proto = 'Ethereum'
  284. @classmethod
  285. def verify_addr(cls,addr,hex_width,return_dict=False):
  286. from mmgen.util import is_hex_str_lc
  287. if is_hex_str_lc(addr) and len(addr) == cls.addr_width:
  288. return { 'hex': addr, 'format': 'ethereum' } if return_dict else True
  289. if g.debug: Msg("Invalid address '{}'".format(addr))
  290. return False
  291. @classmethod
  292. def pubhash2addr(cls,pubkey_hash,p2sh):
  293. assert len(pubkey_hash) == 40,'{}: invalid length for pubkey hash'.format(len(pubkey_hash))
  294. assert not p2sh,'Ethereum has no P2SH address format'
  295. return pubkey_hash
  296. class EthereumTestnetProtocol(EthereumProtocol):
  297. data_subdir = 'testnet'
  298. rpc_port = 8547 # start Parity with --jsonrpc-port=8547 or --ports-shift=2
  299. chain_name = 'kovan'
  300. class EthereumClassicProtocol(EthereumProtocol):
  301. name = 'ethereumClassic'
  302. class_pfx = 'Ethereum'
  303. rpc_port = 8555 # start Parity with --jsonrpc-port=8555 or --ports-shift=10
  304. chain_name = 'ethereum_classic' # chain_id 0x3d (61)
  305. class EthereumClassicTestnetProtocol(EthereumClassicProtocol):
  306. rpc_port = 8557 # start Parity with --jsonrpc-port=8557 or --ports-shift=12
  307. chain_name = 'classic-testnet' # aka Morden, chain_id 0x3e (62) (UNTESTED)
  308. class ZcashProtocol(BitcoinProtocolAddrgen):
  309. name = 'zcash'
  310. base_coin = 'ZEC'
  311. addr_ver_num = {
  312. 'p2pkh': ('1cb8','t1'),
  313. 'p2sh': ('1cbd','t3'),
  314. 'zcash_z': ('169a','zc'),
  315. 'viewkey': ('a8abd3','ZiVK') }
  316. wif_ver_num = { 'std': '80', 'zcash_z': 'ab36' }
  317. mmtypes = ('L','C','Z')
  318. dfl_mmtype = 'L'
  319. @classmethod
  320. def preprocess_key(cls,hexpriv,pubkey_type): # zero the first four bits
  321. if pubkey_type == 'zcash_z':
  322. return '{:02x}'.format(int(hexpriv[:2],16) & 0x0f) + hexpriv[2:]
  323. else:
  324. return hexpriv
  325. @classmethod
  326. def pubhash2addr(cls,pubkey_hash,p2sh):
  327. hl = len(pubkey_hash)
  328. if hl == 40:
  329. return super(cls,cls).pubhash2addr(pubkey_hash,p2sh)
  330. elif hl == 128:
  331. raise NotImplementedError('Zcash z-addresses have no pubkey hash')
  332. else:
  333. raise ValueError('{}: incorrect pubkey_hash length'.format(hl))
  334. class ZcashTestnetProtocol(ZcashProtocol):
  335. wif_ver_num = { 'std': 'ef', 'zcash_z': 'ac08' }
  336. addr_ver_num = {
  337. 'p2pkh': ('1d25','tm'),
  338. 'p2sh': ('1cba','t2'),
  339. 'zcash_z': ('16b6','zt'),
  340. 'viewkey': ('a8ac0c','ZiVt') }
  341. # https://github.com/monero-project/monero/blob/master/src/cryptonote_config.h
  342. class MoneroProtocol(DummyWIF,BitcoinProtocolAddrgen):
  343. name = 'monero'
  344. base_coin = 'XMR'
  345. addr_ver_num = { 'monero': ('12','4'), 'monero_sub': ('2a','8') } # 18,42
  346. wif_ver_num = {}
  347. mmtypes = ('M',)
  348. dfl_mmtype = 'M'
  349. addr_width = 95
  350. pubkey_type = 'monero' # required by DummyWIF
  351. @classmethod
  352. def preprocess_key(cls,hexpriv,pubkey_type): # reduce key
  353. from mmgen.ed25519 import l
  354. n = int(bytes.fromhex(hexpriv)[::-1].hex(),16) % l
  355. return bytes.fromhex('{:064x}'.format(n))[::-1].hex()
  356. @classmethod
  357. def verify_addr(cls,addr,hex_width,return_dict=False):
  358. def b58dec(addr_str):
  359. from mmgen.util import baseconv
  360. l = len(addr_str)
  361. a = ''.join([baseconv.tohex(addr_str[i*11:i*11+11],'b58',pad=16) for i in range(l//11)])
  362. b = baseconv.tohex(addr_str[-(l%11):],'b58',pad=10)
  363. return a + b
  364. from mmgen.util import is_b58_str
  365. assert is_b58_str(addr),'Not valid base-58 string'
  366. assert len(addr) == cls.addr_width,'Incorrect width'
  367. ret = b58dec(addr)
  368. try:
  369. assert not g.use_internal_keccak_module
  370. from sha3 import keccak_256
  371. except:
  372. from mmgen.keccak import keccak_256
  373. chk = keccak_256(bytes.fromhex(ret)[:-4]).hexdigest()[:8]
  374. assert chk == ret[-8:],'{}: incorrect checksum. Correct value: {}'.format(ret[-8:],chk)
  375. return { 'hex': ret, 'format': 'monero' } if return_dict else True
  376. class MoneroTestnetProtocol(MoneroProtocol):
  377. addr_ver_num = { 'monero': ('35','4'), 'monero_sub': ('3f','8') } # 53,63
  378. class CoinProtocol(MMGenObject):
  379. coins = {
  380. # mainnet testnet trustlevel (None == skip)
  381. 'btc': (BitcoinProtocol,BitcoinTestnetProtocol,None),
  382. 'bch': (BitcoinCashProtocol,BitcoinCashTestnetProtocol,None),
  383. 'ltc': (LitecoinProtocol,LitecoinTestnetProtocol,None),
  384. 'eth': (EthereumProtocol,EthereumTestnetProtocol,None),
  385. 'etc': (EthereumClassicProtocol,EthereumClassicTestnetProtocol,None),
  386. 'zec': (ZcashProtocol,ZcashTestnetProtocol,2),
  387. 'xmr': (MoneroProtocol,MoneroTestnetProtocol,None)
  388. }
  389. def __new__(cls,coin,testnet):
  390. coin = coin.lower()
  391. assert type(testnet) == bool
  392. m = "'{}': not a valid coin. Valid choices are {}"
  393. assert coin in cls.coins,m.format(coin,','.join(cls.get_valid_coins()))
  394. return cls.coins[coin][testnet]
  395. @classmethod
  396. def get_valid_coins(cls,upcase=False):
  397. from mmgen.altcoin import CoinInfo as ci
  398. ret = sorted(set(
  399. [e[1] for e in ci.coin_constants['mainnet'] if e[6] != -1]
  400. + list(cls.coins.keys())))
  401. return [getattr(e,('lower','upper')[upcase])() for e in ret]
  402. @classmethod
  403. def get_base_coin_from_name(cls,name):
  404. for (proto,foo) in cls.coins.values():
  405. if name == proto.__name__[:-8].lower():
  406. return proto.base_coin
  407. return False
  408. def init_genonly_altcoins(usr_coin,trust_level=None):
  409. from mmgen.altcoin import CoinInfo as ci
  410. if trust_level is None:
  411. if not usr_coin: return None # BTC
  412. if usr_coin.lower() in CoinProtocol.coins:
  413. return CoinProtocol.coins[usr_coin.lower()][2]
  414. usr_coin = usr_coin.upper()
  415. mn_coins = [e[1] for e in ci.coin_constants['mainnet'] if e[6] != -1]
  416. if usr_coin not in mn_coins: return None
  417. trust_level = ci.coin_constants['mainnet'][mn_coins.index(usr_coin)][6]
  418. data = {}
  419. for k in ('mainnet','testnet'):
  420. data[k] = [e for e in ci.coin_constants[k] if e[6] >= trust_level]
  421. exec(make_init_genonly_altcoins_str(data),globals(),globals())
  422. return trust_level
  423. def make_init_genonly_altcoins_str(data):
  424. def make_proto(e,testnet=False):
  425. tn_str = 'Testnet' if testnet else ''
  426. proto,coin = '{}{}Protocol'.format(e[0],tn_str),e[1]
  427. if proto[0] in '0123456789': proto = 'X_'+proto
  428. if proto in globals(): return ''
  429. if coin.lower() in CoinProtocol.coins: return ''
  430. def num2hexstr(n):
  431. return "'{:0{}x}'".format(n,(4,2)[n < 256])
  432. o = ['class {}(Bitcoin{}ProtocolAddrgen):'.format(proto,tn_str)]
  433. o += ["base_coin = '{}'".format(coin)]
  434. o += ["name = '{}'".format(e[0].lower())]
  435. o += ["nameCaps = '{}'".format(e[0])]
  436. a = "addr_ver_num = {{ 'p2pkh': ({},{!r})".format(num2hexstr(e[3][0]),e[3][1])
  437. b = ", 'p2sh': ({},{!r})".format(num2hexstr(e[4][0]),e[4][1]) if e[4] else ''
  438. o += [a+b+' }']
  439. o += ["wif_ver_num = {{ 'std': {} }}".format(num2hexstr(e[2]))]
  440. o += ["mmtypes = ('L','C'{})".format(",'S'" if e[5] else '')]
  441. o += ["dfl_mmtype = '{}'".format('L')]
  442. return '\n\t'.join(o) + '\n'
  443. out = ''
  444. for e in data['mainnet']:
  445. out += make_proto(e)
  446. for e in data['testnet']:
  447. out += make_proto(e,testnet=True)
  448. tn_coins = [e[1] for e in data['testnet']]
  449. fs = "CoinProtocol.coins['{}'] = ({}Protocol,{})\n"
  450. for e in data['mainnet']:
  451. proto,coin = e[0],e[1]
  452. if proto[0] in '0123456789': proto = 'X_'+proto
  453. if proto+'Protocol' in globals(): continue
  454. if coin.lower() in CoinProtocol.coins: continue
  455. out += fs.format(coin.lower(),proto,('None',proto+'TestnetProtocol')[coin in tn_coins])
  456. # print out
  457. return out
  458. def init_coin(coin,testnet=None):
  459. if testnet is not None:
  460. g.testnet = testnet
  461. coin = coin.upper()
  462. g.coin = coin
  463. g.proto = CoinProtocol(coin,g.testnet)