py3port: 2to3 on all files
The result of running 2to3-2.7 on all Python files in the repository.
This commit is contained in:
parent
f0fea335eb
commit
949e42ebf4
39 changed files with 488 additions and 487 deletions
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
#
|
||||
# Electrum - lightweight Bitcoin client
|
||||
# Copyright (C) 2011 thomasv@gitorious
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ from mmgen.obj import *
|
|||
pnm = g.proj_name
|
||||
|
||||
def dmsg_sc(desc,data):
|
||||
if g.debug_addrlist: Msg(u'sc_debug_{}: {}'.format(desc,data))
|
||||
if g.debug_addrlist: Msg('sc_debug_{}: {}'.format(desc,data))
|
||||
|
||||
class AddrGenerator(MMGenObject):
|
||||
def __new__(cls,addr_type):
|
||||
|
|
@ -39,7 +39,7 @@ class AddrGenerator(MMGenObject):
|
|||
assert addr_type in g.proto.mmtypes,'{}: invalid address type for coin {}'.format(addr_type,g.coin)
|
||||
gen_method = addr_type.gen_method
|
||||
else:
|
||||
raise TypeError,'{}: incorrect argument type for {}()'.format(type(addr_type),cls.__name__)
|
||||
raise TypeError('{}: incorrect argument type for {}()'.format(type(addr_type),cls.__name__))
|
||||
gen_methods = {
|
||||
'p2pkh': AddrGeneratorP2PKH,
|
||||
'segwit': AddrGeneratorSegwit,
|
||||
|
|
@ -59,7 +59,7 @@ class AddrGeneratorP2PKH(AddrGenerator):
|
|||
return CoinAddr(g.proto.pubhash2addr(hash160(pubhex),p2sh=False))
|
||||
|
||||
def to_segwit_redeem_script(self,pubhex):
|
||||
raise NotImplementedError,'Segwit redeem script not supported by this address type'
|
||||
raise NotImplementedError('Segwit redeem script not supported by this address type')
|
||||
|
||||
class AddrGeneratorSegwit(AddrGenerator):
|
||||
def to_addr(self,pubhex):
|
||||
|
|
@ -77,7 +77,7 @@ class AddrGeneratorBech32(AddrGenerator):
|
|||
return CoinAddr(g.proto.pubhash2bech32addr(hash160(pubhex)))
|
||||
|
||||
def to_segwit_redeem_script(self,pubhex):
|
||||
raise NotImplementedError,'Segwit redeem script not supported by this address type'
|
||||
raise NotImplementedError('Segwit redeem script not supported by this address type')
|
||||
|
||||
class AddrGeneratorEthereum(AddrGenerator):
|
||||
def to_addr(self,pubhex):
|
||||
|
|
@ -90,7 +90,7 @@ class AddrGeneratorEthereum(AddrGenerator):
|
|||
return WalletPassword(hash256(sk_hex)[:32])
|
||||
|
||||
def to_segwit_redeem_script(self,pubhex):
|
||||
raise NotImplementedError,'Segwit redeem script not supported by this address type'
|
||||
raise NotImplementedError('Segwit redeem script not supported by this address type')
|
||||
|
||||
# github.com/FiloSottile/zcash-mini/zcash/address.go
|
||||
class AddrGeneratorZcashZ(AddrGenerator):
|
||||
|
|
@ -99,11 +99,11 @@ class AddrGeneratorZcashZ(AddrGenerator):
|
|||
vk_width = 97
|
||||
|
||||
def zhash256(self,s,t):
|
||||
s = map(ord,s+'\0'*32)
|
||||
s = list(map(ord,s+'\0'*32))
|
||||
s[0] |= 0xc0
|
||||
s[32] = t
|
||||
from mmgen.sha256 import Sha256
|
||||
return Sha256(map(chr,s),preprocess=False).digest()
|
||||
return Sha256(list(map(chr,s)),preprocess=False).digest()
|
||||
|
||||
def to_addr(self,pubhex): # pubhex is really privhex
|
||||
key = pubhex.decode('hex')
|
||||
|
|
@ -120,7 +120,7 @@ class AddrGeneratorZcashZ(AddrGenerator):
|
|||
def to_viewkey(self,pubhex): # pubhex is really privhex
|
||||
key = pubhex.decode('hex')
|
||||
assert len(key) == 32,'{}: incorrect privkey length'.format(len(key))
|
||||
vk = map(ord,self.zhash256(key,0)+self.zhash256(key,1))
|
||||
vk = list(map(ord,self.zhash256(key,0)+self.zhash256(key,1)))
|
||||
vk[32] &= 0xf8
|
||||
vk[63] &= 0x7f
|
||||
vk[63] |= 0x40
|
||||
|
|
@ -130,7 +130,7 @@ class AddrGeneratorZcashZ(AddrGenerator):
|
|||
return ZcashViewKey(ret)
|
||||
|
||||
def to_segwit_redeem_script(self,pubhex):
|
||||
raise NotImplementedError,'Zcash z-addresses incompatible with Segwit'
|
||||
raise NotImplementedError('Zcash z-addresses incompatible with Segwit')
|
||||
|
||||
class AddrGeneratorMonero(AddrGenerator):
|
||||
|
||||
|
|
@ -182,7 +182,7 @@ class AddrGeneratorMonero(AddrGenerator):
|
|||
return MoneroViewKey(g.proto.preprocess_key(sha3.keccak_256(sk_hex.decode('hex')).hexdigest(),None))
|
||||
|
||||
def to_segwit_redeem_script(self,sk_hex):
|
||||
raise NotImplementedError,'Monero addresses incompatible with Segwit'
|
||||
raise NotImplementedError('Monero addresses incompatible with Segwit')
|
||||
|
||||
class KeyGenerator(MMGenObject):
|
||||
|
||||
|
|
@ -193,7 +193,7 @@ class KeyGenerator(MMGenObject):
|
|||
assert addr_type in g.proto.mmtypes,'{}: invalid address type for coin {}'.format(addr_type,g.coin)
|
||||
pubkey_type = addr_type.pubkey_type
|
||||
else:
|
||||
raise TypeError,'{}: incorrect argument type for {}()'.format(type(addr_type),cls.__name__)
|
||||
raise TypeError('{}: incorrect argument type for {}()'.format(type(addr_type),cls.__name__))
|
||||
if pubkey_type == 'std':
|
||||
if cls.test_for_secp256k1(silent=silent) and generator != 1:
|
||||
if not opt.key_generator or opt.key_generator == 2 or generator == 2:
|
||||
|
|
@ -206,7 +206,7 @@ class KeyGenerator(MMGenObject):
|
|||
me.desc = 'mmgen-'+pubkey_type
|
||||
return me
|
||||
else:
|
||||
raise ValueError,'{}: invalid pubkey_type argument'.format(pubkey_type)
|
||||
raise ValueError('{}: invalid pubkey_type argument'.format(pubkey_type))
|
||||
|
||||
@classmethod
|
||||
def test_for_secp256k1(self,silent=False):
|
||||
|
|
@ -275,7 +275,7 @@ class AddrListEntry(MMGenListItem):
|
|||
wallet_passwd = MMGenListItemAttr('wallet_passwd','WalletPassword')
|
||||
|
||||
class PasswordListEntry(MMGenListItem):
|
||||
passwd = MMGenImmutableAttr('passwd',unicode,typeconv=False) # TODO: create Password type
|
||||
passwd = MMGenImmutableAttr('passwd',str,typeconv=False) # TODO: create Password type
|
||||
idx = MMGenImmutableAttr('idx','AddrIdx')
|
||||
label = MMGenListItemAttr('label','TwComment',reassign_ok=True)
|
||||
sec = MMGenListItemAttr('sec',PrivKey,typeconv=False)
|
||||
|
|
@ -292,7 +292,7 @@ class AddrListChksum(str,Hilite):
|
|||
) for e in addrlist.data]
|
||||
return str.__new__(cls,make_chksum_N(' '.join(lines), nchars=16, sep=True))
|
||||
|
||||
class AddrListIDStr(unicode,Hilite):
|
||||
class AddrListIDStr(str,Hilite):
|
||||
color = 'green'
|
||||
trunc_ok = False
|
||||
def __new__(cls,addrlist,fmt_str=None):
|
||||
|
|
@ -306,7 +306,7 @@ class AddrListIDStr(unicode,Hilite):
|
|||
if prev != ret[-1]: ret += '-', prev
|
||||
ret += ',', i
|
||||
prev = i
|
||||
s = ''.join(map(unicode,ret))
|
||||
s = ''.join(map(str,ret))
|
||||
|
||||
if fmt_str:
|
||||
ret = fmt_str.format(s)
|
||||
|
|
@ -316,7 +316,7 @@ class AddrListIDStr(unicode,Hilite):
|
|||
ret = '{}{}{}[{}]'.format(addrlist.al_id.sid,('-'+bc,'')[bc=='BTC'],('-'+mt,'')[mt in ('L','E')],s)
|
||||
dmsg_sc('id_str',ret[8:].split('[')[0])
|
||||
|
||||
return unicode.__new__(cls,ret)
|
||||
return str.__new__(cls,ret)
|
||||
|
||||
class AddrList(MMGenObject): # Address info for a single seed ID
|
||||
msgs = {
|
||||
|
|
@ -448,7 +448,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
|
|||
e.wallet_passwd = ag.to_wallet_passwd(e.sec)
|
||||
|
||||
if type(self) == PasswordList:
|
||||
e.passwd = unicode(self.make_passwd(e.sec)) # TODO - own type
|
||||
e.passwd = str(self.make_passwd(e.sec)) # TODO - own type
|
||||
dmsg('Key {:>03}: {}'.format(pos,e.passwd))
|
||||
|
||||
out.append(e)
|
||||
|
|
@ -482,7 +482,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
|
|||
|
||||
def write_to_file(self,ask_tty=True,ask_write_default_yes=False,binary=False,desc=None):
|
||||
tn = ('','.testnet')[g.proto.is_testnet()]
|
||||
fn = u'{}{x}{}.{}'.format(self.id_str,tn,self.ext,x=u'-α' if g.debug_utf8 else '')
|
||||
fn = '{}{x}{}.{}'.format(self.id_str,tn,self.ext,x='-α' if g.debug_utf8 else '')
|
||||
ask_tty = self.has_keys and not opt.quiet
|
||||
write_data_to_file(fn,self.fmt_data,desc or self.file_desc,ask_tty=ask_tty,binary=binary)
|
||||
|
||||
|
|
@ -563,12 +563,12 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
|
|||
|
||||
out = [self.msgs['file_header']+'\n']
|
||||
if self.chksum:
|
||||
out.append(u'# {} data checksum for {}: {}'.format(
|
||||
out.append('# {} data checksum for {}: {}'.format(
|
||||
capfirst(self.data_desc),self.id_str,self.chksum))
|
||||
out.append('# Record this value to a secure location.\n')
|
||||
|
||||
if type(self) == PasswordList:
|
||||
lbl = u'{} {} {}:{}'.format(self.al_id.sid,self.pw_id_str,self.pw_fmt,self.pw_len)
|
||||
lbl = '{} {} {}:{}'.format(self.al_id.sid,self.pw_id_str,self.pw_fmt,self.pw_len)
|
||||
else:
|
||||
bc,mt = g.proto.base_coin,self.al_id.mmtype
|
||||
l_coin = [] if bc == 'BTC' else [g.coin] if bc == 'ETH' else [bc]
|
||||
|
|
@ -578,9 +578,9 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
|
|||
lbl = self.al_id.sid + ('',' ')[bool(lbl_p2)] + lbl_p2
|
||||
|
||||
dmsg_sc('lbl',lbl[9:])
|
||||
out.append(u'{} {{'.format(lbl))
|
||||
out.append('{} {{'.format(lbl))
|
||||
|
||||
fs = u' {:<%s} {:<34}{}' % len(str(self.data[-1].idx))
|
||||
fs = ' {:<%s} {:<34}{}' % len(str(self.data[-1].idx))
|
||||
for e in self.data:
|
||||
c = ' '+e.label if enable_comments and e.label else ''
|
||||
if type(self) == KeyList:
|
||||
|
|
@ -701,14 +701,14 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
|
|||
base_coin,mmtype = 'BTC',MMGenAddrType('L')
|
||||
check_coin_mismatch(base_coin)
|
||||
else:
|
||||
raise ValueError,u"'{}': Invalid first line for {} file '{}'".format(lines[0],self.gen_desc,fn)
|
||||
raise ValueError("'{}': Invalid first line for {} file '{}'".format(lines[0],self.gen_desc,fn))
|
||||
|
||||
self.al_id = AddrListID(SeedID(sid=sid),mmtype)
|
||||
|
||||
data = self.parse_file_body(lines[1:-1])
|
||||
assert issubclass(type(data),list),'Invalid file body data'
|
||||
except Exception as e:
|
||||
m = u'Invalid address list file ({})'.format(e.message)
|
||||
m = 'Invalid address list file ({})'.format(e.message)
|
||||
if exit_on_error: die(3,m)
|
||||
msg(msg)
|
||||
return False
|
||||
|
|
@ -804,9 +804,9 @@ Record this checksum: it will be used to verify the password file in the future
|
|||
if chksum_only:
|
||||
Msg(self.chksum)
|
||||
else:
|
||||
fs = u'{}-{}-{}-{}[{{}}]'.format(self.al_id.sid,self.pw_id_str,self.pw_fmt,self.pw_len)
|
||||
fs = '{}-{}-{}-{}[{{}}]'.format(self.al_id.sid,self.pw_id_str,self.pw_fmt,self.pw_len)
|
||||
self.id_str = AddrListIDStr(self,fs)
|
||||
qmsg(u'Checksum for {} data {}: {}'.format(self.data_desc,self.id_str.hl(),self.chksum.hl()))
|
||||
qmsg('Checksum for {} data {}: {}'.format(self.data_desc,self.id_str.hl(),self.chksum.hl()))
|
||||
qmsg(self.msgs[('record_chksum','check_chksum')[bool(infile)]])
|
||||
|
||||
def set_pw_fmt(self,pw_fmt):
|
||||
|
|
@ -883,7 +883,7 @@ re-import your addresses.
|
|||
if source == 'tw': self.add_tw_data()
|
||||
|
||||
def seed_ids(self):
|
||||
return self.al_ids.keys()
|
||||
return list(self.al_ids.keys())
|
||||
|
||||
def addrlist(self,al_id):
|
||||
# TODO: Validate al_id
|
||||
|
|
@ -899,18 +899,18 @@ re-import your addresses.
|
|||
|
||||
def coinaddr2mmaddr(self,coinaddr):
|
||||
d = self.make_reverse_dict([coinaddr])
|
||||
return (d.values()[0][0]) if d else None
|
||||
return (list(d.values())[0][0]) if d else None
|
||||
|
||||
@classmethod
|
||||
def get_tw_data(cls):
|
||||
vmsg('Getting address data from tracking wallet')
|
||||
if 'label_api' in g.rpch.caps:
|
||||
accts = g.rpch.listlabels()
|
||||
alists = [a.keys() for a in g.rpch.getaddressesbylabel([[k] for k in accts],batch=True)]
|
||||
alists = [list(a.keys()) for a in g.rpch.getaddressesbylabel([[k] for k in accts],batch=True)]
|
||||
else:
|
||||
accts = g.rpch.listaccounts(0,True)
|
||||
alists = g.rpch.getaddressesbyaccount([[k] for k in accts],batch=True)
|
||||
return zip(accts,alists)
|
||||
return list(zip(accts,alists))
|
||||
|
||||
def add_tw_data(self):
|
||||
d,out,i = self.get_tw_data(),{},0
|
||||
|
|
@ -934,7 +934,7 @@ re-import your addresses.
|
|||
self.al_ids[addrlist.al_id] = addrlist
|
||||
return True
|
||||
else:
|
||||
raise TypeError, 'Error: object {!r} is not of type AddrList'.format(addrlist)
|
||||
raise TypeError('Error: object {!r} is not of type AddrList'.format(addrlist))
|
||||
|
||||
def make_reverse_dict(self,coinaddrs):
|
||||
d = MMGenDict()
|
||||
|
|
|
|||
|
|
@ -450,7 +450,7 @@ class CoinInfo(object):
|
|||
msg("Upgrading trust for coin '{}': {} -> {}".format(sym,line[6],1))
|
||||
line[6] = 1
|
||||
|
||||
print(fs.format(*line))
|
||||
print((fs.format(*line)))
|
||||
msg('Processed {} entries'.format(len(data)))
|
||||
|
||||
@classmethod
|
||||
|
|
@ -466,8 +466,8 @@ class CoinInfo(object):
|
|||
high = phash2addr(ver_num,'ff'*20)
|
||||
|
||||
if verbose:
|
||||
print('low address: ' + low)
|
||||
print('high address: ' + high)
|
||||
print(('low address: ' + low))
|
||||
print(('high address: ' + high))
|
||||
|
||||
l1,h1 = low[0],high[0]
|
||||
return (l1,h1) if l1 != h1 else l1
|
||||
|
|
@ -477,9 +477,9 @@ class CoinInfo(object):
|
|||
w = max(len(e[0]) for e in cls.coin_constants['mainnet'])
|
||||
for line in cls.coin_constants['mainnet']:
|
||||
if reverse:
|
||||
print('{:6} {}'.format(line[1],line[0]))
|
||||
print(('{:6} {}'.format(line[1],line[0])))
|
||||
else:
|
||||
print(('','{:{}} '.format(line[0],w))[include_names] + line[1])
|
||||
print((('','{:{}} '.format(line[0],w))[include_names] + line[1]))
|
||||
|
||||
@classmethod
|
||||
def create_trust_table(cls):
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ class Token(MMGenObject): # ERC20
|
|||
if decimals is None:
|
||||
ret_hex = self.do_call('decimals()')
|
||||
try: decimals = int(ret_hex,16)
|
||||
except: raise TokenNotInBlockchain,"Token '{}' not in blockchain".format(addr)
|
||||
except: raise TokenNotInBlockchain("Token '{}' not in blockchain".format(addr))
|
||||
self.base_unit = Decimal(10) ** -decimals
|
||||
|
||||
def transferdata2amt(self,data): # online
|
||||
|
|
@ -80,7 +80,7 @@ class Token(MMGenObject): # ERC20
|
|||
return g.rpch.eth_getCode('0x'+self.addr)[2:]
|
||||
|
||||
def transfer_from(self,from_addr,to_addr,amt,key,start_gas,gasPrice):
|
||||
raise NotImplementedError,'method not implemented'
|
||||
raise NotImplementedError('method not implemented')
|
||||
return self.transfer( from_addr,to_addr,amt,key,start_gas,gasPrice,
|
||||
method_sig='transferFrom(address,address,uint256)',
|
||||
from_addr2=from_addr)
|
||||
|
|
|
|||
|
|
@ -55,11 +55,11 @@ class EthereumTrackingWallet(TrackingWallet):
|
|||
if not 'tokens' in self.data:
|
||||
self.data['tokens'] = {}
|
||||
def conv_types(ad):
|
||||
for v in ad.values():
|
||||
for v in list(ad.values()):
|
||||
v['mmid'] = TwMMGenID(v['mmid'],on_fail='raise')
|
||||
v['comment'] = TwComment(v['comment'],on_fail='raise')
|
||||
conv_types(self.data['accounts'])
|
||||
for v in self.data['tokens'].values():
|
||||
for v in list(self.data['tokens'].values()):
|
||||
conv_types(v)
|
||||
|
||||
def upgrade_wallet_maybe(self):
|
||||
|
|
@ -131,16 +131,16 @@ class EthereumTrackingWallet(TrackingWallet):
|
|||
|
||||
def sorted_list(self):
|
||||
return sorted(
|
||||
map(lambda x: {'addr':x[0],'mmid':x[1]['mmid'],'comment':x[1]['comment']},self.data_root().items()),
|
||||
[{'addr':x[0],'mmid':x[1]['mmid'],'comment':x[1]['comment']} for x in list(self.data_root().items())],
|
||||
key=lambda x: x['mmid'].sort_key+x['addr'] )
|
||||
|
||||
def mmid_ordered_dict(self):
|
||||
from collections import OrderedDict
|
||||
return OrderedDict(map(lambda x: (x['mmid'],{'addr':x['addr'],'comment':x['comment']}), self.sorted_list()))
|
||||
return OrderedDict([(x['mmid'],{'addr':x['addr'],'comment':x['comment']}) for x in self.sorted_list()])
|
||||
|
||||
@write_mode
|
||||
def set_label(self,coinaddr,lbl):
|
||||
for addr,d in self.data_root().items():
|
||||
for addr,d in list(self.data_root().items()):
|
||||
if addr == coinaddr:
|
||||
d['comment'] = lbl.comment
|
||||
self.write()
|
||||
|
|
@ -204,12 +204,12 @@ Actions: [q]uit view, [p]rint to file, pager [v]iew, [w]ide view,
|
|||
|
||||
def get_unspent_rpc(self):
|
||||
rpc_init()
|
||||
return map(lambda d: {
|
||||
return [{
|
||||
'account': TwLabel(d['mmid']+' '+d['comment'],on_fail='raise'),
|
||||
'address': d['addr'],
|
||||
'amount': self.get_addr_bal(d['addr']),
|
||||
'confirmations': 0, # TODO
|
||||
}, TrackingWallet().sorted_list())
|
||||
} for d in TrackingWallet().sorted_list()]
|
||||
|
||||
class EthereumTokenTwUnspentOutputs(EthereumTwUnspentOutputs):
|
||||
|
||||
|
|
@ -238,7 +238,7 @@ class EthereumTwAddrList(TwAddrList):
|
|||
self.total = g.proto.coin_amt('0')
|
||||
|
||||
from mmgen.obj import CoinAddr
|
||||
for mmid,d in tw.items():
|
||||
for mmid,d in list(tw.items()):
|
||||
# if d['confirmations'] < minconf: continue # cannot get confirmations for eth account
|
||||
label = TwLabel(mmid+' '+d['comment'],on_fail='raise')
|
||||
if usr_addr_list and (label.mmid not in usr_addr_list): continue
|
||||
|
|
@ -297,6 +297,6 @@ class EthereumAddrData(AddrData):
|
|||
vmsg('Getting address data from tracking wallet')
|
||||
tw = TrackingWallet().mmid_ordered_dict()
|
||||
# emulate the output of RPC 'listaccounts' and 'getaddressesbyaccount'
|
||||
return [(mmid+' '+d['comment'],[d['addr']]) for mmid,d in tw.items()]
|
||||
return [(mmid+' '+d['comment'],[d['addr']]) for mmid,d in list(tw.items())]
|
||||
|
||||
class EthereumTokenAddrData(EthereumAddrData): pass
|
||||
|
|
|
|||
|
|
@ -150,7 +150,7 @@ class EthereumMMGenTX(MMGenTX):
|
|||
o_num = len(self.outputs)
|
||||
assert o_num in o_ok,'Transaction has invalid number of outputs!'.format(o_num)
|
||||
self.make_txobj()
|
||||
self.hex = json.dumps(dict([(k,str(v))for k,v in self.txobj.items()]))
|
||||
self.hex = json.dumps(dict([(k,str(v))for k,v in list(self.txobj.items())]))
|
||||
self.update_txid()
|
||||
|
||||
def del_output(self,idx): pass
|
||||
|
|
@ -317,7 +317,7 @@ class EthereumMMGenTX(MMGenTX):
|
|||
|
||||
def is_in_mempool(self):
|
||||
# pmsg(g.rpch.parity_pendingTransactions())
|
||||
return '0x'+self.coin_txid in map(lambda x: x['hash'],g.rpch.parity_pendingTransactions())
|
||||
return '0x'+self.coin_txid in [x['hash'] for x in g.rpch.parity_pendingTransactions()]
|
||||
|
||||
def is_in_wallet(self):
|
||||
d = g.rpch.eth_getTransactionReceipt('0x'+self.coin_txid)
|
||||
|
|
@ -401,7 +401,7 @@ class EthereumTokenMMGenTX(EthereumMMGenTX):
|
|||
return True
|
||||
|
||||
def final_inputs_ok_msg(self,change_amt):
|
||||
m = u"Transaction leaves ≈{} {} and {} {} in the sender's account"
|
||||
m = "Transaction leaves ≈{} {} and {} {} in the sender's account"
|
||||
send_acct_tbal = 0 if self.outputs[0].is_chg else \
|
||||
Token(g.token).balance(self.inputs[0].addr) - self.outputs[0].amt
|
||||
return m.format(ETHAmt(change_amt).hl(),g.coin,ETHAmt(send_acct_tbal).hl(),g.dcoin)
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ for c in _colors:
|
|||
globals()['_16_'+c] = '\033[{}m'.format(e[1][0]) if e[1][1] == 0 \
|
||||
else '\033[{};{}m'.format(*e[1])
|
||||
globals()['_clr_'+c] = ''; _reset = ''
|
||||
exec 'def {c}(s): return _clr_{c}+s+_reset'.format(c=c)
|
||||
exec('def {c}(s): return _clr_{c}+s+_reset'.format(c=c))
|
||||
|
||||
def nocolor(s): return s
|
||||
|
||||
|
|
@ -85,6 +85,6 @@ def test_color():
|
|||
pass
|
||||
for desc,n in (('auto','auto'),('8-color',8),('256-color',256)):
|
||||
if n != 'auto': init_color(num_colors=n)
|
||||
print('{:9}: {}'.format(desc,' '.join([globals()[c](c) for c in sorted(_colors)])))
|
||||
print(('{:9}: {}'.format(desc,' '.join([globals()[c](c) for c in sorted(_colors)]))))
|
||||
|
||||
if __name__ == '__main__': test_color()
|
||||
|
|
|
|||
|
|
@ -89,7 +89,7 @@ a plain decimal number, or as {r}, using an integer followed by
|
|||
r=MMGenTX().rel_fee_desc,
|
||||
l=fee_spec_letters(use_quotes=True),
|
||||
u=fee_spec_names() ),
|
||||
'txsign': u"""
|
||||
'txsign': """
|
||||
Transactions may contain both {pnm} or non-{pnm} input addresses.
|
||||
|
||||
To sign non-{pnm} inputs, a {dn} wallet dump or flat key list is used
|
||||
|
|
@ -119,4 +119,4 @@ column below:
|
|||
pnm=g.proj_name,
|
||||
pnu=g.proto.name.capitalize(),
|
||||
pnl=g.proj_name.lower())
|
||||
}[k] + (u'-α' if g.debug_utf8 else '')
|
||||
}[k] + ('-α' if g.debug_utf8 else '')
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ def sha256_rounds(s,n):
|
|||
def scramble_seed(seed,scramble_key,hash_rounds):
|
||||
import hmac
|
||||
scr_seed = hmac.new(seed,scramble_key,sha256).digest()
|
||||
fs = u'Seed: {}\nScramble key: {}\nScrambled seed: {}'
|
||||
fs = 'Seed: {}\nScramble key: {}\nScrambled seed: {}'
|
||||
dmsg(fs.format(hexlify(seed),scramble_key.decode('utf8'),hexlify(scr_seed)))
|
||||
return sha256_rounds(scr_seed,hash_rounds)
|
||||
|
||||
|
|
@ -111,7 +111,7 @@ def scrypt_hash_passphrase(passwd,salt,hash_preset,buflen=32):
|
|||
# Buflen arg is for brainwallets only, which use this function to generate
|
||||
# the seed directly.
|
||||
N,r,p = get_hash_params(hash_preset)
|
||||
if type(passwd) == unicode: passwd = passwd.encode('utf8')
|
||||
if type(passwd) == str: passwd = passwd.encode('utf8')
|
||||
return scrypt.hash(passwd,salt,2**N,r,p,buflen=buflen)
|
||||
|
||||
def make_key(passwd,salt,hash_preset,desc='encryption key',from_what='passphrase',verbose=False):
|
||||
|
|
@ -142,7 +142,7 @@ def _get_random_data_from_user(uchars):
|
|||
if opt.quiet: msg_r('\r')
|
||||
else: msg_r("\rThank you. That's enough.{}\n\n".format(' '*18))
|
||||
|
||||
fmt_time_data = map('{:.22f}'.format,time_data)
|
||||
fmt_time_data = list(map('{:.22f}'.format,time_data))
|
||||
dmsg('\nUser input:\n{!r}\nKeystroke time values:\n{}\n'.format(key_data,'\n'.join(fmt_time_data)))
|
||||
prompt = 'User random data successfully acquired. Press ENTER to continue'
|
||||
prompt_and_get_char(prompt,'',enter_ok=True)
|
||||
|
|
@ -171,7 +171,7 @@ def get_hash_preset_from_user(hp=g.hash_preset,desc='data'):
|
|||
while True:
|
||||
ret = my_raw_input(prompt)
|
||||
if ret:
|
||||
if ret in g.hash_presets.keys():
|
||||
if ret in list(g.hash_presets.keys()):
|
||||
return ret
|
||||
else:
|
||||
m = 'Invalid input. Valid choices are {}'
|
||||
|
|
|
|||
|
|
@ -96,13 +96,13 @@ def find_files_in_dir(ftype,fdir,no_dups=False):
|
|||
die(3,"'{}': not a recognized file type".format(ftype))
|
||||
|
||||
try: dirlist = os.listdir(fdir)
|
||||
except: die(3,u"ERROR: unable to read directory '{}'".format(fdir))
|
||||
except: die(3,"ERROR: unable to read directory '{}'".format(fdir))
|
||||
|
||||
matches = [l for l in dirlist if l[-len(ftype.ext)-1:]=='.'+ftype.ext]
|
||||
|
||||
if no_dups:
|
||||
if len(matches) > 1:
|
||||
die(1,u"ERROR: more than one {} file in directory '{}'".format(ftype.__name__,fdir))
|
||||
die(1,"ERROR: more than one {} file in directory '{}'".format(ftype.__name__,fdir))
|
||||
return os.path.join(fdir,matches[0]) if len(matches) else None
|
||||
else:
|
||||
return [os.path.join(fdir,m) for m in matches]
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ class g(object):
|
|||
alice = False
|
||||
|
||||
# test suite:
|
||||
bogus_wallet_data = u''
|
||||
bogus_wallet_data = ''
|
||||
debug_utf8 = False
|
||||
|
||||
for k in ('win','linux'):
|
||||
|
|
@ -107,7 +107,7 @@ class g(object):
|
|||
die(2,'$HOME is not set! Unable to determine home directory')
|
||||
|
||||
data_dir_root,data_dir,cfg_file = None,None,None
|
||||
daemon_data_dir = u'' # set by user or protocol
|
||||
daemon_data_dir = '' # set by user or protocol
|
||||
|
||||
# User opt sets global var:
|
||||
common_opts = (
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ def launch(what):
|
|||
sys.exit(2)
|
||||
|
||||
import sys
|
||||
sys.argv = map(my_dec,sys.argv)
|
||||
sys.argv = list(map(my_dec,sys.argv))
|
||||
|
||||
if what in ('walletgen','walletchk','walletconv','passchg'):
|
||||
what = 'wallet'
|
||||
|
|
@ -55,15 +55,15 @@ def launch(what):
|
|||
if os.getenv('MMGEN_TRACEBACK'):
|
||||
raise
|
||||
else:
|
||||
try: m = u'{}'.format(e.message)
|
||||
try: m = '{}'.format(e.message)
|
||||
except: m = repr(e.message)
|
||||
|
||||
from mmgen.util import die,ydie,rdie
|
||||
d = [ (ydie,2,u'\nMMGen Unhandled Exception ({n}): {m}'),
|
||||
(die, 1,u'{m}'),
|
||||
(ydie,2,u'{m}'),
|
||||
(ydie,3,u'\nMMGen Error ({n}): {m}'),
|
||||
(rdie,4,u'\nMMGen Fatal Error ({n}): {m}')
|
||||
d = [ (ydie,2,'\nMMGen Unhandled Exception ({n}): {m}'),
|
||||
(die, 1,'{m}'),
|
||||
(ydie,2,'{m}'),
|
||||
(ydie,3,'\nMMGen Error ({n}): {m}'),
|
||||
(rdie,4,'\nMMGen Fatal Error ({n}): {m}')
|
||||
][e.mmcode if hasattr(e,'mmcode') else 0]
|
||||
|
||||
d[0](d[1],d[2].format(n=type(e).__name__,m=m))
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ opts_data = lambda: {
|
|||
what=gen_what,g=g,
|
||||
dmat="'{}' or '{}'".format(g.proto.dfl_mmtype,MAT.mmtypes[g.proto.dfl_mmtype]['name'])
|
||||
),
|
||||
'notes': u"""
|
||||
'notes': """
|
||||
|
||||
NOTES FOR THIS COMMAND
|
||||
|
||||
|
|
@ -111,7 +111,7 @@ FMT CODES:
|
|||
n_pw=help_notes('passwd'),
|
||||
n_bw=help_notes('brainwallet'),
|
||||
n_fmt='\n '.join(SeedSource.format_fmt_codes().splitlines()),
|
||||
n_at='\n '.join(["'{}','{:<12} - {}".format(k,v['name']+"'",v['desc']) for k,v in MAT.mmtypes.items()]),
|
||||
n_at='\n '.join(["'{}','{:<12} - {}".format(k,v['name']+"'",v['desc']) for k,v in list(MAT.mmtypes.items())]),
|
||||
o=opts
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -83,7 +83,7 @@ try:
|
|||
rpc_init()
|
||||
except UnrecognizedTokenSymbol as e:
|
||||
m = "When importing addresses for a new token, the token must be specified by address, not symbol."
|
||||
raise type(e),'{}\n{}'.format(e.message,m)
|
||||
raise type(e)('{}\n{}'.format(e.message,m))
|
||||
|
||||
if len(cmd_args) == 1:
|
||||
infile = cmd_args[0]
|
||||
|
|
@ -132,7 +132,7 @@ msg_fmt = '{{:{}}} {{:34}} {{:{}}}'.format(w_n_of_m,w_mmid)
|
|||
|
||||
if opt.rescan: import threading
|
||||
|
||||
fs = u'Importing {} address{} from {}{}'
|
||||
fs = 'Importing {} address{} from {}{}'
|
||||
bm =' (batch mode)' if opt.batch else ''
|
||||
msg(fs.format(len(al.data),suf(al.data,'es'),infile,bm))
|
||||
|
||||
|
|
|
|||
|
|
@ -23,11 +23,11 @@ mmgen-autosign: Auto-sign MMGen transactions
|
|||
import sys,os,subprocess,time,signal,shutil
|
||||
from stat import *
|
||||
|
||||
mountpoint = u'/mnt/tx'
|
||||
tx_dir = u'/mnt/tx/tx'
|
||||
part_label = u'MMGEN_TX'
|
||||
wallet_dir = u'/dev/shm/autosign'
|
||||
key_fn = u'autosign.key'
|
||||
mountpoint = '/mnt/tx'
|
||||
tx_dir = '/mnt/tx/tx'
|
||||
part_label = 'MMGEN_TX'
|
||||
wallet_dir = '/dev/shm/autosign'
|
||||
key_fn = 'autosign.key'
|
||||
|
||||
from mmgen.common import *
|
||||
prog_name = os.path.basename(sys.argv[0])
|
||||
|
|
@ -136,7 +136,7 @@ def get_wallet_files():
|
|||
try: dlist = os.listdir(wallet_dir)
|
||||
except: die(1,m.format(wallet_dir))
|
||||
|
||||
wfs = filter(lambda x: x[-6:] == '.mmdat',dlist)
|
||||
wfs = [x for x in dlist if x[-6:] == '.mmdat']
|
||||
if not wfs:
|
||||
die(1,'No wallet files present!')
|
||||
return [os.path.join(wallet_dir,w) for w in wfs]
|
||||
|
|
@ -196,7 +196,7 @@ def sign_tx_file(txfile):
|
|||
else:
|
||||
return False
|
||||
except Exception as e:
|
||||
msg(u'An error occurred: {}'.format(e.message))
|
||||
msg('An error occurred: {}'.format(e.message))
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
|
@ -231,7 +231,7 @@ def decrypt_wallets():
|
|||
opt.passwd_file = os.path.join(tx_dir,key_fn)
|
||||
# opt.passwd_file = '/tmp/key'
|
||||
from mmgen.seed import SeedSource
|
||||
msg(u"Unlocking wallet{} with key from '{}'".format(suf(wfs),opt.passwd_file))
|
||||
msg("Unlocking wallet{} with key from '{}'".format(suf(wfs),opt.passwd_file))
|
||||
fails = 0
|
||||
for wf in wfs:
|
||||
try:
|
||||
|
|
@ -263,18 +263,18 @@ def wipe_existing_key():
|
|||
try: os.stat(fn)
|
||||
except: pass
|
||||
else:
|
||||
msg(u'\nWiping existing key {}'.format(fn))
|
||||
msg('\nWiping existing key {}'.format(fn))
|
||||
subprocess.call(['wipe','-cf',fn])
|
||||
|
||||
def create_key():
|
||||
from binascii import hexlify
|
||||
kdata = hexlify(os.urandom(32))
|
||||
fn = os.path.join(tx_dir,key_fn)
|
||||
desc = u'key file {}'.format(fn)
|
||||
desc = 'key file {}'.format(fn)
|
||||
msg('Creating ' + desc)
|
||||
try:
|
||||
with open(fn,'w') as f: f.write(kdata+'\n')
|
||||
os.chmod(fn,0400)
|
||||
os.chmod(fn,0o400)
|
||||
msg('Wrote ' + desc)
|
||||
except:
|
||||
die(2,'Unable to write ' + desc)
|
||||
|
|
@ -349,7 +349,7 @@ def set_led(cmd):
|
|||
|
||||
def get_insert_status():
|
||||
if os.getenv('MMGEN_TEST_SUITE'): return True
|
||||
try: os.stat(os.path.join(u'/dev/disk/by-label',part_label))
|
||||
try: os.stat(os.path.join('/dev/disk/by-label',part_label))
|
||||
except: return False
|
||||
else: return True
|
||||
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ opts_data = lambda: {
|
|||
g=g,pnm=g.proj_name,d58=dfl_len['b58'],d32=dfl_len['b32'],dhex=dfl_len['hex'],
|
||||
kgs=' '.join(['{}:{}'.format(n,k) for n,k in enumerate(g.key_generators,1)])
|
||||
),
|
||||
'notes': u"""
|
||||
'notes': """
|
||||
|
||||
NOTES FOR THIS COMMAND
|
||||
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ if not opt.status: do_license_msg()
|
|||
from mmgen.tx import *
|
||||
|
||||
tx = MMGenTX(infile,silent_open=True) # sig check performed here
|
||||
vmsg(u"Signed transaction file '{}' is valid".format(infile))
|
||||
vmsg("Signed transaction file '{}' is valid".format(infile))
|
||||
|
||||
if not tx.marked_signed():
|
||||
die(1,'Transaction is not signed!')
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ for tx_num,tx_file in enumerate(tx_files,1):
|
|||
if tx.marked_signed():
|
||||
msg('Transaction is already signed!'); continue
|
||||
|
||||
vmsg(u"Successfully opened transaction file '{}'".format(tx_file))
|
||||
vmsg("Successfully opened transaction file '{}'".format(tx_file))
|
||||
|
||||
if opt.tx_id:
|
||||
msg(tx.txid); continue
|
||||
|
|
|
|||
|
|
@ -95,16 +95,16 @@ opts_data = lambda: {
|
|||
iaction=capfirst(iaction),
|
||||
oaction=capfirst(oaction),
|
||||
),
|
||||
'notes': u"""
|
||||
'notes': """
|
||||
|
||||
{n_pw}{n_bw}
|
||||
|
||||
FMT CODES:
|
||||
{f}
|
||||
""".format(
|
||||
f=u'\n '.join(SeedSource.format_fmt_codes().splitlines()),
|
||||
f='\n '.join(SeedSource.format_fmt_codes().splitlines()),
|
||||
n_pw=help_notes('passwd'),
|
||||
n_bw=(u'','\n\n' + help_notes('brainwallet'))[bw_note]
|
||||
n_bw=('','\n\n' + help_notes('brainwallet'))[bw_note]
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -125,7 +125,7 @@ if invoked_as in ('conv','passchg'):
|
|||
ss_in = None if invoked_as == 'gen' else SeedSource(sf,passchg=(invoked_as=='passchg'))
|
||||
if invoked_as == 'chk':
|
||||
lbl = ss_in.ssdata.label.hl() if hasattr(ss_in.ssdata,'label') else 'NONE'
|
||||
vmsg(u'Wallet label: {}'.format(lbl))
|
||||
vmsg('Wallet label: {}'.format(lbl))
|
||||
# TODO: display creation date
|
||||
sys.exit(0)
|
||||
|
||||
|
|
|
|||
70
mmgen/obj.py
70
mmgen/obj.py
|
|
@ -49,10 +49,10 @@ def truncate_str(s,width): # width = screen width
|
|||
class MMGenObject(object):
|
||||
|
||||
# Pretty-print any object subclassed from MMGenObject, recursing into sub-objects - WIP
|
||||
def pmsg(self): print(self.pformat())
|
||||
def pdie(self): print(self.pformat()); sys.exit(0)
|
||||
def pmsg(self): print((self.pformat()))
|
||||
def pdie(self): print((self.pformat())); sys.exit(0)
|
||||
def pformat(self,lvl=0):
|
||||
scalars = (str,unicode,int,float,Decimal)
|
||||
scalars = (str,str,int,float,Decimal)
|
||||
def do_list(out,e,lvl=0,is_dict=False):
|
||||
out.append('\n')
|
||||
for i in e:
|
||||
|
|
@ -63,16 +63,16 @@ class MMGenObject(object):
|
|||
out.append('{:>{l}}{}'.format('',el.pformat(lvl=lvl+1),l=(lvl+1)*8))
|
||||
elif type(el) in scalars:
|
||||
if isList(e):
|
||||
out.append(u'{:>{l}}{:16}\n'.format('',repr(el),l=lvl*8))
|
||||
out.append('{:>{l}}{:16}\n'.format('',repr(el),l=lvl*8))
|
||||
else:
|
||||
out.append(u' {}'.format(repr(el)))
|
||||
out.append(' {}'.format(repr(el)))
|
||||
elif isList(el) or isDict(el):
|
||||
indent = 1 if is_dict else lvl*8+4
|
||||
out.append(u'{:>{l}}{:16}'.format('','<'+type(el).__name__+'>',l=indent))
|
||||
out.append('{:>{l}}{:16}'.format('','<'+type(el).__name__+'>',l=indent))
|
||||
if isList(el) and type(el[0]) in scalars: out.append('\n')
|
||||
do_list(out,el,lvl=lvl+1,is_dict=isDict(el))
|
||||
else:
|
||||
out.append(u'{:>{l}}{:16} {}\n'.format('','<'+type(el).__name__+'>',repr(el),l=(lvl*8)+8))
|
||||
out.append('{:>{l}}{:16} {}\n'.format('','<'+type(el).__name__+'>',repr(el),l=(lvl*8)+8))
|
||||
out.append('\n')
|
||||
if not e: out.append('{}\n'.format(repr(e)))
|
||||
|
||||
|
|
@ -90,7 +90,7 @@ class MMGenObject(object):
|
|||
# print self.__dict__.keys()
|
||||
# print self.keys()
|
||||
|
||||
out = [u'<{}>{}\n'.format(type(self).__name__,' '+repr(self) if isScalar(self) else '')]
|
||||
out = ['<{}>{}\n'.format(type(self).__name__,' '+repr(self) if isScalar(self) else '')]
|
||||
if isList(self) or isDict(self):
|
||||
do_list(out,self,lvl=lvl,is_dict=isDict(self))
|
||||
|
||||
|
|
@ -100,12 +100,12 @@ class MMGenObject(object):
|
|||
if k in ('_OrderedDict__root','_OrderedDict__map'): continue # exclude these because of recursion
|
||||
e = getattr(self,k)
|
||||
if isList(e) or isDict(e):
|
||||
out.append(u'{:>{l}}{:<10} {:16}'.format('',k,'<'+type(e).__name__+'>',l=(lvl*8)+4))
|
||||
out.append('{:>{l}}{:<10} {:16}'.format('',k,'<'+type(e).__name__+'>',l=(lvl*8)+4))
|
||||
do_list(out,e,lvl=lvl,is_dict=isDict(e))
|
||||
elif hasattr(e,'pformat') and type(e) != type:
|
||||
out.append(u'{:>{l}}{:10} {}'.format('',k,e.pformat(lvl=lvl+1),l=(lvl*8)+4))
|
||||
out.append('{:>{l}}{:10} {}'.format('',k,e.pformat(lvl=lvl+1),l=(lvl*8)+4))
|
||||
else:
|
||||
out.append(u'{:>{l}}{:<10} {:16} {}\n'.format(
|
||||
out.append('{:>{l}}{:<10} {:16} {}\n'.format(
|
||||
'',k,'<'+type(e).__name__+'>',repr(e),l=(lvl*8)+4))
|
||||
|
||||
import re
|
||||
|
|
@ -126,7 +126,7 @@ class InitErrors(object):
|
|||
if os.getenv('MMGEN_TRACEBACK'): on_fail == 'raise'
|
||||
from mmgen.util import die,msg
|
||||
if on_fail == 'silent': return None # TODO: return False instead?
|
||||
elif on_fail == 'raise': raise ValueError,m
|
||||
elif on_fail == 'raise': raise ValueError(m)
|
||||
elif on_fail == 'die': die(1,m)
|
||||
elif on_fail == 'return':
|
||||
if m: msg(m)
|
||||
|
|
@ -144,7 +144,7 @@ class Hilite(object):
|
|||
# 'append_chars' and 'encl' must consist of single-width chars only
|
||||
def fmtc(cls,s,width=None,color=False,encl='',trunc_ok=None,
|
||||
center=False,nullrepl='',append_chars='',append_color=False):
|
||||
s = unicode(s)
|
||||
s = str(s)
|
||||
s_wide_count = len([1 for ch in s if unicodedata.east_asian_width(ch) in ('F','W')])
|
||||
assert type(encl) is str and len(encl) in (0,2),"'encl' must be 2-character str"
|
||||
a,b = list(encl) if encl else ('','')
|
||||
|
|
@ -248,7 +248,7 @@ class MMGenListItem(MMGenObject):
|
|||
|
||||
def __init__(self,*args,**kwargs):
|
||||
if args:
|
||||
raise ValueError, 'Non-keyword args not allowed'
|
||||
raise ValueError('Non-keyword args not allowed')
|
||||
for k in kwargs:
|
||||
if kwargs[k] != None:
|
||||
setattr(self,k,kwargs[k])
|
||||
|
|
@ -299,7 +299,7 @@ class AddrIdxList(list,InitErrors,MMGenObject):
|
|||
else: break
|
||||
else:
|
||||
return list.__init__(self,sorted(set(ret))) # fell off end of loop - success
|
||||
raise ValueError,"{!r}: invalid range".format(i)
|
||||
raise ValueError("{!r}: invalid range".format(i))
|
||||
except Exception as e:
|
||||
m = "{!r}: value cannot be converted to AddrIdxList ({})"
|
||||
return type(self).init_fail(m.format(idx_list or fmt_str,e.message),on_fail)
|
||||
|
|
@ -314,7 +314,7 @@ class BTCAmt(Decimal,Hilite,InitErrors):
|
|||
min_coin_unit = satoshi
|
||||
amt_fs = '4.8'
|
||||
units = ('satoshi',)
|
||||
forbidden_types = (float,long)
|
||||
forbidden_types = (float,int)
|
||||
|
||||
def __new__(cls,num,from_unit=None,on_fail='die'):
|
||||
if type(num) == cls: return num
|
||||
|
|
@ -323,7 +323,7 @@ class BTCAmt(Decimal,Hilite,InitErrors):
|
|||
if from_unit:
|
||||
assert from_unit in cls.units,(
|
||||
"'{}': unrecognized denomination for {}".format(from_unit,cls.__name__))
|
||||
assert type(num) in (int,long),'value is not an integer or long integer'
|
||||
assert type(num) in (int,int),'value is not an integer or long integer'
|
||||
me = Decimal.__new__(cls,num * getattr(cls,from_unit))
|
||||
else:
|
||||
for t in cls.forbidden_types:
|
||||
|
|
@ -355,7 +355,7 @@ class BTCAmt(Decimal,Hilite,InitErrors):
|
|||
if fs == None: fs = self.amt_fs
|
||||
s = str(int(self)) if int(self) == self else self.normalize().__format__('f')
|
||||
if '.' in fs:
|
||||
p1,p2 = map(int,fs.split('.',1))
|
||||
p1,p2 = list(map(int,fs.split('.',1)))
|
||||
ss = s.split('.',1)
|
||||
if len(ss) == 2:
|
||||
a,b = ss
|
||||
|
|
@ -463,7 +463,7 @@ class ViewKey(object):
|
|||
elif g.proto.name == 'monero':
|
||||
return MoneroViewKey.__new__(MoneroViewKey,s,on_fail)
|
||||
else:
|
||||
raise ValueError,'{}: protocol does not support view keys'.format(g.proto.name.capitalize())
|
||||
raise ValueError('{}: protocol does not support view keys'.format(g.proto.name.capitalize()))
|
||||
|
||||
class ZcashViewKey(CoinAddr): hex_width = 128
|
||||
|
||||
|
|
@ -484,7 +484,7 @@ class SeedID(str,Hilite,InitErrors):
|
|||
assert set(sid) <= set(hexdigits.upper()),'not uppercase hex digits'
|
||||
assert len(sid) == cls.width,'not {} characters wide'.format(cls.width)
|
||||
return str.__new__(cls,sid)
|
||||
raise ValueError,'no arguments provided'
|
||||
raise ValueError('no arguments provided')
|
||||
except Exception as e:
|
||||
m = "{!r}: value cannot be converted to SeedID ({})"
|
||||
return cls.init_fail(m.format(seed or sid,e.message),on_fail)
|
||||
|
|
@ -542,7 +542,7 @@ class TwMMGenID(str,Hilite,InitErrors,MMGenObject):
|
|||
return me
|
||||
|
||||
# contains TwMMGenID,TwComment. Not for display
|
||||
class TwLabel(unicode,InitErrors,MMGenObject):
|
||||
class TwLabel(str,InitErrors,MMGenObject):
|
||||
def __new__(cls,s,on_fail='die'):
|
||||
if type(s) == cls: return s
|
||||
cls.arg_chk(cls,on_fail)
|
||||
|
|
@ -550,12 +550,12 @@ class TwLabel(unicode,InitErrors,MMGenObject):
|
|||
ss = s.split(None,1)
|
||||
mmid = TwMMGenID(ss[0],on_fail='raise')
|
||||
comment = TwComment(ss[1] if len(ss) == 2 else '',on_fail='raise')
|
||||
me = unicode.__new__(cls,u'{}{}'.format(mmid,u' {}'.format(comment) if comment else ''))
|
||||
me = str.__new__(cls,'{}{}'.format(mmid,' {}'.format(comment) if comment else ''))
|
||||
me.mmid = mmid
|
||||
me.comment = comment
|
||||
return me
|
||||
except Exception as e:
|
||||
m = u"{}\n{!r}: value cannot be converted to TwLabel"
|
||||
m = "{}\n{!r}: value cannot be converted to TwLabel"
|
||||
return cls.init_fail(m.format(e.message,s),on_fail)
|
||||
|
||||
class HexStr(str,Hilite,InitErrors):
|
||||
|
|
@ -566,7 +566,7 @@ class HexStr(str,Hilite,InitErrors):
|
|||
assert case in ('upper','lower')
|
||||
cls.arg_chk(cls,on_fail)
|
||||
try:
|
||||
assert type(s) in (str,unicode,bytes),'not a string'
|
||||
assert type(s) in (str,str,bytes),'not a string'
|
||||
assert set(s) <= set(getattr(hexdigits,case)()),'not {}case hexadecimal symbols'.format(case)
|
||||
assert not len(s) % 2,'odd-length string'
|
||||
return str.__new__(cls,s)
|
||||
|
|
@ -689,7 +689,7 @@ class AddrListID(str,Hilite,InitErrors,MMGenObject):
|
|||
m = "Cannot create AddrListID ({})".format(e.message)
|
||||
return cls.init_fail(m,on_fail)
|
||||
|
||||
class MMGenLabel(unicode,Hilite,InitErrors):
|
||||
class MMGenLabel(str,Hilite,InitErrors):
|
||||
color = 'pink'
|
||||
allowed = []
|
||||
forbidden = []
|
||||
|
|
@ -701,10 +701,10 @@ class MMGenLabel(unicode,Hilite,InitErrors):
|
|||
cls.arg_chk(cls,on_fail)
|
||||
for k in cls.forbidden,cls.allowed:
|
||||
assert type(k) == list
|
||||
for ch in k: assert type(ch) == unicode and len(ch) == 1
|
||||
for ch in k: assert type(ch) == str and len(ch) == 1
|
||||
try:
|
||||
s = s.strip()
|
||||
if type(s) != unicode:
|
||||
if type(s) != str:
|
||||
s = s.decode('utf8')
|
||||
for ch in s:
|
||||
# Allow: (L)etter,(N)umber,(P)unctuation,(S)ymbol,(Z)space
|
||||
|
|
@ -715,12 +715,12 @@ class MMGenLabel(unicode,Hilite,InitErrors):
|
|||
assert len(s) <= cls.max_len, 'too long (>{} symbols)'.format(cls.max_len)
|
||||
assert len(s) >= cls.min_len, 'too short (<{} symbols)'.format(cls.min_len)
|
||||
assert not cls.allowed or set(list(s)).issubset(set(cls.allowed)),\
|
||||
u'contains non-allowed symbols: {}'.format(' '.join(set(list(s)) - set(cls.allowed)))
|
||||
'contains non-allowed symbols: {}'.format(' '.join(set(list(s)) - set(cls.allowed)))
|
||||
assert not cls.forbidden or not any(ch in s for ch in cls.forbidden),\
|
||||
u"contains one of these forbidden symbols: '{}'".format("', '".join(cls.forbidden))
|
||||
return unicode.__new__(cls,s)
|
||||
"contains one of these forbidden symbols: '{}'".format("', '".join(cls.forbidden))
|
||||
return str.__new__(cls,s)
|
||||
except Exception as e:
|
||||
m = u"{!r}: value cannot be converted to {} ({})"
|
||||
m = "{!r}: value cannot be converted to {} ({})"
|
||||
return cls.init_fail(m.format(s,cls.__name__,e.message),on_fail)
|
||||
|
||||
class MMGenWalletLabel(MMGenLabel):
|
||||
|
|
@ -739,7 +739,7 @@ class MMGenPWIDString(MMGenLabel):
|
|||
max_len = 256
|
||||
min_len = 1
|
||||
desc = 'password ID string'
|
||||
forbidden = list(u' :/\\')
|
||||
forbidden = list(' :/\\')
|
||||
|
||||
class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
|
||||
width = 1
|
||||
|
|
@ -799,7 +799,7 @@ class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
|
|||
cls.arg_chk(cls,on_fail)
|
||||
from mmgen.globalvars import g
|
||||
try:
|
||||
for k,v in cls.mmtypes.items():
|
||||
for k,v in list(cls.mmtypes.items()):
|
||||
if s in (k,v['name']):
|
||||
if s == v['name']: s = k
|
||||
me = str.__new__(cls,s)
|
||||
|
|
@ -810,7 +810,7 @@ class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
|
|||
me.extra_attrs = v['extra_attrs'] if 'extra_attrs' in v else ()
|
||||
me.wif_label = v['wif_label'] if 'wif_label' in v else 'wif:'
|
||||
return me
|
||||
raise ValueError,'not found'
|
||||
raise ValueError('not found')
|
||||
except Exception as e:
|
||||
m = '{}{!r}: invalid value for {} ({})'.format(
|
||||
('{!r}\n'.format(errmsg) if errmsg else ''),s,cls.__name__,e.message)
|
||||
|
|
@ -818,7 +818,7 @@ class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
|
|||
|
||||
@classmethod
|
||||
def get_names(cls):
|
||||
return [v['name'] for v in cls.mmtypes.values()]
|
||||
return [v['name'] for v in list(cls.mmtypes.values())]
|
||||
|
||||
class MMGenPasswordType(MMGenAddrType):
|
||||
mmtypes = {
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue