Instantiates address with a BTC::Key or a binary public key.
 Returns BTC::Script with data 'OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG'
160082
def script
      raise ArgumentError, "BTC::PublicKeyAddress: invalid data length (must be 20 bytes)" if self.data.bytesize != 20
      BTC::Script.new << OP_DUP << OP_HASH160 << self.data << OP_EQUALVERIFY << OP_CHECKSIG
    end
1276015
def make_pkh_output_script(pubkey, witness=False):
    '''
    
    '''
    if witness and not riemann.network.SEGWIT:
        raise ValueError(
            'Network {} does not support witness scripts.'
            .format(riemann.get_current_network_name()))

    output_script = bytearray()

    if type(pubkey) is not bytearray and type(pubkey) is not bytes:
        raise ValueError('Unknown pubkey format. '
                         'Expected bytes. Got: {}'.format(type(pubkey)))

    pubkey_hash = utils.hash160(pubkey)

    if witness:
        output_script.extend(riemann.network.P2WPKH_PREFIX)
        output_script.extend(pubkey_hash)
    else:
        output_script.extend(b'\x76\xa9\x14')  # OP_DUP OP_HASH160 PUSH14
        output_script.extend(pubkey_hash)
        output_script.extend(b'\x88\xac')  # OP_EQUALVERIFY OP_CHECKSIG
    return output_script
861908
def verify_multisig(address, hash_hex, scriptSig):
    
    script_parts = virtualchain.btc_script_deserialize(scriptSig)
    if len(script_parts) < 2:
        log.warn("Verfiying multisig failed, couldn't grab script parts")
        return False

    redeem_script = script_parts[-1]
    script_sigs = script_parts[1:-1]

    if virtualchain.address_reencode(virtualchain.btc_make_p2sh_address(redeem_script)) != virtualchain.address_reencode(address):
        log.warn(("Address {} does not match redeem script {}".format(address, redeem_script)))
        return False

    m, pubk_hexes = virtualchain.parse_multisig_redeemscript(redeem_script)
    if len(script_sigs) != m:
        log.warn("Failed to validate multi-sig, not correct number of signatures: have {}, require {}".format(
            len(script_sigs), m))
        return False

    cur_pubk = 0
    for cur_sig in script_sigs:
        sig64 = base64.b64encode(binascii.unhexlify(cur_sig))
        sig_passed = False
        while not sig_passed:
            if cur_pubk >= len(pubk_hexes):
                log.warn("Failed to validate multi-signature, ran out of public keys to check")
                return False
            sig_passed = virtualchain.ecdsalib.verify_digest(hash_hex, pubk_hexes[cur_pubk], sig64)
            cur_pubk += 1

    return True
439122
def p2pkh_addr
      return nil unless p2pkh?
      hash160 = chunks[2].pushed_data.bth
      return nil unless hash160.htb.bytesize == 20
      Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.address_version)
    end
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
1296907
def btc_tx_get_hash( tx_serialized, hashcode=None ):
    
    if btc_tx_is_segwit(tx_serialized):
        raise ValueError('Segwit transaction: {}'.format(tx_serialized))

    tx_bin = binascii.unhexlify(tx_serialized)
    if hashcode:
        return binascii.hexlify( hashing.bin_double_sha256(tx_bin + encoding.encode(int(hashcode), 256, 4)[::-1]) )

    else:
        return binascii.hexlify( hashing.bin_double_sha256(tx_bin)[::-1] )
130281
def _get_pubkey_hash(cert):
    '''
    
    '''
    sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
    return _pretty_hex(sha_hash)
399676
def btc_script_to_hex(script):
    

    hex_script = ''
    parts = script.split(' ')
    for part in parts:
        if part[0:3] == 'OP_':
            value = OPCODE_VALUES.get(part)
            if not value:
                raise ValueError("Unrecognized opcode {}".format(part))

            hex_script += "%0.2x" % value

        elif hashing.is_hex(part):
            hex_script += '%0.2x' % hashing.count_bytes(part) + part

        else:
            raise Exception('Invalid script - only opcodes and hex characters allowed.')

    return hex_script
729195
def btc_make_p2sh_address( script_hex ):
    
    h = hashing.bin_hash160(binascii.unhexlify(script_hex))
    addr = bin_hash160_to_address(h, version_byte=multisig_version_byte)
    return addr
627527
def btc_make_p2wpkh_address( pubkey_hex ):
    
    pubkey_hex = keylib.key_formatting.compress(pubkey_hex)
    hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex'))
    return segwit_addr_encode(hash160_bin)
374181
def get_balance(address = nil)
      outputs = get_unspent_outputs(address.nil? ? [] : [oa_address_to_address(address)])
      colored_outputs = outputs.map{|o|o.output}
      sorted_outputs = colored_outputs.sort_by { |o|o.script.to_string}
      groups = sorted_outputs.group_by{|o| o.script.to_string}
      result = groups.map{|k, v|
        btc_address = script_to_address(v[0].script)
        sorted_script_outputs = v.sort_by{|o|o.asset_id unless o.asset_id}
        group_assets = sorted_script_outputs.group_by{|o|o.asset_id}.select{|k,v| !k.nil?}
        assets = group_assets.map{|asset_id, outputs|
          {
              'asset_id' => asset_id,
              'quantity' => outputs.inject(0) { |sum, o| sum + o.asset_quantity }.to_s,
              'amount' => outputs.inject(0) { |sum, o| sum + o.asset_amount }.to_s,
              'asset_definition_url' => outputs[0].asset_definition_url,
              'proof_of_authenticity' => outputs[0].proof_of_authenticity
          }
        }
        {
            'address' => btc_address,
            'oa_address' => (btc_address.nil? || btc_address.is_a?(Array)) ? nil : address_to_oa_address(btc_address),
            'value' => satoshi_to_coin(v.inject(0) { |sum, o|sum +  o.value}),
            'assets' => assets,
            'account' => v[0].account
        }
      }
      address.nil? ? result : result.select{|r|r['oa_address'] == address}
    end
607155
def btc_script_classify(scriptpubkey, private_key_info=None):
    
    if scriptpubkey.startswith("76a914") and scriptpubkey.endswith("88ac") and len(scriptpubkey) == 50:
        return 'p2pkh'

    elif scriptpubkey.startswith("a914") and scriptpubkey.endswith("87") and len(scriptpubkey) == 46:
        # maybe p2sh-p2wpkh or p2sh-p2wsh?
        if private_key_info:
            if btc_is_singlesig_segwit(private_key_info):
                return 'p2sh-p2wpkh'
            elif btc_is_multisig_segwit(private_key_info):
                return 'p2sh-p2wsh'

        return 'p2sh'

    elif scriptpubkey.startswith('0014') and len(scriptpubkey) == 44:
        return 'p2wpkh'

    elif scriptpubkey.startswith('0020') and len(scriptpubkey) == 68:
        return 'p2wsh'

    script_tokens = btc_script_deserialize(scriptpubkey)
    if len(script_tokens) == 0:
        return None

    if script_tokens[0] == OPCODE_VALUES['OP_RETURN']:
        return "nulldata"

    elif script_tokens[-1] == OPCODE_VALUES['OP_CHECKMULTISIG']:
        return "multisig"

    elif len(script_tokens) == 2 and script_tokens[-1] == OPCODE_VALUES["OP_CHECKSIG"]:
        return "p2pk"

    return None
867017
def p2pkh?
      return false unless chunks.size == 5
      [OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG] ==
          (chunks[0..1]+ chunks[3..4]).map(&:ord) && chunks[2].bytesize == 21
    end
134391
def verify(address, plaintext, scriptSigb64):
    
    assert isinstance(address, str)
    assert isinstance(scriptSigb64, str)

    scriptSig = base64.b64decode(scriptSigb64)
    hash_hex = hashlib.sha256(plaintext).hexdigest()

    vb = keylib.b58check.b58check_version_byte(address)

    if vb == bitcoin_blockchain.version_byte:
        return verify_singlesig(address, hash_hex, scriptSig)
    elif vb == bitcoin_blockchain.multisig_version_byte:
        return verify_multisig(address, hash_hex, scriptSig)
    else:
        log.warning("Unrecognized address version byte {}".format(vb))
        raise NotImplementedError("Addresses must be single-sig (version-byte = 0) or multi-sig (version-byte = 5)")
671612
def p2sh_addr
      return nil unless p2sh?
      hash160 = chunks[1].pushed_data.bth
      return nil unless hash160.htb.bytesize == 20
      Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.p2sh_version)
    end
1066568
def import_public_key(line):
    """"""
    log.debug('loading SSH public key: %r', line)
    file_type, base64blob, name = line.split()
    blob = base64.b64decode(base64blob)
    result = parse_pubkey(blob)
    result['name'] = name.encode('utf-8')
    assert result['type'] == file_type.encode('ascii')
    log.debug('loaded %s public key: %s', file_type, result['fingerprint'])
    return result
823094
def verify(data, sig)
      regenerate_pubkey unless @key.public_key
      sig = Bitcoin::OpenSSL_EC.repack_der_signature(sig)
      if sig
        @key.dsa_verify_asn1(data, sig)
      else
        false
      end
    end