parse script pubkey into witness version and witness program
494968
def script_pubkey=(script_pubkey)
      values = [script_pubkey].pack('H*').unpack("C*")
      @ver = values[0] == 0 ? values[0] : values[0] - 0x50
      @prog = values[2..-1]
    end
1369023
def btc_witness_script_deserialize(_script):
    

    script = None
    if isinstance(_script, str) and re.match('^[0-9a-fA-F]*$', _script):
        # convert from hex to bin, safely
        script = binascii.unhexlify(_script)
    else:
        script = _script[:]

    # pointer to byte offset in _script (as an array due to Python scoping rules)
    ptr = [0]

    witness_stack_len = read_var_int(ptr, script)
    witness_stack = []

    for _ in xrange(0, witness_stack_len):

        stack_item = read_var_string(ptr, script)
        witness_stack.append(stack_item)

    return witness_stack
834686
def get_cli():
    """"""
    parser = argparse.ArgumentParser(
        prog="auto_version",
        description="auto version v%s: a tool to control version numbers" % __version__,
    )
    parser.add_argument(
        "--target",
        action="append",
        default=[],
        help="Files containing version info. "
        "Assumes unique variable names between files. (default: %s)."
        % (config.targets,),
    )
    parser.add_argument(
        "--bump",
        choices=SemVerSigFig,
        help="Bumps the specified part of SemVer string. "
        "Use this locally to correctly modify the version file.",
    )
    parser.add_argument(
        "--news",
        "--file-triggers",
        action="store_true",
        dest="file_triggers",
        help="Detects need to bump based on presence of files (as specified in config).",
    )
    parser.add_argument(
        "--set",
        help="Set the SemVer string. Use this locally to set the project version explicitly.",
    )
    parser.add_argument(
        "--set-patch-count",
        action="store_true",
        help="Sets the patch number to the commit count.",
    )
    parser.add_argument(
        "--lock",
        action="store_true",
        help="Locks the SemVer string. "
        "Lock will remain for another call to autoversion before being cleared.",
    )
    parser.add_argument(
        "--release",
        action="store_true",
        default=False,
        help="Marks as a release build, which flags the build as released.",
    )
    parser.add_argument(
        "--version",
        action="store_true",
        default=False,
        help="Prints the version of auto_version itself (self-version).",
    )
    parser.add_argument("--config", help="Configuration file path.")
    parser.add_argument(
        "-v",
        "--verbosity",
        action="count",
        default=0,
        help="increase output verbosity. " "can be specified multiple times",
    )
    return parser.parse_known_args()
365868
def matching_pubkey
      Pubkey.all
        .detect { |key| key.verify(self) }
        .tap { |key| self.pubkey = key }
    end
235901
def parse_multisig_redeemscript( redeem_script_hex ):
    
    script_parts = []
    redeem_script_hex = str(redeem_script_hex)

    try:
        script_parts = btc_script_deserialize(redeem_script_hex)
    except:
        if os.environ.get("BLOCKSTACK_TEST") == "1":
            traceback.print_exc()

        log.error("Invalid redeem script %s" % redeem_script_hex)
        return None, None

    try:
        assert len(script_parts) > 2
        assert script_parts[-1] == OPCODE_VALUES['OP_CHECKMULTISIG']
        script_parts.pop(-1)

        # get n
        n = script_parts.pop(-1)
        pubkeys = []

        # get m
        m = script_parts.pop(0)

        for i in xrange(0, n):
            pubk = script_parts.pop(0)
            
            # must be a public key
            BitcoinPublicKey(pubk)
            pubkeys.append(pubk)

        assert len(script_parts) == 0, "script_parts = %s" % script_parts
        return (m, pubkeys)
    except Exception, e:
        if os.environ.get("BLOCKSTACK_TEST") == "1":
            traceback.print_exc()

        log.error("Invalid redeem script %s (parses to %s)" % (redeem_script_hex, script_parts))
        return (None, None)
1191541
def process_pem_rsakey(self, data, name, idx):
        
        from cryptography.hazmat.primitives.serialization import load_der_public_key
        from cryptography.hazmat.primitives.serialization import load_der_private_key
        try:
            if startswith(data, '-----BEGIN RSA PUBLIC KEY') or startswith(data, '-----BEGIN PUBLIC KEY'):
                rsa = load_der_public_key(pem_to_der(data), self.get_backend())
                public_numbers = rsa.public_numbers()
            elif startswith(data, '-----BEGIN RSA PRIVATE KEY') or startswith(data, '-----BEGIN PRIVATE KEY'):
                rsa = load_der_private_key(pem_to_der(data), None, self.get_backend())
                public_numbers = rsa.private_numbers().public_numbers
            else:
                return None
            self.num_rsa_keys += 1
            self.num_rsa += 1

            js = collections.OrderedDict()
            js['type'] = 'pem-rsa-key'
            js['fname'] = name
            js['idx'] = idx
            js['pem'] = data
            js['e'] = '0x%x' % public_numbers.e
            js['n'] = '0x%x' % public_numbers.n

            if self.has_fingerprint(public_numbers.n):
                logger.warning('Fingerprint found in PEM RSA key %s ' % name)
                self.mark_and_add_effort(public_numbers.n, js)

                if self.do_print:
                    print(json.dumps(js))

            return TestResult(js)

        except Exception as e:
            logger.debug('Pubkey loading error: %s : %s [%s] : %s' % (name, idx, data[:20], e))
            self.trace_logger.log(e)
1330311
def p2pkh_input(outpoint, sig, pubkey, sequence=0xFFFFFFFE):
    '''
    
    '''
    stack_script = '{sig} {pk}'.format(sig=sig, pk=pubkey)
    stack_script = script_ser.serialize(stack_script)
    return tb.make_legacy_input(outpoint, stack_script, b'', sequence)
800281
def make_witness_input(outpoint, sequence):
    '''
    
    '''
    if 'decred' in riemann.get_current_network_name():
        return tx.DecredTxIn(
            outpoint=outpoint,
            sequence=utils.i2le_padded(sequence, 4))
    return tx.TxIn(outpoint=outpoint,
                   stack_script=b'',
                   redeem_script=b'',
                   sequence=utils.i2le_padded(sequence, 4))
217176
def sighash_for_witness(index, script_pubkey_or_script_code, hash_type, amount, skip_separator_index)
      hash_prevouts = Bitcoin.double_sha256(inputs.map{|i|i.out_point.to_payload}.join)
      hash_sequence = Bitcoin.double_sha256(inputs.map{|i|[i.sequence].pack('V')}.join)
      outpoint = inputs[index].out_point.to_payload
      amount = [amount].pack('Q')
      nsequence = [inputs[index].sequence].pack('V')
      hash_outputs = Bitcoin.double_sha256(outputs.map{|o|o.to_payload}.join)

      script_code = script_pubkey_or_script_code.to_script_code(skip_separator_index)

      case (hash_type & 0x1f)
      when SIGHASH_TYPE[:single]
        hash_outputs = index >= outputs.size ? "\x00".ljust(32, "\x00") : Bitcoin.double_sha256(outputs[index].to_payload)
        hash_sequence = "\x00".ljust(32, "\x00")
      when SIGHASH_TYPE[:none]
        hash_sequence = hash_outputs = "\x00".ljust(32, "\x00")
      end

      if (hash_type & SIGHASH_TYPE[:anyonecanpay]) != 0
        hash_prevouts = hash_sequence ="\x00".ljust(32, "\x00")
      end
      hash_type |= (Bitcoin.chain_params.fork_id << 8) if Bitcoin.chain_params.fork_chain?
      buf = [ [version].pack('V'), hash_prevouts, hash_sequence, outpoint,
              script_code ,amount, nsequence, hash_outputs, [@lock_time, hash_type].pack('VV')].join
      Bitcoin.double_sha256(buf)
    end
764394
def _legacy_pubs(buf):
    """"""
    leftover = buf.read()
    if leftover:
        log.warning('skipping leftover: %r', leftover)
    code = util.pack('B', msg_code('SSH_AGENT_RSA_IDENTITIES_ANSWER'))
    num = util.pack('L', 0)  # no SSH v1 keys
    return util.frame(code, num)
623278
def get_pubkey(self):
        '''
        
        '''
        if '__master_opts__' in self.opts and \
                self.opts['__master_opts__'].get('ssh_use_home_key') and \
                os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
            priv = os.path.expanduser('~/.ssh/id_rsa')
        else:
            priv = self.opts.get(
                    'ssh_priv',
                    os.path.join(
                        self.opts['pki_dir'],
                        'ssh',
                        'salt-ssh.rsa'
                        )
                    )
        pub = '{0}.pub'.format(priv)
        with salt.utils.files.fopen(pub, 'r') as fp_:
            return '{0} rsa root@master'.format(fp_.read().split()[1])
1129493
def import_public_keys(contents):
    """"""
    for line in io.StringIO(contents):
        # Verify this line represents valid SSH public key
        formats.import_public_key(line)
        yield line
961143
def from_str(cls: Type[CRCPubkeyType], crc_pubkey: str) -> CRCPubkeyType:
        
        data = CRCPubkey.re_crc_pubkey.match(crc_pubkey)
        if data is None:
            raise Exception("Could not parse CRC public key {0}".format(crc_pubkey))
        pubkey = data.group(1)
        crc = data.group(2)
        return cls(pubkey, crc)
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
354259
function parseVersion(versionString) {
  const [release, prerelease] = versionString.split('-')
  const splitRelease = release.split('.').map(number => parseInt(number, 10))

  return {
    major: splitRelease[0],
    minor: splitRelease[1],
    patch: splitRelease[2],
    prerelease: prerelease || '',
    raw: versionString
  }
}
179473
function validateKey(key, flags, version) {
  assert(Buffer.isBuffer(key));
  assert(typeof flags === 'number');
  assert(typeof version === 'number');

  if (flags & Script.flags.VERIFY_STRICTENC) {
    if (!common.isKeyEncoding(key))
      throw new ScriptError('PUBKEYTYPE');
  }

  if (version === 1) {
    if (flags & Script.flags.VERIFY_WITNESS_PUBKEYTYPE) {
      if (!common.isCompressedEncoding(key))
        throw new ScriptError('WITNESS_PUBKEYTYPE');
    }
  }

  return true;
}
711743
def fingerprint_from_raw_ssh_pub_key(key):
    
    fp_plain = hashlib.md5(key).hexdigest()
    return ':'.join(a + b for a, b in zip(fp_plain[::2], fp_plain[1::2]))