Parse a pay-to-public-key-hash address.
        Return a :class:`Contract` or None.
421614
def p2pkh(self, s):
        
        data = self.parse_b58_hashed(s)
        if data is None or not data.startswith(self._address_prefix):
            return None
        size = len(self._address_prefix)
        script = self._network.contract.for_p2pkh(data[size:])
        script_info = self._network.contract.info_for_script(script)
        return Contract(script_info, self._network)
1111717
def parse_transaction_bytes(tx_bytes):
    
    tx = messages.StellarSignTx()
    unpacker = xdrlib.Unpacker(tx_bytes)

    tx.source_account = _xdr_read_address(unpacker)
    tx.fee = unpacker.unpack_uint()
    tx.sequence_number = unpacker.unpack_uhyper()

    # Timebounds is an optional field
    if unpacker.unpack_bool():
        max_timebound = 2 ** 32 - 1  # max unsigned 32-bit int
        # (trezor does not support the full 64-bit time value)

        tx.timebounds_start = unpacker.unpack_uhyper()
        tx.timebounds_end = unpacker.unpack_uhyper()

        if tx.timebounds_start > max_timebound or tx.timebounds_start < 0:
            raise ValueError(
                "Starting timebound out of range (must be between 0 and "
                + max_timebound
            )
        if tx.timebounds_end > max_timebound or tx.timebounds_end < 0:
            raise ValueError(
                "Ending timebound out of range (must be between 0 and " + max_timebound
            )

    # memo type determines what optional fields are set
    tx.memo_type = unpacker.unpack_uint()

    # text
    if tx.memo_type == MEMO_TYPE_TEXT:
        tx.memo_text = unpacker.unpack_string()
    # id (64-bit uint)
    if tx.memo_type == MEMO_TYPE_ID:
        tx.memo_id = unpacker.unpack_uhyper()
    # hash / return are the same structure (32 bytes representing a hash)
    if tx.memo_type == MEMO_TYPE_HASH or tx.memo_type == MEMO_TYPE_RETURN:
        tx.memo_hash = unpacker.unpack_fopaque(32)

    tx.num_operations = unpacker.unpack_uint()

    operations = []
    for _ in range(tx.num_operations):
        operations.append(_parse_operation_bytes(unpacker))

    return tx, operations
1324967
def parse(cls, buf):
        

        pkt = DhcpPacket()
        (pkt.ciaddr,) = cls.struct('4s').unpack_from(buf, 12)
        (pkt.giaddr,) = cls.struct('4s').unpack_from(buf, 24)
        cls.struct('4s').pack_into(buf, 24, b'')
        pos = 240
        while pos < len(buf):
            (opttag,) = cls.struct('B').unpack_from(buf, pos)
            if opttag == 0:
                pos += 1
                continue
            if opttag == END:
                pkt.end = pos
                break
            (optlen,) = cls.struct('B').unpack_from(buf, pos + 1)
            startpos = pos
            pos += 2
            if opttag != RELAY_AGENT_INFO:
                pos += optlen
                continue
            optend = pos + optlen
            while pos < optend:
                (subopttag, suboptlen) = cls.struct('BB').unpack_from(buf, pos)
                fmt = '%is' % (suboptlen,)
                (val,) = cls.struct(fmt).unpack_from(buf, pos + 2)
                pkt.relay_options[subopttag] = val
                pos += suboptlen + 2
            cls.struct('%is' % (optlen + 2)).pack_into(buf, startpos, b'')
        pkt.buf = buf
        return pkt
809170
def standard_address(network: nil)
      if public_key_hash_script?
        return BTC::PublicKeyAddress.new(hash: @chunks[2].pushdata, network: network)
      elsif script_hash_script?
        return BTC::ScriptHashAddress.new(hash: @chunks[1].pushdata, network: network)
      elsif public_key_script?
        return BTC::PublicKeyAddress.new(hash: BTC.hash160(@chunks[0].pushdata), network: network)
      end
      nil
    end
887843
def make_pkh_address(pubkey, witness=False, cashaddr=True):
    '''
    
    '''
    pubkey_hash = utils.hash160(pubkey)
    return _make_pkh_address(pubkey_hash=pubkey_hash,
                             witness=witness,
                             cashaddr=cashaddr)
581241
def tx_for_tx_hash(self, tx_hash):
        
        url = "%s/rawtx/%s" % (self.url, b2h_rev(tx_hash))
        d = urlopen(url).read()
        j = json.loads(d.decode("utf8"))
        tx = Tx.from_hex(j.get("rawtx", ""))
        if tx.hash() == tx_hash:
            return tx
302066
def parse_key(key):
    
    hkey, lkey = struct.unpack('<II',key[0:UBIFS_SK_LEN])
    ino_num = hkey & UBIFS_S_KEY_HASH_MASK
    key_type = lkey >> UBIFS_S_KEY_BLOCK_BITS
    khash = lkey

    #if key_type < UBIFS_KEY_TYPES_CNT:
    return {'type':key_type, 'ino_num':ino_num, 'khash': khash}
1143497
def parse_path(nstr: str) -> Address:
    
    if not nstr:
        return []

    n = nstr.split("/")

    # m/a/b/c => a/b/c
    if n[0] == "m":
        n = n[1:]

    # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c
    if n[0] in slip44:
        coin_id = slip44[n[0]]
        n[0:1] = ["44h", "{}h".format(coin_id)]

    def str_to_harden(x: str) -> int:
        if x.startswith("-"):
            return H_(abs(int(x)))
        elif x.endswith(("h", "'")):
            return H_(int(x[:-1]))
        else:
            return int(x)

    try:
        return [str_to_harden(x) for x in n]
    except Exception:
        raise ValueError("Invalid BIP32 path", nstr)
368659
def neo_get_scripthash_from_address(address):
    
    hash_bytes = binascii.hexlify(base58.b58decode_check(address))
    return reverse_hex(hash_bytes[2:].decode('utf-8'))
843284
def to_output_script(address):
    '''
    
    '''
    parsed = parse(address)
    parsed_hash = b''

    try:
        if (parsed.find(riemann.network.P2WPKH_PREFIX) == 0
                and len(parsed) == 22):
            return parsed
    except TypeError:
        pass

    try:
        if (parsed.find(riemann.network.P2WSH_PREFIX) == 0
                and len(parsed) == 34):
            return parsed
    except TypeError:
        pass

    try:
        if (parsed.find(riemann.network.CASHADDR_P2SH) == 0
                and len(parsed) == len(riemann.network.CASHADDR_P2SH) + 20):
            prefix = b'\xa9\x14'  # OP_HASH160 PUSH14
            parsed_hash = parsed[len(riemann.network.P2SH_PREFIX):]
            suffix = b'\x87'  # OP_EQUAL
    except TypeError:
        pass

    try:
        if (parsed.find(riemann.network.CASHADDR_P2PKH) == 0
                and len(parsed) == len(riemann.network.CASHADDR_P2PKH) + 20):
            prefix = b'\x76\xa9\x14'  # OP_DUP OP_HASH160 PUSH14
            parsed_hash = parsed[len(riemann.network.P2PKH_PREFIX):]
            suffix = b'\x88\xac'  # OP_EQUALVERIFY OP_CHECKSIG
    except TypeError:
        pass

    if (parsed.find(riemann.network.P2PKH_PREFIX) == 0
            and len(parsed) == len(riemann.network.P2PKH_PREFIX) + 20):
        prefix = b'\x76\xa9\x14'  # OP_DUP OP_HASH160 PUSH14
        parsed_hash = parsed[len(riemann.network.P2PKH_PREFIX):]
        suffix = b'\x88\xac'  # OP_EQUALVERIFY OP_CHECKSIG

    if (parsed.find(riemann.network.P2SH_PREFIX) == 0
            and len(parsed) == len(riemann.network.P2SH_PREFIX) + 20):
        prefix = b'\xa9\x14'  # OP_HASH160 PUSH14
        parsed_hash = parsed[len(riemann.network.P2SH_PREFIX):]
        suffix = b'\x87'  # OP_EQUAL

    if parsed_hash == b'':
        raise ValueError('Cannot parse output script from address.')

    output_script = prefix + parsed_hash + suffix
    return output_script
627988
def _parse_address(self, val):
        

        ret = {
            'type': None,
            'value': None
        }

        try:

            ret['type'] = val[1]['type']

        except (KeyError, ValueError, TypeError):

                pass

        try:

            ret['value'] = val[1]['label']

        except (KeyError, ValueError, TypeError):

            ret['value'] = '\n'.join(val[3]).strip()

        try:

            self.vars['address'].append(ret)

        except AttributeError:

            self.vars['address'] = []
            self.vars['address'].append(ret)
1227004
def parse( bin_payload, sender_script, recipient_address ):
    
   
   if len(bin_payload) < MIN_OP_LENGTHS['namespace_reveal']:
       raise AssertionError("Payload is too short to be a namespace reveal")

   off = 0
   life = None 
   coeff = None 
   base = None 
   bucket_hex = None
   buckets = []
   discount_hex = None
   nonalpha_discount = None 
   no_vowel_discount = None
   version = None
   namespace_id = None 
   namespace_id_hash = None
   
   life = int( hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_life']]), 16 )
   
   off += LENGTHS['blockchain_id_namespace_life']
   
   coeff = int( hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_coeff']]), 16 )
   
   off += LENGTHS['blockchain_id_namespace_coeff']
   
   base = int( hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_base']]), 16 )
   
   off += LENGTHS['blockchain_id_namespace_base']
   
   bucket_hex = hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_buckets']])
   
   off += LENGTHS['blockchain_id_namespace_buckets']
   
   discount_hex = hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_discounts']])
   
   off += LENGTHS['blockchain_id_namespace_discounts']
   
   version = int( hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_version']]), 16)
   
   off += LENGTHS['blockchain_id_namespace_version']
   
   namespace_id = bin_payload[off:]
   namespace_id_hash = None
   try:
       namespace_id_hash = hash_name( namespace_id, sender_script, register_addr=recipient_address )
   except:
       log.error("Invalid namespace ID and/or sender script")
       return None
   
   # extract buckets 
   buckets = [int(x, 16) for x in list(bucket_hex)]
   
   # extract discounts
   nonalpha_discount = int( list(discount_hex)[0], 16 )
   no_vowel_discount = int( list(discount_hex)[1], 16 )
  
   try:
       rc = namespacereveal_sanity_check( namespace_id, version, life, coeff, base, buckets, nonalpha_discount, no_vowel_discount )
       if not rc:
           raise Exception("Invalid namespace parameters")

   except Exception, e:
       if BLOCKSTACK_TEST:
           log.exception(e)

       log.error("Invalid namespace parameters")
       return None 

   return {
      'opcode': 'NAMESPACE_REVEAL',
      'lifetime': life,
      'coeff': coeff,
      'base': base,
      'buckets': buckets,
      'version': version,
      'nonalpha_discount': nonalpha_discount,
      'no_vowel_discount': no_vowel_discount,
      'namespace_id': namespace_id,
      'preorder_hash': namespace_id_hash
   }
398452
def get_hash(path, cut=0):
    
    code, output = call(path, 'rev-parse', 'HEAD')
    if code > 0:
        return None
    # maybe the string is with a linebreak.
    sha1 = output.strip()
    if cut > 0:
        sha1 = sha1[:7]
    return sha1
848754
def get(value: str) -> 'Protocol':
        

        for pktype in PublicKeyType:
            if value in (pktype.ver_type, pktype.authn_type):
                return pktype
        return None
1066720
def get_JWT(url, address=None):
    
    jwt_txt = None
    jwt = None

    log.debug("Try {}".format(url))

    # special case: handle file://
    urlinfo = urllib2.urlparse.urlparse(url)
    if urlinfo.scheme == 'file':
        # points to a path on disk
        try:
            with open(urlinfo.path, 'r') as f:
                jwt_txt = f.read()

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Failed to read {}".format(url))
            return None

    else:
        # http(s) URL or similar
        try:
            resp = requests.get(url)
            assert resp.status_code == 200, 'Bad status code on {}: {}'.format(url, resp.status_code)
            jwt_txt = resp.text

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Unable to resolve {}".format(url))
            return None

    try:
        # one of two things are possible:
        # * this is a JWT string
        # * this is a serialized JSON string whose first item is a dict that has 'token' as key,
        # and that key is a JWT string.
        try:
            jwt_txt = json.loads(jwt_txt)[0]['token']
        except:
            pass

        jwt = jsontokens.decode_token(jwt_txt)
    except Exception as e:
        if BLOCKSTACK_TEST:
            log.exception(e)

        log.warning("Unable to decode token at {}".format(url))
        return None

    try:
        # must be well-formed
        assert isinstance(jwt, dict)
        assert 'payload' in jwt, jwt
        assert isinstance(jwt['payload'], dict)
        assert 'issuer' in jwt['payload'], jwt
        assert isinstance(jwt['payload']['issuer'], dict)
        assert 'publicKey' in jwt['payload']['issuer'], jwt
        assert virtualchain.ecdsalib.ecdsa_public_key(str(jwt['payload']['issuer']['publicKey']))

    except AssertionError as ae:
        if BLOCKSTACK_TEST or BLOCKSTACK_DEBUG:
            log.exception(ae)

        log.warning("JWT at {} is malformed".format(url))
        return None

    if address is not None:
        public_key = str(jwt['payload']['issuer']['publicKey'])
        addrs = [virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.decompress(public_key)).address()),
                 virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.compress(public_key)).address())]

        if virtualchain.address_reencode(address) not in addrs:
            # got a JWT, but it doesn't match the address
            log.warning("Found JWT at {}, but its public key has addresses {} and {} (expected {})".format(url, addrs[0], addrs[1], address))
            return None

        verifier = jsontokens.TokenVerifier()
        if not verifier.verify(jwt_txt, public_key):
            # got a JWT, and the address matches, but the signature does not
            log.warning("Found JWT at {}, but it was not signed by {} ({})".format(url, public_key, address))
            return None

    return jwt
925167
def _get_private_key_obj(private_key, passphrase=None):
    '''
    
    '''
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase))
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey
1212709
def get_address(name, hash, db, target=None):
        '''
        
        '''

        key = DB.pkey([EZO.DEPLOYED, name, target, hash])

        d, err = db.get(key)
        if err:
            return None, err
        if not d:
            return None, None
        return d['address'].lower(), None