Browse Source

py3port: use floor division where applicable

MMGen 6 years ago
parent
commit
46f44b645b

+ 1 - 1
mmgen/addr.py

@@ -136,7 +136,7 @@ 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)])
+		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)
 		return a + b
 

+ 1 - 1
mmgen/altcoin.py

@@ -459,7 +459,7 @@ class CoinInfo(object):
 		def phash2addr(ver_num,pk_hash):
 			from mmgen.protocol import _b58chk_encode
 			s = '{:0{}x}'.format(ver_num,2 if ver_num < 256 else 4) + pk_hash
-			lzeroes = (len(s) - len(s.lstrip('0'))) / 2 # non-zero only for ver num '00' (BTC p2pkh)
+			lzeroes = (len(s) - len(s.lstrip('0'))) // 2 # non-zero only for ver num '00' (BTC p2pkh)
 			return ('1' * lzeroes) + _b58chk_encode(s)
 
 		low = phash2addr(ver_num,'00'*20)

+ 2 - 2
mmgen/altcoins/eth/contract.py

@@ -32,7 +32,7 @@ from mmgen.obj import MMGenObject,TokenAddr,CoinTxID,ETHAmt
 from mmgen.util import msg,msg_r,pmsg,pdie
 
 def parse_abi(s):
-	return [s[:8]] + [s[8+x*64:8+(x+1)*64] for x in range(len(s[8:])/64)]
+	return [s[:8]] + [s[8+x*64:8+(x+1)*64] for x in range(len(s[8:])//64)]
 
 def create_method_id(sig): return keccak_256(sig).hexdigest()[:8]
 
@@ -88,7 +88,7 @@ class Token(MMGenObject): # ERC20
 	def create_data(self,to_addr,amt,method_sig='transfer(address,uint256)',from_addr=None):
 		from_arg = from_addr.rjust(64,'0') if from_addr else ''
 		to_arg = to_addr.rjust(64,'0')
-		amt_arg = '{:064x}'.format(int(amt/self.base_unit))
+		amt_arg = '{:064x}'.format(int(amt//self.base_unit))
 		return create_method_id(method_sig) + from_arg + to_arg + amt_arg
 
 	def txcreate(   self,from_addr,to_addr,amt,start_gas,gasPrice,nonce=None,

+ 6 - 6
mmgen/altcoins/eth/obj.py

@@ -38,12 +38,12 @@ class ETHAmt(BTCAmt):
 	units = ('wei','Kwei','Mwei','Gwei','szabo','finney')
 	amt_fs = '4.18'
 
-	def toWei(self):    return int(Decimal(self) / self.wei)
-	def toKwei(self):   return int(Decimal(self) / self.Kwei)
-	def toMwei(self):   return int(Decimal(self) / self.Mwei)
-	def toGwei(self):   return int(Decimal(self) / self.Gwei)
-	def toSzabo(self):  return int(Decimal(self) / self.szabo)
-	def toFinney(self): return int(Decimal(self) / self.finney)
+	def toWei(self):    return int(Decimal(self) // self.wei)
+	def toKwei(self):   return int(Decimal(self) // self.Kwei)
+	def toMwei(self):   return int(Decimal(self) // self.Mwei)
+	def toGwei(self):   return int(Decimal(self) // self.Gwei)
+	def toSzabo(self):  return int(Decimal(self) // self.szabo)
+	def toFinney(self): return int(Decimal(self) // self.finney)
 
 class ETHNonce(int,Hilite,InitErrors): # WIP
 	def __new__(cls,n,on_fail='die'):

+ 2 - 2
mmgen/altcoins/eth/tx.py

@@ -190,7 +190,7 @@ class EthereumMMGenTX(MMGenTX):
 
 	# given absolute fee in ETH, return gas price in Gwei using tx_gas
 	def fee_abs2rel(self,abs_fee,to_unit='Gwei'):
-		ret = ETHAmt(int(abs_fee.toWei() / self.tx_gas.toWei()),'wei')
+		ret = ETHAmt(int(abs_fee.toWei() // self.tx_gas.toWei()),'wei')
 		dmsg('fee_abs2rel() ==> {} ETH'.format(ret))
 		return ret if to_unit == 'eth' else ret.to_unit(to_unit,show_decimal=True)
 
@@ -253,7 +253,7 @@ class EthereumMMGenTX(MMGenTX):
 		keys = ('from','to','amt','nonce')
 		ld = len(self.txobj['data'])
 		return fs.format(   *((self.txobj[k] if self.txobj[k] != '' else Str('None')).hl() for k in keys),
-							d='{}... ({} bytes)'.format(self.txobj['data'][:40],ld/2) if ld else Str('None'),
+							d='{}... ({} bytes)'.format(self.txobj['data'][:40],ld//2) if ld else Str('None'),
 							c=g.dcoin if len(self.outputs) else '',
 							g=yellow(str(self.txobj['gasPrice'].to_unit('Gwei',show_decimal=True))),
 							G=yellow(str(self.txobj['startGas'].toKwei())),

+ 1 - 1
mmgen/main_passgen.py

@@ -127,7 +127,7 @@ sf = get_seed_file(cmd_args,1)
 
 pw_fmt = ('b58','b32','hex')[bool(opt.base32)+2*bool(opt.hex)]
 
-pw_len = (opt.passwd_len,dfl_len[pw_fmt]/2)[opt.passwd_len in ('h','H')]
+pw_len = (opt.passwd_len,dfl_len[pw_fmt]//2)[opt.passwd_len in ('h','H')]
 
 PasswordList(pw_id_str=pw_id_str,pw_len=pw_len,pw_fmt=pw_fmt,chk_params_only=True)
 do_license_msg()

+ 3 - 3
mmgen/obj.py

@@ -339,10 +339,10 @@ class BTCAmt(Decimal,Hilite,InitErrors):
 			return cls.init_fail(m.format(num,cls.__name__,e.message),on_fail)
 
 	def toSatoshi(self):
-		return int(Decimal(self) / self.satoshi)
+		return int(Decimal(self) // self.satoshi)
 
 	def to_unit(self,unit,show_decimal=False):
-		ret = Decimal(self) / getattr(self,unit)
+		ret = Decimal(self) // getattr(self,unit)
 		if show_decimal and ret < 1:
 			return '{:.8f}'.format(ret).rstrip('0')
 		return int(ret)
@@ -656,7 +656,7 @@ class PrivKey(str,Hilite,InitErrors,MMGenObject):
 
 		try:
 			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)
+			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'))
 			else:

+ 2 - 2
mmgen/protocol.py

@@ -45,7 +45,7 @@ def _numtob58(num):
 	def b58enc(n):
 		while n:
 			yield _b58a[n % 58]
-			n /= 58
+			n //= 58
 	return ''.join(b58enc(num))[::-1]
 
 def _b58tonum(b58str):
@@ -415,7 +415,7 @@ class MoneroProtocol(DummyWIF,BitcoinProtocolAddrgen):
 		def b58dec(addr_str):
 			from mmgen.util import baseconv
 			dec,l = baseconv.tohex,len(addr_str)
-			a = ''.join([dec(addr_str[i*11:i*11+11],'b58',pad=16) for i in range(l/11)])
+			a = ''.join([dec(addr_str[i*11:i*11+11],'b58',pad=16) for i in range(l//11)])
 			b = dec(addr_str[-(l%11):],'b58',pad=10)
 			return a + b
 

+ 6 - 6
mmgen/seed.py

@@ -40,7 +40,7 @@ class Seed(MMGenObject):
 	def __init__(self,seed_bin=None):
 		if not seed_bin:
 			# Truncate random data for smaller seed lengths
-			seed_bin = sha256(get_random(1033)).digest()[:opt.seed_len/8]
+			seed_bin = sha256(get_random(1033)).digest()[:opt.seed_len//8]
 		elif len(seed_bin)*8 not in g.seed_lens:
 			die(3,'{}: invalid seed length'.format(len(seed_bin)))
 
@@ -357,7 +357,7 @@ class Mnemonic (SeedSourceUnenc):
 	fmt_codes = 'mmwords','words','mnemonic','mnem','mn','m'
 	desc = 'mnemonic data'
 	ext = 'mmwords'
-	mn_lens = [i / 32 * 3 for i in g.seed_lens]
+	mn_lens = [i // 32 * 3 for i in g.seed_lens]
 	wl_id = 'electrum' # or 'tirosh'
 
 	def _get_data_from_user(self,desc):
@@ -429,10 +429,10 @@ class Mnemonic (SeedSourceUnenc):
 		return ' '.join(words)
 
 	@staticmethod
-	def _mn2hex_pad(mn): return len(mn) * 8 / 3
+	def _mn2hex_pad(mn): return len(mn) * 8 // 3
 
 	@staticmethod
-	def _hex2mn_pad(hexnum): return len(hexnum) * 3 / 8
+	def _hex2mn_pad(hexnum): return len(hexnum) * 3 // 8
 
 	def _format(self):
 
@@ -768,7 +768,7 @@ class Brainwallet (SeedSourceEnc):
 			seed_len = opt.seed_len
 		qmsg_r('Hashing brainwallet data.  Please wait...')
 		# Use buflen arg of scrypt.hash() to get seed of desired length
-		seed = scrypt_hash_passphrase(self.brainpasswd,'',d.hash_preset,buflen=seed_len/8)
+		seed = scrypt_hash_passphrase(self.brainpasswd,'',d.hash_preset,buflen=seed_len//8)
 		qmsg('Done')
 		self.seed = Seed(seed)
 		msg('Seed ID: {}'.format(self.seed.sid))
@@ -807,7 +807,7 @@ to exit and re-run the program with the '--old-incog-fmt' option.
 
 	def _get_incog_data_len(self,seed_len):
 		e = (g.hincog_chk_len,0)[bool(opt.old_incog_fmt)]
-		return g.aesctr_iv_len + g.salt_len + e + seed_len/8
+		return g.aesctr_iv_len + g.salt_len + e + seed_len//8
 
 	def _incog_data_size_chk(self):
 		# valid sizes: 56, 64, 72

+ 1 - 1
mmgen/sha256.py

@@ -72,7 +72,7 @@ class Sha256(object):
 
 	def bytesToWords(self):
 		assert type(self.M) in (str,list)
-		words = [0] * (len(self.M) / 4 + len(self.M) % 4)
+		words = [0] * (len(self.M) // 4 + len(self.M) % 4)
 		b = 0
 		for i in range(len(self.M)):
 			words[b >> 5] |= ord(self.M[i]) << (24 - b % 32)

+ 4 - 4
mmgen/tw.py

@@ -108,7 +108,7 @@ watch-only wallet using '{}-addrimport' and then re-run this program.
 #		sys.exit(0)
 
 		if not us_rpc: die(0,self.wmsg['no_spendable_outputs'])
-		confs_per_day = 60*60*24 / g.proto.secs_per_block
+		confs_per_day = 60*60*24 // g.proto.secs_per_block
 		tr_rpc = []
 		lbl_id = ('account','label')['label_api' in g.rpch.caps]
 		for o in us_rpc:
@@ -118,7 +118,7 @@ watch-only wallet using '{}-addrimport' and then re-run this program.
 				o.update({
 					'twmmid': l.mmid,
 					'label':  l.comment,
-					'days':   int(o['confirmations'] / confs_per_day),
+					'days':   int(o['confirmations'] // confs_per_day),
 					'amt':    g.proto.coin_amt(o['amount']),
 					'addr':   CoinAddr(o['address']),
 					'confs':  o['confirmations']
@@ -482,7 +482,7 @@ class TwAddrList(MMGenDict):
 				return j.sort_key
 
 		al_id_save = None
-		confs_per_day = 60*60*24 / g.proto.secs_per_block
+		confs_per_day = 60*60*24 // g.proto.secs_per_block
 		for mmid in sorted(self,key=sort_algo,reverse=bool(sort and 'reverse' in sort)):
 			if mmid.type == 'mmgen':
 				if al_id_save and al_id_save != mmid.obj.al_id:
@@ -500,7 +500,7 @@ class TwAddrList(MMGenDict):
 				addr=(e['addr'].fmt(color=True,width=addr_width) if showbtcaddrs else None),
 				cmt=e['lbl'].comment.fmt(width=max_cmt_len,color=True,nullrepl='-'),
 				amt=e['amt'].fmt('4.{}'.format(max(max_fp_len,3)),color=True),
-				age=mmid.confs / (1,confs_per_day)[show_days] if hasattr(mmid,'confs') and mmid.confs != None else '-'
+				age=mmid.confs // (1,confs_per_day)[show_days] if hasattr(mmid,'confs') and mmid.confs != None else '-'
 				))
 
 		return '\n'.join(out + ['\nTOTAL: {} {}'.format(self.total.hl(color=True),g.dcoin)])

+ 7 - 7
mmgen/tx.py

@@ -474,7 +474,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 		new_size =           4       + 1     + 1   + 1   + isize + 1  + osize + wsize  + 4 \
 				if wsize else old_size
 
-		ret = (old_size * 3 + new_size) / 4
+		ret = (old_size * 3 + new_size) // 4
 
 		dmsg('\nData from estimate_size():')
 		dmsg('  inputs size: {}, outputs size: {}, witness size: {}'.format(isize,osize,wsize))
@@ -485,14 +485,14 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 	# coin-specific fee routines
 	def get_relay_fee(self):
 		kb_fee = g.proto.coin_amt(g.rpch.getnetworkinfo()['relayfee'])
-		ret = kb_fee * self.estimate_size() / 1024
+		ret = kb_fee * self.estimate_size() // 1024
 		vmsg('Relay fee: {} {c}/kB, for transaction: {} {c}'.format(kb_fee,ret,c=g.coin))
 		return ret
 
 	# convert absolute BTC fee to satoshis-per-byte using estimated size
 	def fee_abs2rel(self,abs_fee,to_unit=None):
 		unit = getattr(g.proto.coin_amt,to_unit or 'min_coin_unit')
-		return int(abs_fee / unit / self.estimate_size())
+		return int(abs_fee // unit // self.estimate_size())
 
 	def get_rel_fee_from_network(self): # rel_fee is in BTC/kB
 		try:
@@ -514,7 +514,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 	# given network fee estimate in BTC/kB, return absolute fee using estimated tx size
 	def fee_est2abs(self,rel_fee,fe_type=None):
 		tx_size = self.estimate_size()
-		ret = g.proto.coin_amt(rel_fee) * opt.tx_fee_adj * tx_size / 1024
+		ret = g.proto.coin_amt(rel_fee) * opt.tx_fee_adj * tx_size // 1024
 		if opt.verbose:
 			msg('{} fee for {} confirmations: {} {}/kB'.format(fe_type.upper(),opt.tx_confs,rel_fee,g.coin))
 			msg('TX size (estimated): {}'.format(tx_size))
@@ -1016,11 +1016,11 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 			ip = desc == 'inputs'
 			out = desc.capitalize() + ':\n' + enl
 			addr_w = max(len(e.addr) for e in io)
-			confs_per_day = 60*60*24 / g.proto.secs_per_block
+			confs_per_day = 60*60*24 // g.proto.secs_per_block
 			for n,e in enumerate(sorted(io,key=lambda o: o.mmid.sort_key if o.mmid else o.addr)):
 				if ip and blockcount:
 					confs = e.confs + blockcount - self.blockcount
-					days = int(confs / confs_per_day)
+					days = int(confs // confs_per_day)
 				if e.mmid:
 					mmid_fmt = e.mmid.fmt(
 						width=max_mmwid,
@@ -1057,7 +1057,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 		return g.proto.coin_amt(self.get_fee_from_tx()).hl()
 
 	def format_view_verbose_footer(self):
-		ts = len(self.hex)/2 if self.hex else 'unknown'
+		ts = len(self.hex)//2 if self.hex else 'unknown'
 		out = 'Transaction size: Vsize {} (estimated), Total {}'.format(self.estimate_size(),ts)
 		if self.marked_signed():
 			ws = DeserializedTX(self.hex)['witness_size']

+ 9 - 10
mmgen/util.py

@@ -170,7 +170,7 @@ def make_chksum_N(s,nchars,sep=False):
 	if nchars%4 or not (4 <= nchars <= 64): return False
 	s = sha256(sha256(s).digest()).hexdigest().upper()
 	sep = ('',' ')[bool(sep)]
-	return sep.join([s[i*4:i*4+4] for i in range(nchars/4)])
+	return sep.join([s[i*4:i*4+4] for i in range(nchars//4)])
 
 def make_chksum_8(s,sep=False):
 	from mmgen.obj import HexStr
@@ -191,8 +191,7 @@ def split2(s,sep=None): return splitN(s,2,sep) # always return a 2-element list
 def split3(s,sep=None): return splitN(s,3,sep) # always return a 3-element list
 
 def split_into_cols(col_wid,s):
-	return ' '.join([s[col_wid*i:col_wid*(i+1)]
-					for i in range(len(s)/col_wid+1)]).rstrip()
+	return ' '.join([s[col_wid*i:col_wid*(i+1)] for i in range(len(s)//col_wid+1)]).rstrip()
 
 def screen_width(s):
 	return len(s) + len([1 for ch in s if unicodedata.east_asian_width(ch) in ('F','W')])
@@ -220,16 +219,16 @@ def make_timestr(secs=None):
 	return '{:04d}/{:02d}/{:02d} {:02d}:{:02d}:{:02d}'.format(*tv)
 
 def secs_to_dhms(secs):
-	dsecs = secs/3600
+	dsecs = secs//3600
 	return '{}{:02d}:{:02d}:{:02d}'.format(
-		('','{} day{}, '.format(dsecs/24,suf(dsecs/24)))[dsecs > 24],
-		dsecs % 24, (secs/60) % 60, secs % 60)
+		('','{} day{}, '.format(dsecs//24,suf(dsecs//24)))[dsecs > 24],
+		dsecs % 24, (secs//60) % 60, secs % 60)
 
 def secs_to_hms(secs):
-	return '{:02d}:{:02d}:{:02d}'.format(secs/3600, (secs/60) % 60, secs % 60)
+	return '{:02d}:{:02d}:{:02d}'.format(secs//3600, (secs//60) % 60, secs % 60)
 
 def secs_to_ms(secs):
-	return '{:02d}:{:02d}'.format(secs/60, secs % 60)
+	return '{:02d}:{:02d}'.format(secs//60, secs % 60)
 
 def is_int(s):
 	try:
@@ -344,7 +343,7 @@ class baseconv(object):
 		num,ret = int(hexnum,16),[]
 		while num:
 			ret.append(num % base)
-			num /= base
+			num //= base
 		o = [wl[n] for n in [0] * ((pad or 0)-len(ret)) + ret[::-1]]
 		return ''.join(o) if tostr else o
 
@@ -379,7 +378,7 @@ def pretty_hexdump(data,gw=2,cols=8,line_nums=False):
 		[
 			('' if (line_nums == False or i % cols) else '{:06x}: '.format(i*gw)) +
 				hexlify(data[i*gw:i*gw+gw]) + ('\n',' ')[bool((i+1) % cols)]
-					for i in range(len(data)/gw + r)
+					for i in range(len(data)//gw + r)
 		]
 	).rstrip() + '\n'
 

+ 1 - 1
scripts/tx-v1-to-v3.py

@@ -84,7 +84,7 @@ def find_block_by_time(timestamp):
 			top = block_num
 		else:
 			bot = block_num
-		block_num = (top + bot) / 2
+		block_num = (top + bot) // 2
 		if top - bot < 2:
 			msg('\nFound: {} '.format(block_num))
 			break

+ 1 - 1
test/scrambletest.py

@@ -112,4 +112,4 @@ run_tests()
 
 t = int(time.time()) - start_time
 m = '\nAll requested tests finished OK, elapsed time: {:02}:{:02}'
-gmsg(m.format(t/60,t%60))
+gmsg(m.format(t//60,t%60))

+ 2 - 2
test/test.py

@@ -1374,7 +1374,7 @@ def create_fake_unspent_entry(coinaddr,al_id=None,idx=None,lbl=None,non_mmgen=Fa
 		'address': coinaddr,
 		'spendable': False,
 		'scriptPubKey': '{}{}{}'.format(s_beg,coinaddr.hex,s_end),
-		'confirmations': getrandnum(3) / 2 # max: 8388608 (7 digits)
+		'confirmations': getrandnum(3) // 2 # max: 8388608 (7 digits)
 	}
 	return ret
 
@@ -3839,7 +3839,7 @@ start_time = int(time.time())
 def end_msg():
 	t = int(time.time()) - start_time
 	m = '{} test{} performed.  Elapsed time: {:02d}:{:02d}\n'
-	sys.stderr.write(green(m.format(cmd_total,suf(cmd_total),t/60,t%60)))
+	sys.stderr.write(green(m.format(cmd_total,suf(cmd_total),t//60,t%60)))
 
 ts = MMGenTestSuite()
 

+ 1 - 1
test/tooltest.py

@@ -506,4 +506,4 @@ else:
 		if cmd is not list(cmd_data.keys())[-1]: msg('')
 
 t = int(time.time()) - start_time
-gmsg('All requested tests finished OK, elapsed time: {:02}:{:02}'.format(t/60,t%60))
+gmsg('All requested tests finished OK, elapsed time: {:02}:{:02}'.format(t//60,t%60))