def btc_tx_sign_multisig(tx, idx, redeem_script, private_keys, hashcode=SIGHASH_ALL):
    """
    Sign a p2sh multisig input (not segwit!).

    @tx must be a hex-encoded tx

    Return the signed transaction
    """
    
    from .multisig import parse_multisig_redeemscript

    # sign in the right order.  map all possible public keys to their private key
    txobj = btc_tx_deserialize(str(tx))

    privs = {}
    for pk in private_keys:
        pubk = ecdsalib.ecdsa_private_key(pk).public_key().to_hex()

        compressed_pubkey = keylib.key_formatting.compress(pubk)
        uncompressed_pubkey = keylib.key_formatting.decompress(pubk)

        privs[compressed_pubkey] = pk
        privs[uncompressed_pubkey] = pk

    m, public_keys = parse_multisig_redeemscript(str(redeem_script))

    used_keys, sigs = [], []
    for public_key in public_keys:
        if public_key not in privs:
            continue

        if len(used_keys) == m:
            break

        if public_key in used_keys:
            raise ValueError('Tried to reuse key in redeem script: {}'.format(public_key))

        pk_str = privs[public_key]
        used_keys.append(public_key)

        sig = btc_tx_make_input_signature(tx, idx, redeem_script, pk_str, hashcode)
        sigs.append(sig)

    if len(used_keys) != m:
        raise ValueError('Missing private keys (used {}, required {})'.format(len(used_keys), m))

    txobj["ins"][idx]["script"] = btc_script_serialize([None] + sigs + [redeem_script])
    return btc_tx_serialize(txobj)