From f6d5c5b465339c1331cc971b41ec995135cecf57 Mon Sep 17 00:00:00 2001 From: MMGen Date: Wed, 31 Oct 2018 15:30:11 +0000 Subject: [PATCH] py3port: replace s.encode('hex'), s.decode('hex') with hexlify(), unhexlify() --- mmgen/addr.py | 21 +++++++++++---------- mmgen/altcoins/eth/contract.py | 16 ++++++++-------- mmgen/altcoins/eth/tx.py | 16 ++++++++-------- mmgen/obj.py | 7 ++++--- mmgen/protocol.py | 12 ++++++------ mmgen/sha256.py | 4 +++- test/gentest.py | 2 +- test/sha256test.py | 3 ++- test/test.py | 2 +- 9 files changed, 44 insertions(+), 39 deletions(-) diff --git a/mmgen/addr.py b/mmgen/addr.py index c936edc2..cbd89e18 100755 --- a/mmgen/addr.py +++ b/mmgen/addr.py @@ -83,7 +83,7 @@ class AddrGeneratorEthereum(AddrGenerator): def to_addr(self,pubhex): assert type(pubhex) == PubKey import sha3 - return CoinAddr(sha3.keccak_256(pubhex[2:].decode('hex')).digest()[12:].encode('hex')) + return CoinAddr(hexlify(sha3.keccak_256(unhexlify(pubhex[2:])).digest()[12:]).decode()) def to_wallet_passwd(self,sk_hex): from mmgen.protocol import hash256 @@ -106,7 +106,7 @@ class AddrGeneratorZcashZ(AddrGenerator): return Sha256(list(map(chr,s)),preprocess=False).digest() def to_addr(self,pubhex): # pubhex is really privhex - key = pubhex.decode('hex') + key = unhexlify(pubhex) assert len(key) == 32,'{}: incorrect privkey length'.format(len(key)) if g.platform == 'win': ydie(1,'Zcash z-addresses not supported on Windows platform') @@ -118,7 +118,7 @@ class AddrGeneratorZcashZ(AddrGenerator): return CoinAddr(ret) def to_viewkey(self,pubhex): # pubhex is really privhex - key = pubhex.decode('hex') + key = unhexlify(pubhex) assert len(key) == 32,'{}: incorrect privkey length'.format(len(key)) vk = list(map(ord,self.zhash256(key,0)+self.zhash256(key,1))) vk[32] &= 0xf8 @@ -136,8 +136,8 @@ class AddrGeneratorMonero(AddrGenerator): def b58enc(self,addr_str): enc,l = baseconv.fromhex,len(addr_str) - a = ''.join([enc(addr_str[i*8:i*8+8].encode('hex'),'b58',pad=11,tostr=True) for i in range(l//8)]) - b = enc(addr_str[l-l%8:].encode('hex'),'b58',pad=7,tostr=True) + a = ''.join([enc(hexlify(addr_str[i*8:i*8+8]),'b58',pad=11,tostr=True) for i in range(l//8)]) + b = enc(hexlify(addr_str[l-l%8:]),'b58',pad=7,tostr=True) return a + b def to_addr(self,sk_hex): # sk_hex instead of pubhex @@ -162,12 +162,12 @@ class AddrGeneratorMonero(AddrGenerator): return Q def hex2int_le(hexstr): - return int(hexstr.decode('hex')[::-1].encode('hex'),16) + return int(hexlify(unhexlify(hexstr)[::-1]),16) vk_hex = self.to_viewkey(sk_hex) pk_str = encodepoint(scalarmultbase(hex2int_le(sk_hex))) pvk_str = encodepoint(scalarmultbase(hex2int_le(vk_hex))) - addr_p1 = g.proto.addr_ver_num['monero'][0].decode('hex') + pk_str + pvk_str + addr_p1 = unhexlify(g.proto.addr_ver_num['monero'][0]) + pk_str + pvk_str import sha3 return CoinAddr(self.b58enc(addr_p1 + sha3.keccak_256(addr_p1).digest()[:4])) @@ -179,7 +179,7 @@ class AddrGeneratorMonero(AddrGenerator): def to_viewkey(self,sk_hex): assert len(sk_hex) == 64,'{}: incorrect privkey length'.format(len(sk_hex)) import sha3 - return MoneroViewKey(g.proto.preprocess_key(sha3.keccak_256(sk_hex.decode('hex')).hexdigest(),None)) + return MoneroViewKey(g.proto.preprocess_key(sha3.keccak_256(unhexlify(sk_hex)).hexdigest(),None)) def to_segwit_redeem_script(self,sk_hex): raise NotImplementedError('Monero addresses incompatible with Segwit') @@ -212,7 +212,8 @@ class KeyGenerator(MMGenObject): def test_for_secp256k1(self,silent=False): try: from mmgen.secp256k1 import priv2pub - assert priv2pub(('deadbeef'*8).decode('hex'),1) + m = 'Unable to execute priv2pub() from secp256k1 extension module' + assert priv2pub(unhexlify('deadbeef'*8),1),m return True except: return False @@ -408,7 +409,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file seed = seed.get_data() seed = self.scramble_seed(seed) - dmsg_sc('seed',seed[:8].encode('hex')) + dmsg_sc('seed',hexlify(seed[:8]).decode()) compressed = self.al_id.mmtype.compressed pubkey_type = self.al_id.mmtype.pubkey_type diff --git a/mmgen/altcoins/eth/contract.py b/mmgen/altcoins/eth/contract.py index 60136cec..843acf19 100755 --- a/mmgen/altcoins/eth/contract.py +++ b/mmgen/altcoins/eth/contract.py @@ -65,8 +65,8 @@ class Token(MMGenObject): # ERC20 def total_supply(self): return self.do_call('totalSupply()',toUnit=True) def decimals(self): return int(self.do_call('decimals()'),16) - def name(self): return self.strip(self.do_call('name()')[2:].decode('hex')) - def symbol(self): return self.strip(self.do_call('symbol()')[2:].decode('hex')) + def name(self): return self.strip(unhexlify(self.do_call('name()')[2:])) + def symbol(self): return self.strip(unhexlify(self.do_call('symbol()')[2:])) def info(self): fs = '{:15}{}\n' * 5 @@ -96,23 +96,23 @@ class Token(MMGenObject): # ERC20 if nonce is None: nonce = int(g.rpch.parity_nextNonce('0x'+from_addr),16) data = self.create_data(to_addr,amt,method_sig=method_sig,from_addr=from_addr2) - return {'to': self.addr.decode('hex'), + return {'to': unhexlify(self.addr), 'startgas': start_gas.toWei(), 'gasprice': gasPrice.toWei(), 'value': 0, 'nonce': nonce, - 'data': data.decode('hex') } + 'data': unhexlify(data) } def txsign(self,tx_in,key,from_addr,chain_id=None): tx = Transaction(**tx_in) if chain_id is None: chain_id = int(g.rpch.parity_chainId(),16) tx.sign(key,chain_id) - hex_tx = rlp.encode(tx).encode('hex') - coin_txid = CoinTxID(tx.hash.encode('hex')) - if tx.sender.encode('hex') != from_addr: + hex_tx = hexlify(rlp.encode(tx)) + coin_txid = CoinTxID(hexlify(tx.hash)) + if hexlify(tx.sender).decode() != from_addr: m = "Sender address '{}' does not match address of key '{}'!" - die(3,m.format(from_addr,tx.sender.encode('hex'))) + die(3,m.format(from_addr,hexlify(tx.sender).decode())) if g.debug: msg('{}'.format('\n '.join(parse_abi(data)))) pmsg(tx.to_dict()) diff --git a/mmgen/altcoins/eth/tx.py b/mmgen/altcoins/eth/tx.py index b7f7e0aa..c0e497a9 100755 --- a/mmgen/altcoins/eth/tx.py +++ b/mmgen/altcoins/eth/tx.py @@ -95,7 +95,7 @@ class EthereumMMGenTX(MMGenTX): if self.check_sigs(): from ethereum.transactions import Transaction import rlp - etx = rlp.decode(self.hex.decode('hex'),Transaction) + etx = rlp.decode(unhexlify(self.hex),Transaction) d = etx.to_dict() # ==> hex values have '0x' prefix, 0 is '0x' for k in ('sender','to','data'): if k in d: d[k] = d[k].replace('0x','',1) @@ -107,8 +107,8 @@ class EthereumMMGenTX(MMGenTX): 'nonce': ETHNonce(d['nonce']), 'data': HexStr(d['data']) } if o['data'] and not o['to']: - self.token_addr = TokenAddr(etx.creates.encode('hex')).decode() - txid = CoinTxID(etx.hash.encode('hex')) + self.token_addr = TokenAddr(hexlify(etx.creates).decode()) + txid = CoinTxID(hexlify(etx.hash)) assert txid == self.coin_txid,"txid in tx.hex doesn't match value in MMGen transaction file" else: d = json.loads(self.hex) @@ -279,12 +279,12 @@ class EthereumMMGenTX(MMGenTX): def do_sign(self,d,wif,tx_num_str): - d_in = {'to': d['to'].decode('hex'), + d_in = {'to': unhexlify(d['to']), 'startgas': d['startGas'].toWei(), 'gasprice': d['gasPrice'].toWei(), 'value': d['amt'].toWei() if d['amt'] else 0, 'nonce': d['nonce'], - 'data': d['data'].decode('hex')} + 'data': unhexlify(d['data'])} msg_r('Signing transaction{}...'.format(tx_num_str)) @@ -293,11 +293,11 @@ class EthereumMMGenTX(MMGenTX): etx = Transaction(**d_in) etx.sign(wif,d['chainId']) import rlp - self.hex = rlp.encode(etx).encode('hex') - self.coin_txid = CoinTxID(etx.hash.encode('hex')) + self.hex = hexlify(rlp.encode(etx)) + self.coin_txid = CoinTxID(hexlify(etx.hash)) msg('OK') if d['data']: - self.token_addr = TokenAddr(etx.creates.encode('hex')) + self.token_addr = TokenAddr(hexlify(etx.creates)) except Exception as e: m = "{!r}: transaction signing failed!" msg(m.format(e.message)) diff --git a/mmgen/obj.py b/mmgen/obj.py index f0cc77c0..591cb58c 100755 --- a/mmgen/obj.py +++ b/mmgen/obj.py @@ -25,6 +25,7 @@ import sys,os,unicodedata from decimal import * from mmgen.color import * from string import hexdigits,ascii_letters,digits +from binascii import hexlify def is_mmgen_seed_id(s): return SeedID(sid=s,on_fail='silent') def is_mmgen_idx(s): return AddrIdx(s,on_fail='silent') @@ -658,13 +659,13 @@ class PrivKey(str,Hilite,InitErrors,MMGenObject): assert s and type(compressed) == bool and pubkey_type,'Incorrect args for PrivKey()' assert len(s) == cls.width // 2,'Key length must be {}'.format(cls.width/2) if pubkey_type == 'password': # skip WIF creation and pre-processing for passwds - me = str.__new__(cls,s.encode('hex')) + me = str.__new__(cls,hexlify(s)) else: - me = str.__new__(cls,g.proto.preprocess_key(s.encode('hex'),pubkey_type)) + me = str.__new__(cls,g.proto.preprocess_key(hexlify(s),pubkey_type)) me.wif = WifKey(g.proto.hex2wif(me,pubkey_type,compressed),on_fail='raise') me.compressed = compressed me.pubkey_type = pubkey_type - me.orig_hex = s.encode('hex') # save the non-preprocessed key + me.orig_hex = hexlify(s) # save the non-preprocessed key return me except Exception as e: fs = "Key={!r}\nCompressed={}\nValue pair cannot be converted to PrivKey\n({})" diff --git a/mmgen/protocol.py b/mmgen/protocol.py index cec8ee71..66d32e67 100755 --- a/mmgen/protocol.py +++ b/mmgen/protocol.py @@ -21,7 +21,7 @@ protocol.py: Coin protocol functions, classes and methods """ import sys,os,hashlib -from binascii import unhexlify +from binascii import hexlify,unhexlify from mmgen.util import msg,pmsg,ymsg,Msg,pdie,ydie from mmgen.obj import MMGenObject,BTCAmt,LTCAmt,BCHAmt,B2XAmt,ETHAmt from mmgen.globalvars import g @@ -153,7 +153,7 @@ class BitcoinProtocol(MMGenObject): msg('{}: Invalid witness version number'.format(ret[0])) elif ret[1]: return { - 'hex': ''.join(map(chr,ret[1])).encode('hex'), + 'hex': hexlify(''.join(map(chr,ret[1]))), 'format': 'bech32' } if return_dict else True return False @@ -203,7 +203,7 @@ class BitcoinProtocol(MMGenObject): @classmethod def pubhash2bech32addr(cls,pubhash): - d = list(map(ord,pubhash.decode('hex'))) + d = list(unhexlify(pubhash)) return bech32.bech32_encode(cls.bech32_hrp,[cls.witness_vernum]+bech32.convertbits(d,8,5)) class BitcoinTestnetProtocol(BitcoinProtocol): @@ -406,8 +406,8 @@ class MoneroProtocol(DummyWIF,BitcoinProtocolAddrgen): from ed25519ll.djbec import l except: from mmgen.ed25519 import l - n = int(hexpriv.decode('hex')[::-1].encode('hex'),16) % l - return '{:064x}'.format(n).decode('hex')[::-1].encode('hex') + n = int(hexlify(unhexlify(hexpriv)[::-1]),16) % l + return hexlify(unhexlify('{:064x}'.format(n))[::-1]) @classmethod def verify_addr(cls,addr,hex_width,return_dict=False): @@ -425,7 +425,7 @@ class MoneroProtocol(DummyWIF,BitcoinProtocolAddrgen): ret = b58dec(addr) import sha3 - chk = sha3.keccak_256(ret.decode('hex')[:-4]).hexdigest()[:8] + chk = sha3.keccak_256(unhexlify(ret)[:-4]).hexdigest()[:8] assert chk == ret[-8:],'Incorrect checksum' return { 'hex': ret.encode(), 'format': 'monero' } if return_dict else True diff --git a/mmgen/sha256.py b/mmgen/sha256.py index 4677df7b..93e36c2e 100755 --- a/mmgen/sha256.py +++ b/mmgen/sha256.py @@ -29,6 +29,8 @@ sha256.py: custom sha256 implementation for Zcash # and here: # https://github.com/howardwu/zaddr +from binascii import hexlify + class Sha256(object): def initConstants(): @@ -68,7 +70,7 @@ class Sha256(object): return self.M def hexdigest(self): - return self.digest().encode('hex') + return hexlify(self.digest()) def bytesToWords(self): assert type(self.M) in (str,list) diff --git a/test/gentest.py b/test/gentest.py index 454d0cc9..c4cc0b98 100755 --- a/test/gentest.py +++ b/test/gentest.py @@ -81,7 +81,7 @@ if not 1 <= len(cmd_args) <= 2: opts.usage() addr_type = MMGenAddrType(opt.type or g.proto.dfl_mmtype) def pyethereum_sec2addr(sec): - return sec.decode(),eth.privtoaddr(sec).encode('hex') + return sec.decode(),hexlify(eth.privtoaddr(sec)).decode() def keyconv_sec2addr(sec): p = sp.Popen(['keyconv','-C',g.coin,sec.wif],stderr=sp.PIPE,stdout=sp.PIPE) diff --git a/test/sha256test.py b/test/sha256test.py index ec1f2527..83a644fa 100755 --- a/test/sha256test.py +++ b/test/sha256test.py @@ -2,6 +2,7 @@ import sys,os,hashlib +from binascii import hexlify from mmgen.sha256 import Sha256 random_rounds = int(sys.argv[1]) if len(sys.argv) == 2 else 500 @@ -39,7 +40,7 @@ def test_random(rounds): for i in range(rounds): if i+1 in (1,rounds) or not (i+1) % 10: msg('\rTesting random input data: {:4}/{} '.format(i+1,rounds)) - dlen = int(os.urandom(4).encode('hex'),16) >> 18 + dlen = int(hexlify(os.urandom(4)),16) >> 18 compare_hashes(dlen,os.urandom(dlen)) msg('OK\n') diff --git a/test/test.py b/test/test.py index d9e99449..651989ff 100755 --- a/test/test.py +++ b/test/test.py @@ -1369,7 +1369,7 @@ def create_fake_unspent_entry(coinaddr,al_id=None,idx=None,lbl=None,non_mmgen=Fa lbl_id: '{}:{}'.format(g.proto.base_coin.lower(),coinaddr) if non_mmgen \ else ('{}:{}{}'.format(al_id,idx,lbl)), 'vout': int(getrandnum(4) % 8), - 'txid': str(hexlify(os.urandom(32))), + 'txid': hexlify(os.urandom(32)), 'amount': g.proto.coin_amt('{}.{}'.format(amt1 + getrandnum(4) % amt2, getrandnum(4) % 100000000)), 'address': coinaddr, 'spendable': False,