Example #1
0
    def verify_addr(cls, addr, hex_width, return_dict=False):

        if 'B' in cls.mmtypes and addr[:len(cls.bech32_hrp)] == cls.bech32_hrp:
            ret = bech32.decode(cls.bech32_hrp, addr)
            if ret[0] != cls.witness_vernum:
                msg('{}: Invalid witness version number'.format(ret[0]))
            elif ret[1]:
                return {
                    'hex': bytes(ret[1]).hex(),
                    'format': 'bech32'
                } if return_dict else True
            return False

        for addr_fmt in cls.addr_ver_num:
            ver_num, pfx = cls.addr_ver_num[addr_fmt]
            if type(pfx) == tuple:
                if addr[0] not in pfx: continue
            elif addr[:len(pfx)] != pfx: continue
            addr_hex = _b58chk_decode(addr)
            if addr_hex[:len(ver_num)] != ver_num: continue
            return {
                'hex': addr_hex[len(ver_num):],
                'format': {
                    'p2pkh': 'p2pkh',
                    'p2sh': 'p2sh',
                    'p2sh2': 'p2sh',
                    'zcash_z': 'zcash_z',
                    'viewkey': 'viewkey'
                }[addr_fmt]
            } if return_dict else True

        return False
Example #2
0
 def opt_is_in_list(val, lst, desc):
     if val not in lst:
         q, sep = (('', ','), ("'", "','"))[type(lst[0]) == str]
         msg('{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format(
             v=val, w=desc, q=q, o=sep.join([str(i) for i in sorted(lst)])))
         return False
     return True
Example #3
0
	def verify_addr(cls,addr,hex_width,return_dict=False):

		if 'B' in cls.mmtypes and addr[:len(cls.bech32_hrp)] == cls.bech32_hrp:
			ret = bech32.decode(cls.bech32_hrp,addr)
			if ret[0] != cls.witness_vernum:
				msg('{}: Invalid witness version number'.format(ret[0]))
			elif ret[1]:
				return {
					'hex': bytes(ret[1]).hex(),
					'format': 'bech32'
				} if return_dict else True
			return False

		for addr_fmt in cls.addr_ver_num:
			ver_num,pfx = cls.addr_ver_num[addr_fmt]
			if type(pfx) == tuple:
				if addr[0] not in pfx: continue
			elif addr[:len(pfx)] != pfx: continue
			addr_hex = _b58chk_decode(addr)
			if addr_hex[:len(ver_num)] != ver_num: continue
			return {
				'hex': addr_hex[len(ver_num):],
				'format': { 'p2pkh':'p2pkh',
							'p2sh':'p2sh',
							'p2sh2':'p2sh',
							'zcash_z':'zcash_z',
							'viewkey':'viewkey'}[addr_fmt]
			} if return_dict else True

		return False
Example #4
0
def cleandir(d):
	try:    files = os.listdir(d)
	except: return

	msg(green("Cleaning directory '%s'" % d))
	for f in files:
		os.unlink(os.path.join(d,f))
Example #5
0
 def do_call(self, method_sig, method_args='', toUnit=False):
     data = create_method_id(method_sig) + method_args
     if g.debug:
         msg('ETH_CALL {}:  {}'.format(method_sig,
                                       '\n  '.join(parse_abi(data))))
     ret = g.rpch.eth_call({'to': '0x' + self.addr, 'data': '0x' + data})
     return int(ret, 16) * self.base_unit if toUnit else ret
Example #6
0
def get_data_from_config_file():
    from mmgen.util import msg, die, check_or_create_dir
    check_or_create_dir(g.data_dir_root)  # dies on error

    # https://wiki.debian.org/Python:
    #   Debian (Ubuntu) sys.prefix is '/usr' rather than '/usr/local, so add 'local'
    # TODO - test for Windows
    # This must match the configuration in setup.py
    data = u''
    try:
        with open(g.cfg_file, 'rb') as f:
            data = f.read().decode('utf8')
    except:
        cfg_template = os.path.join(
            *([sys.prefix] +
              (['share'], ['local', 'share'])[g.platform == 'linux'] +
              [g.proj_name.lower(),
               os.path.basename(g.cfg_file)]))
        try:
            with open(cfg_template, 'rb') as f:
                template_data = f.read()
        except:
            msg("WARNING: configuration template not found at '{}'".format(
                cfg_template))
        else:
            try:
                with open(g.cfg_file, 'wb') as f:
                    f.write(template_data)
                os.chmod(g.cfg_file, 0600)
            except:
                die(
                    2, "ERROR: unable to write to datadir '{}'".format(
                        g.data_dir))
    return data
Example #7
0
 def opt_is_int(val, desc):
     try:
         int(val)
     except:
         msg("'%s': invalid %s (not an integer)" % (val, desc))
         return False
     return True
Example #8
0
File: opts.py Project: mmgen/mmgen
	def opt_is_in_list(val,lst,desc):
		if val not in lst:
			q,sep = (('',','),("'","','"))[type(lst[0]) == str]
			fs = '{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'
			msg(fs.format(v=val,w=desc,q=q,o=sep.join(map(str,sorted(lst)))))
			return False
		return True
Example #9
0
    def init_fail(cls, e, m, e2=None, m2=None, objname=None, preformat=False):

        if preformat:
            errmsg = m
        else:
            fs = "{!r}: value cannot be converted to {} {}({})"
            e2_fmt = '({}) '.format(e2.args[0]) if e2 else ''
            errmsg = fs.format(m, objname or cls.__name__, e2_fmt, e.args[0])

        if m2: errmsg = '{!r}\n{}'.format(m2, errmsg)

        from mmgen.globalvars import g
        from mmgen.util import die, msg
        if cls.on_fail == 'silent':
            return None  # TODO: return False instead?
        elif cls.on_fail == 'return':
            if errmsg: msg(errmsg)
            return None  # TODO: return False instead?
        elif g.traceback or cls.on_fail == 'raise':
            if hasattr(cls, 'exc'):
                raise cls.exc(errmsg)
            else:
                raise
        elif cls.on_fail == 'die':
            die(1, errmsg)
Example #10
0
    def __init__(self, args, no_output=False):

        if opt.direct_exec:
            msg('')
            from subprocess import call, check_output
            f = (call, check_output)[bool(no_output)]
            ret = f([args[0]] + args[1:])
            if f == call and ret != 0:
                die(
                    1,
                    red('ERROR: process returned a non-zero exit status ({})'.
                        format(ret)))
        else:
            if opt.pexpect_spawn:
                self.p = pexpect.spawn(args[0], args[1:], encoding='utf8')
                self.p.delaybeforesend = 0
            else:
                self.p = PopenSpawn(args, encoding='utf8')
#				self.p.delaybeforesend = 0 # TODO: try this here too

            if opt.exact_output: self.p.logfile = sys.stdout

        self.req_exit_val = 0
        self.skip_ok = False
        self.timeout = int(opt.pexpect_timeout or 0) or (60, 5)[bool(
            opt.debug_pexpect)]
        self.sent_value = None
Example #11
0
 def opt_is_int(val, desc):
     try:
         int(val)
     except:
         msg("'{}': invalid {} (not an integer)".format(val, desc))
         return False
     return True
Example #12
0
    def __init__(self, args, no_output=False):

        if opt.direct_exec:
            msg('')
            from subprocess import run, DEVNULL
            run([args[0]] + args[1:],
                check=True,
                stdout=DEVNULL if no_output else None)
        else:
            timeout = int(opt.pexpect_timeout or 0) or (60, 5)[bool(
                opt.debug_pexpect)]
            if opt.pexpect_spawn:
                self.p = pexpect.spawn(args[0],
                                       args[1:],
                                       encoding='utf8',
                                       timeout=timeout)
                self.p.delaybeforesend = 0
            else:
                self.p = PopenSpawn(args, encoding='utf8', timeout=timeout)
#				self.p.delaybeforesend = 0 # TODO: try this here too

            if opt.exact_output: self.p.logfile = sys.stdout

        self.req_exit_val = 0
        self.skip_ok = False
        self.sent_value = None
Example #13
0
def ok_or_die(val,chk_func,s,skip_ok=False):
	try: ret = chk_func(val)
	except: ret = False
	if ret:
		if not skip_ok: ok()
	else:
		msg(red("Returned value '%s' is not a %s" % (val,s)))
		sys.exit(3)
Example #14
0
File: opts.py Project: mmgen/mmgen
	def opt_compares(val,op_str,target,desc,what=''):
		import operator as o
		op_f = { '<':o.lt, '<=':o.le, '>':o.gt, '>=':o.ge, '=':o.eq }[op_str]
		if what: what += ' '
		if not op_f(val,target):
			msg('{}: invalid {} ({}not {} {})'.format(val,desc,what,op_str,target))
			return False
		return True
Example #15
0
 async def get_decimals(self):
     ret = await self.do_call('decimals()')
     try:
         assert ret[:2] == '0x'
         return int(ret, 16)
     except:
         msg("RPC call to decimals() failed (returned '{}')".format(ret))
         return None
Example #16
0
 def opt_is_float(val, desc):
     try:
         float(val)
     except:
         msg("'{}': invalid {} (not a floating-point number)".format(
             val, desc))
         return False
     return True
Example #17
0
	def opt_compares(val,op_str,target,desc,what=''):
		import operator as o
		op_f = { '<':o.lt, '<=':o.le, '>':o.gt, '>=':o.ge, '=':o.eq }[op_str]
		if what: what += ' '
		if not op_f(val,target):
			msg('{}: invalid {} ({}not {} {})'.format(val,desc,what,op_str,target))
			return False
		return True
Example #18
0
	def opt_is_in_list(val,lst,desc):
		if val not in lst:
			q,sep = ("'","','") if type(lst[0]) == str else ("",",")
			msg("{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}".format(
					v=val,w=desc,q=q,
					o=sep.join([str(i) for i in sorted(lst)])
				))
			return False
		return True
Example #19
0
 def init_fail(m, on_fail):
     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 == 'die': die(1, m)
     elif on_fail == 'return':
         if m: msg(m)
         return None  # TODO: here too?
Example #20
0
File: opts.py Project: mmgen/mmgen
	def opt_splits(val,sep,n,desc):
		sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else "'{}'".format(sep)
		try: l = val.split(sep)
		except:
			msg("'{}': invalid {} (not {}-separated list)".format(val,desc,sepword))
			return False

		if len(l) == n: return True
		else:
			msg("'{}': invalid {} ({} {}-separated items required)".format(val,desc,n,sepword))
			return False
Example #21
0
	def opt_splits(val,sep,n,desc):
		sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else "'{}'".format(sep)
		try: l = val.split(sep)
		except:
			msg("'{}': invalid {} (not {}-separated list)".format(val,desc,sepword))
			return False

		if len(l) == n: return True
		else:
			msg("'{}': invalid {} ({} {}-separated items required)".format(val,desc,n,sepword))
			return False
Example #22
0
	def init_fail(m,on_fail,silent=False):
		from mmgen.util import die,msg
		if silent: m = ''
		if os.getenv('MMGEN_TRACEBACK'):
			raise ValueError,m
		elif on_fail == 'die': die(1,m)
		elif on_fail == 'return':
			if m: msg(m)
			return None # TODO: change to False
		elif on_fail == 'silent': return None # same here
		elif on_fail == 'raise':  raise ValueError,m
Example #23
0
 def init_fail(m, on_fail, silent=False):
     if silent: m = ''
     from mmgen.util import die, msg
     if on_fail == 'die': die(1, m)
     elif on_fail == 'return':
         if m: msg(m)
         return None  # TODO: change to False
     elif on_fail == 'silent':
         return None  # same here
     elif on_fail == 'raise':
         raise ValueError, m
Example #24
0
 def decimals(self):
     if self._decimals == None:
         res = self.do_call('decimals()')
         try:
             assert res[:2] == '0x'
             self._decimals = int(res[2:], 16)
         except:
             msg("RPC call to decimals() failed (returned '{}')".format(
                 res))
             return None
     return self._decimals
Example #25
0
def start_mscolor():
	import sys
	from mmgen.globalvars import g
	try:
		import colorama
		colorama.init(strip=True,convert=True)
	except:
		from mmgen.util import msg
		msg('Import of colorama module failed')
	else:
		g.stdout = sys.stdout
		g.stderr = sys.stderr
Example #26
0
def opt_is_tx_fee(val,desc):
	from mmgen.tx import MMGenTX
	ret = MMGenTX().convert_fee_spec(val,224,on_fail='return')
	if ret == False:
		msg("'{}': invalid {} (not a {} amount or satoshis-per-byte specification)".format(
				val,desc,g.coin.upper()))
	elif ret != None and ret > g.proto.max_tx_fee:
		msg("'{}': invalid {} (> max_tx_fee ({} {}))".format(
				val,desc,g.proto.max_tx_fee,g.coin.upper()))
	else:
		return True
	return False
Example #27
0
	def opt_splits(val,sep,n,desc):
		sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else "'%s'" % sep
		try: l = val.split(sep)
		except:
			msg("'%s': invalid %s (not %s-separated list)" % (val,desc,sepword))
			return False

		if len(l) == n: return True
		else:
			msg("'%s': invalid %s (%s %s-separated items required)" %
					(val,desc,n,sepword))
			return False
Example #28
0
def opt_is_tx_fee(val, desc):
    from mmgen.tx import MMGenTX
    ret = MMGenTX().convert_fee_spec(val, 224, on_fail='return')
    if ret == False:
        msg("'{}': invalid {} (not a {} amount or satoshis-per-byte specification)"
            .format(val, desc, g.coin.upper()))
    elif ret != None and ret > g.proto.max_tx_fee:
        msg("'{}': invalid {} (> max_tx_fee ({} {}))".format(
            val, desc, g.proto.max_tx_fee, g.coin.upper()))
    else:
        return True
    return False
Example #29
0
File: opts.py Project: mmgen/mmgen
def get_cfg_template_data():
	# https://wiki.debian.org/Python:
	#   Debian (Ubuntu) sys.prefix is '/usr' rather than '/usr/local, so add 'local'
	# TODO - test for Windows
	# This must match the configuration in setup.py
	cfg_template = os.path.join(*([sys.prefix]
				+ (['share'],['local','share'])[g.platform=='linux']
				+ [g.proj_name.lower(),os.path.basename(g.cfg_file)]))
	try:
		return open(cfg_template).read()
	except:
		msg("WARNING: configuration template not found at '{}'".format(cfg_template))
		return ''
Example #30
0
def warn_altcoins(trust_level):
	if trust_level == None: return
	tl = (red('COMPLETELY UNTESTED'),red('LOW'),yellow('MEDIUM'),green('HIGH'))
	m = """
Support for coin '{}' is EXPERIMENTAL.  The {pn} project assumes no
responsibility for any loss of funds you may incur.
This coin's {pn} testing status: {}
Are you sure you want to continue?
""".strip().format(g.coin,tl[trust_level],pn=g.proj_name)
	if os.getenv('MMGEN_TEST_SUITE'):
		msg(m); return
	if not keypress_confirm(m,default_yes=True):
		sys.exit(0)
Example #31
0
	def opt_splits(val,sep,n,desc):
		sepword = "comma" if sep == "," else (
					"colon" if sep == ":" else ("'"+sep+"'"))
		try: l = val.split(sep)
		except:
			msg("'%s': invalid %s (not %s-separated list)" % (val,desc,sepword))
			return False

		if len(l) == n: return True
		else:
			msg("'%s': invalid %s (%s %s-separated items required)" %
					(val,desc,n,sepword))
			return False
Example #32
0
	def send(self,t,delay=None,s=False):
		self.sent_value = None
		delay = delay or (0,0.3)[bool(opt.buf_keypress)]
		if delay: time.sleep(delay)
		ret = self.p.send(t) # returns num bytes written
		if ret:
			self.sent_value = t
		if delay: time.sleep(delay)
		if opt.verbose:
			ls = (' ','')[bool(opt.debug or not s)]
			es = ('  ','')[bool(s)]
			msg('{}SEND {}{}'.format(ls,es,yellow("'{}'".format(t.replace('\n',r'\n')))))
		return ret
Example #33
0
def opt_is_tx_fee(val, desc):
    from mmgen.tx import MMGenTX
    ret = MMGenTX().process_fee_spec(val, 224, on_fail='return')
    if ret == False:
        msg("'{}': invalid {}\n(not a {} amount or {} specification)".format(
            val, desc, g.coin.upper(),
            MMGenTX().rel_fee_desc))
    elif ret != None and ret > g.proto.max_tx_fee:
        msg("'{}': invalid {}\n({} > max_tx_fee ({} {}))".format(
            val, desc, ret.fmt(fs='1.1'), g.proto.max_tx_fee, g.coin.upper()))
    else:
        return True
    return False
Example #34
0
def warn_altcoins(trust_level):
	if trust_level == None: return
	tl = (red('COMPLETELY UNTESTED'),red('LOW'),yellow('MEDIUM'),green('HIGH'))
	m = """
Support for coin '{}' is EXPERIMENTAL.  The {pn} project assumes no
responsibility for any loss of funds you may incur.
This coin's {pn} testing status: {}
Are you sure you want to continue?
""".strip().format(g.coin,tl[trust_level],pn=g.proj_name)
	if os.getenv('MMGEN_TEST_SUITE'):
		msg(m); return
	if not keypress_confirm(m,default_yes=True):
		sys.exit(0)
Example #35
0
 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:
         m = "Sender address '{}' does not match address of key '{}'!"
         die(3, m.format(from_addr, tx.sender.encode('hex')))
     if g.debug:
         msg('{}'.format('\n  '.join(parse_abi(data))))
         pmsg(tx.to_dict())
     return hex_tx, coin_txid
Example #36
0
def _show_hash_presets():
	fs = "  {:<7} {:<6} {:<3}  {}"
	msg("Available parameters for scrypt.hash():")
	msg(fs.format("Preset","N","r","p"))
	for i in sorted(g.hash_presets.keys()):
		msg(fs.format("'%s'" % i, *g.hash_presets[i]))
	msg("N = memory usage (power of two), p = iterations (rounds)")
Example #37
0
 def send(self, t, delay=None, s=False):
     self.sent_value = None
     delay = delay or (0, 0.3)[bool(opt.buf_keypress)]
     if delay: time.sleep(delay)
     ret = self.p.send(t)  # returns num bytes written
     if ret:
         self.sent_value = t
     if delay: time.sleep(delay)
     if opt.verbose:
         ls = (' ', '')[bool(opt.debug or not s)]
         es = ('  ', '')[bool(s)]
         msg('{}SEND {}{}'.format(
             ls, es, yellow("'{}'".format(t.replace('\n', r'\n')))))
     return ret
Example #38
0
def _show_hash_presets():
    fs = '  {:<7} {:<6} {:<3}  {}'
    msg('Available parameters for scrypt.hash():')
    msg(fs.format('Preset', 'N', 'r', 'p'))
    for i in sorted(g.hash_presets.keys()):
        msg(fs.format("'{}'".format(i, *g.hash_presets[i])))
    msg('N = memory usage (power of two), p = iterations (rounds)')
Example #39
0
def get_cfg_template_data():
	# https://wiki.debian.org/Python:
	#   Debian (Ubuntu) sys.prefix is '/usr' rather than '/usr/local, so add 'local'
	# TODO - test for Windows
	# This must match the configuration in setup.py
	cfg_template = os.path.join(*([sys.prefix]
				+ (['share'],['local','share'])[g.platform=='linux']
				+ [g.proj_name.lower(),os.path.basename(g.cfg_file)]))
	try:
		with open(cfg_template,'rb') as f:
			return f.read()
	except:
		msg("WARNING: configuration template not found at '{}'".format(cfg_template))
		return u''
Example #40
0
    def opt_splits(val, sep, n, desc):
        sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else "'%s'" % sep
        try:
            l = val.split(sep)
        except:
            msg("'%s': invalid %s (not %s-separated list)" %
                (val, desc, sepword))
            return False

        if len(l) == n: return True
        else:
            msg("'%s': invalid %s (%s %s-separated items required)" %
                (val, desc, n, sepword))
            return False
Example #41
0
def _show_hash_presets():
	fs = '  {:<7} {:<6} {:<3}  {}'
	msg('Available parameters for scrypt.hash():')
	msg(fs.format('Preset','N','r','p'))
	for i in sorted(g.hash_presets.keys()):
		msg(fs.format("'%s'" % i, *g.hash_presets[i]))
	msg('N = memory usage (power of two), p = iterations (rounds)')
Example #42
0
File: opts.py Project: mmgen/mmgen
def opt_is_tx_fee(val,desc):
	from mmgen.tx import MMGenTX
	ret = MMGenTX().process_fee_spec(val,224,on_fail='return')
	# Non-standard startgas: disable fee checking
	if hasattr(opt,'contract_data') and opt.contract_data: ret = None
	if hasattr(opt,'tx_gas') and opt.tx_gas:               ret = None
	if ret == False:
		msg("'{}': invalid {}\n(not a {} amount or {} specification)".format(
				val,desc,g.coin.upper(),MMGenTX().rel_fee_desc))
	elif ret != None and ret > g.proto.max_tx_fee:
		msg("'{}': invalid {}\n({} > max_tx_fee ({} {}))".format(
				val,desc,ret.fmt(fs='1.1'),g.proto.max_tx_fee,g.coin.upper()))
	else:
		return True
	return False
Example #43
0
	def importaddress(self,address,label=None,rescan=True):
		try:
#			return self.proxy.badmethod(address,label) # DEBUG
			return self.proxy.importaddress(address,label,rescan)
		except JSONRPCException as e:
			if e.error['message'] == "Method not found":
				from mmgen.util import msg
				msg("""
*******************************************************************************
*******************************************************************************
ERROR: 'importaddress' not found.  Does your bitcoind support watch-only addrs?
*******************************************************************************
*******************************************************************************
""")
			raise _wrap_exception(e.error)
Example #44
0
def opt_is_tx_fee(val,desc):
	from mmgen.tx import MMGenTX
	ret = MMGenTX().process_fee_spec(val,224,on_fail='return')
	# Non-standard startgas: disable fee checking
	if hasattr(opt,'contract_data') and opt.contract_data: ret = None
	if hasattr(opt,'tx_gas') and opt.tx_gas:               ret = None
	if ret == False:
		msg("'{}': invalid {}\n(not a {} amount or {} specification)".format(
				val,desc,g.coin.upper(),MMGenTX().rel_fee_desc))
	elif ret != None and ret > g.proto.max_tx_fee:
		msg("'{}': invalid {}\n({} > max_tx_fee ({} {}))".format(
				val,desc,ret.fmt(fs='1.1'),g.proto.max_tx_fee,g.coin.upper()))
	else:
		return True
	return False
Example #45
0
	def txsign(self,tx_in,key,from_addr,chain_id=None):

		from .pyethereum.transactions import Transaction

		if chain_id is None:
			chain_id_method = ('parity_chainId','eth_chainId')['eth_chainId' in g.rpch.caps]
			chain_id = int(g.rpch.request(chain_id_method),16)
		tx = Transaction(**tx_in).sign(key,chain_id)
		hex_tx = rlp.encode(tx).hex()
		coin_txid = CoinTxID(tx.hash.hex())
		if tx.sender.hex() != from_addr:
			m = "Sender address '{}' does not match address of key '{}'!"
			die(3,m.format(from_addr,tx.sender.hex()))
		if g.debug:
			msg('{}'.format('\n  '.join(parse_abi(data))))
			pmsg(tx.to_dict())
		return hex_tx,coin_txid
Example #46
0
	async def txsign(self,tx_in,key,from_addr,chain_id=None):

		from .pyethereum.transactions import Transaction

		if chain_id is None:
			chain_id_method = ('parity_chainId','eth_chainId')['eth_chainId' in g.rpc.caps]
			chain_id = int(await g.rpc.call(chain_id_method),16)
		tx = Transaction(**tx_in).sign(key,chain_id)
		hex_tx = rlp.encode(tx).hex()
		coin_txid = CoinTxID(tx.hash.hex())
		if tx.sender.hex() != from_addr:
			m = "Sender address '{}' does not match address of key '{}'!"
			die(3,m.format(from_addr,tx.sender.hex()))
		if g.debug:
			msg('TOKEN DATA:')
			pp_msg(tx.to_dict())
			msg('PARSED ABI DATA:\n  {}'.format('\n  '.join(parse_abi(tx.data.hex()))))
		return hex_tx,coin_txid
Example #47
0
	def run_test(self,name,ut):

		msg_r('Testing MnemonicEntry methods...')

		from mmgen.mn_entry import mn_entry

		msg_r('\nTesting computed wordlist constants...')
		usl = {}
		for wl_id in self.vectors:
			for j,k in (('uniq_ss_len','usl'),('shortest_word','sw'),('longest_word','lw')):
				a = getattr(mn_entry(wl_id),j)
				b = self.vectors[wl_id][k]
				assert a == b, '{}:{} {} != {}'.format(wl_id,j,a,b)
		msg('OK')

		msg_r('Testing idx()...')
		qmsg('')
		junk = 'a g z aa gg zz aaa ggg zzz aaaa gggg zzzz aaaaaaaaaaaaaa gggggggggggggg zzzzzzzzzzzzzz'
		for wl_id in self.vectors:
			m = mn_entry(wl_id)
			qmsg('Wordlist: '+wl_id)
			for entry_mode in ('full','short'):
				for a,word in enumerate(m.wl):
					b = m.idx(word,entry_mode)
					assert a == b, '{} != {} ({!r} - entry mode: {!r})'.format(a,b,word,entry_mode)
				a = None
				for word in junk.split():
					b = m.idx(word,entry_mode)
					assert a == b, '{} != {} ({!r} - entry mode: {!r})'.format(a,b,word,entry_mode)
			if 'idx_minimal' in self.vectors[wl_id]:
				for vec in self.vectors[wl_id]['idx_minimal']:
					chk = vec[1]
					b = m.idx(vec[0],'minimal')
					if chk is False:
						assert b is None, (b,None)
					elif chk is None:
						assert type(b) == tuple, (type(b),tuple)
					elif type(chk) is int:
						assert b == chk, (b,chk)
		msg('OK')

		return True
Example #48
0
File: obj.py Project: mmgen/mmgen
	def init_fail(cls,e,m,e2=None,m2=None,objname=None,preformat=False):

		if preformat:
			errmsg = m
		else:
			fs = "{!r}: value cannot be converted to {} {}({})"
			e2_fmt = '({}) '.format(e2.args[0]) if e2 else ''
			errmsg = fs.format(m,objname or cls.__name__,e2_fmt,e.args[0])

		if m2: errmsg = '{!r}\n{}'.format(m2,errmsg)

		from mmgen.globalvars import g
		if g.traceback: cls.on_fail == 'raise'
		from mmgen.util import die,msg
		if   cls.on_fail == 'silent': return None # TODO: return False instead?
		elif cls.on_fail == 'raise':  raise ValueError(errmsg)
		elif cls.on_fail == 'die':    die(1,errmsg)
		elif cls.on_fail == 'return':
			if errmsg: msg(errmsg)
			return None                       # TODO: here too?
Example #49
0
    def verify_addr(cls, addr, hex_width, return_dict=False):

        if 'B' in cls.mmtypes and addr[:len(cls.bech32_hrp)] == cls.bech32_hrp:
            ret = bech32.decode(cls.bech32_hrp, addr)
            if ret[0] != cls.witness_vernum:
                msg('{}: Invalid witness version number'.format(ret[0]))
            elif ret[1]:
                return {
                    'hex': ''.join(map(chr, ret[1])).encode('hex'),
                    'format': 'bech32'
                } if return_dict else True
            return False

        for addr_fmt in cls.addr_ver_num:
            ver_num, pfx = cls.addr_ver_num[addr_fmt]
            if type(pfx) == tuple:
                if addr[0] not in pfx: continue
            elif addr[:len(pfx)] != pfx: continue
            num = _b58tonum(addr)
            if num == False:
                if g.debug: Msg('Address cannot be converted to base 58')
                break
            addr_hex = '{:0{}x}'.format(num, len(ver_num) + hex_width + 8)
            #			pmsg(hex_width,len(addr_hex),addr_hex[:len(ver_num)],ver_num)
            if addr_hex[:len(ver_num)] != ver_num: continue
            if hash256(addr_hex[:-8])[:8] == addr_hex[-8:]:
                return {
                    'hex': addr_hex[len(ver_num):-8],
                    'format': {
                        'p2pkh': 'p2pkh',
                        'p2sh': 'p2sh',
                        'p2sh2': 'p2sh',
                        'zcash_z': 'zcash_z',
                        'viewkey': 'viewkey'
                    }[addr_fmt]
                } if return_dict else True
            else:
                if g.debug: Msg('Invalid checksum in address')
                break

        return False
Example #50
0
	def __init__(self,args,no_output=False):

		if opt.direct_exec:
			msg('')
			from subprocess import call,check_output
			f = (call,check_output)[bool(no_output)]
			ret = f([args[0]] + args[1:])
			if f == call and ret != 0:
				die(1,red('ERROR: process returned a non-zero exit status ({})'.format(ret)))
		else:
			if opt.pexpect_spawn:
				self.p = pexpect.spawn(args[0],args[1:],encoding='utf8')
				self.p.delaybeforesend = 0
			else:
				self.p = PopenSpawn(args,encoding='utf8')
#				self.p.delaybeforesend = 0 # TODO: try this here too

			if opt.exact_output: self.p.logfile = sys.stdout

		self.req_exit_val = 0
		self.skip_ok = False
		self.timeout = int(opt.pexpect_timeout or 0) or (60,5)[bool(opt.debug_pexpect)]
		self.sent_value = None
Example #51
0
	def listaccounts(self, minconf=1, includeWatchonly=False, as_dict=False):
		"""
        Returns a list of account names.

        Arguments:

        - *minconf* -- Minimum number of confirmations before payments are included.
        - *as_dict* -- Returns a dictionary of account names, with their balance as values.
		"""
		try:
			if as_dict:
				return dict(self.proxy.listaccounts(minconf,includeWatchonly))
			else:
				return self.proxy.listaccounts(minconf,includeWatchonly).keys()
		except JSONRPCException as e:
			from mmgen.util import msg
			msg("""
*******************************************************************************
*******************************************************************************
ERROR: 'listaccounts' failed.  Does your bitcoind support watch-only addresses?
*******************************************************************************
*******************************************************************************
""")
			raise _wrap_exception(e.error)
Example #52
0
#!/usr/bin/env python3

from mmgen.common import *

cmd_args = opts.init({'text': { 'desc': '', 'usage':'', 'options':'' }})

from mmgen.util import msg

text = {
	'gr': 'Greek text: {}'.format(''.join(map(chr,list(range(913,939))))),
	'ru': 'Russian text: {}'.format(''.join(map(chr,list(range(1040,1072))))),
	'zh': 'Chinese text: {}'.format('所以,我們非常需要這樣一種電子支付系統,它基於密碼學原理而不基於信用,'),
	'jp': 'Japanese text: {}'.format('必要なのは、信用ではなく暗号化された証明に基づく電子取引システムであり、')
}

assert cmd_args[0] in text,'argument must be one of {}'.format(list(text.keys()))

msg(text[cmd_args[0]])
Example #53
0
 def opt_unrecognized(key, val, desc):
     msg("'{}': unrecognized {} for option '{}'".format(
         val, desc, fmt_opt(key)))
     return False
Example #54
0
def check_opts(usr_opts):       # Returns false if any check fails

	def opt_splits(val,sep,n,desc):
		sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else "'%s'" % sep
		try: l = val.split(sep)
		except:
			msg("'%s': invalid %s (not %s-separated list)" % (val,desc,sepword))
			return False

		if len(l) == n: return True
		else:
			msg("'%s': invalid %s (%s %s-separated items required)" %
					(val,desc,n,sepword))
			return False

	def opt_compares(val,op,target,desc,what=''):
		if what: what += ' '
		if not eval('%s %s %s' % (val, op, target)):
			msg('%s: invalid %s (%snot %s %s)' % (val,desc,what,op,target))
			return False
		return True

	def opt_is_int(val,desc):
		try: int(val)
		except:
			msg("'%s': invalid %s (not an integer)" % (val,desc))
			return False
		return True

	def opt_is_in_list(val,lst,desc):
		if val not in lst:
			q,sep = (('',','),("'","','"))[type(lst[0]) == str]
			msg('{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format(
					v=val,w=desc,q=q,
					o=sep.join([str(i) for i in sorted(lst)])
				))
			return False
		return True

	def opt_unrecognized(key,val,desc):
		msg("'%s': unrecognized %s for option '%s'"
				% (val,desc,fmt_opt(key)))
		return False

	def opt_display(key,val='',beg='For selected',end=':\n'):
		s = '%s=%s' % (fmt_opt(key),val) if val else fmt_opt(key)
		msg_r("%s option '%s'%s" % (beg,s,end))

	global opt
	for key,val in [(k,getattr(opt,k)) for k in usr_opts]:

		desc = "parameter for '%s' option" % fmt_opt(key)

		from mmgen.util import check_infile,check_outfile,check_outdir
		# Check for file existence and readability
		if key in ('keys_from_file','mmgen_keys_from_file',
				'passwd_file','keysforaddrs','comment_file'):
			check_infile(val)  # exits on error
			continue

		if key == 'outdir':
			check_outdir(val)  # exits on error
# 		# NEW
		elif key in ('in_fmt','out_fmt'):
			from mmgen.seed import SeedSource,IncogWallet,Brainwallet,IncogWalletHidden
			sstype = SeedSource.fmt_code_to_type(val)
			if not sstype:
				return opt_unrecognized(key,val,'format code')
			if key == 'out_fmt':
				p = 'hidden_incog_output_params'
				if sstype == IncogWalletHidden and not getattr(opt,p):
						die(1,'Hidden incog format output requested. You must supply'
						+ " a file and offset with the '%s' option" % fmt_opt(p))
				if issubclass(sstype,IncogWallet) and opt.old_incog_fmt:
					opt_display(key,val,beg='Selected',end=' ')
					opt_display('old_incog_fmt',beg='conflicts with',end=':\n')
					die(1,'Export to old incog wallet format unsupported')
				elif issubclass(sstype,Brainwallet):
					die(1,'Output to brainwallet format unsupported')
		elif key in ('hidden_incog_input_params','hidden_incog_output_params'):
			a = val.split(',')
			if len(a) < 2:
				opt_display(key,val)
				msg('Option requires two comma-separated arguments')
				return False
			fn,ofs = ','.join(a[:-1]),a[-1] # permit comma in filename
			if not opt_is_int(ofs,desc): return False
			if key == 'hidden_incog_input_params':
				check_infile(fn,blkdev_ok=True)
				key2 = 'in_fmt'
			else:
				try: os.stat(fn)
				except:
					b = os.path.dirname(fn)
					if b: check_outdir(b)
				else: check_outfile(fn,blkdev_ok=True)
				key2 = 'out_fmt'
			if hasattr(opt,key2):
				val2 = getattr(opt,key2)
				from mmgen.seed import IncogWalletHidden
				if val2 and val2 not in IncogWalletHidden.fmt_codes:
					die(1,
						'Option conflict:\n  %s, with\n  %s=%s' % (
						fmt_opt(key),fmt_opt(key2),val2
					))
		elif key == 'seed_len':
			if not opt_is_int(val,desc): return False
			if not opt_is_in_list(int(val),g.seed_lens,desc): return False
		elif key == 'hash_preset':
			if not opt_is_in_list(val,g.hash_presets.keys(),desc): return False
		elif key == 'brain_params':
			a = val.split(',')
			if len(a) != 2:
				opt_display(key,val)
				msg('Option requires two comma-separated arguments')
				return False
			d = 'seed length ' + desc
			if not opt_is_int(a[0],d): return False
			if not opt_is_in_list(int(a[0]),g.seed_lens,d): return False
			d = 'hash preset ' + desc
			if not opt_is_in_list(a[1],g.hash_presets.keys(),d): return False
		elif key == 'usr_randchars':
			if val == 0: continue
			if not opt_is_int(val,desc): return False
			if not opt_compares(val,'>=',g.min_urandchars,desc): return False
			if not opt_compares(val,'<=',g.max_urandchars,desc): return False
		elif key == 'tx_fee':
			if not opt_is_tx_fee(val,desc): return False
		elif key == 'tx_confs':
			if not opt_is_int(val,desc): return False
			if not opt_compares(val,'>=',1,desc): return False
		elif key == 'key_generator':
			if not opt_compares(val,'<=',len(g.key_generators),desc): return False
			if not opt_compares(val,'>',0,desc): return False
		elif key == 'coin':
			from mmgen.protocol import CoinProtocol
			if not opt_is_in_list(val.lower(),CoinProtocol.coins.keys(),'coin'): return False
		elif key == 'rbf':
			if not g.proto.cap('rbf'):
				die(1,'--rbf requested, but {} does not support replace-by-fee transactions'.format(g.coin))
		elif key in ('bob','alice'):
			from mmgen.regtest import daemon_dir
			m = "Regtest (Bob and Alice) mode not set up yet.  Run '{}-regtest setup' to initialize."
			try: os.stat(daemon_dir)
			except: die(1,m.format(g.proj_name.lower()))
		elif key == 'locktime':
			if not opt_is_int(val,desc): return False
			if not opt_compares(val,'>',0,desc): return False
		else:
			if g.debug: Msg("check_opts(): No test for opt '%s'" % key)

	return True
Example #55
0
def ok():
	if opt.verbose or opt.exact_output:
		sys.stderr.write(green("OK\n"))
	else: msg(" OK")
Example #56
0
	def opt_compares(val,op,target,desc,what=''):
		if what: what += ' '
		if not eval('%s %s %s' % (val, op, target)):
			msg('%s: invalid %s (%snot %s %s)' % (val,desc,what,op,target))
			return False
		return True
Example #57
0
	def opt_is_int(val,desc):
		try: int(val)
		except:
			msg("'%s': invalid %s (not an integer)" % (val,desc))
			return False
		return True
Example #58
0
	def opt_unrecognized(key,val,desc):
		msg("'%s': unrecognized %s for option '%s'"
				% (val,desc,fmt_opt(key)))
		return False
Example #59
0
    "usage": "[opts]",
    "options": """
-h, --help                 Print this help message
-e, --echo-passphrase      Print passphrase to screen when typing it
""",
}

short_opts = "he"
long_opts = "help", "echo_passphrase"

opts, cmd_args = process_opts(sys.argv, help_data, short_opts, long_opts)

c = connect_to_bitcoind()

prompt = "Enter passphrase: "
if "echo_passphrase" in opts:
    password = my_raw_input(prompt)
else:
    password = my_getpass(prompt)

from bitcoinrpc import exceptions

try:
    c.walletpassphrase(password, 9999)
except exceptions.WalletWrongEncState:
    msg("Wallet is unencrypted")
except exceptions.WalletPassphraseIncorrect:
    msg("Passphrase incorrect")
except exceptions.WalletAlreadyUnlocked:
    msg("WARNING: Wallet already unlocked!")