import { Buff } from '@cmdcode/buff';
import { verify_sig } from '@cmdcode/crypto-tools/signer';
export function gen_membership(index, signer, wallet) {
    return signer.gen_cred(index, wallet.xpub);
}
export function has_membership(members, signer) {
    const entry = members.find(e => signer.has_id(e.id, e.pub));
    return entry !== undefined;
}
export function get_membership(members, signer) {
    const entry = members.find(e => signer.has_id(e.id, e.pub));
    if (entry === undefined) {
        throw new Error('signer is not a member');
    }
    return entry;
}
export function has_credential(cred, signer) {
    return signer.has_id(cred.id, cred.pub);
}
export function has_member_data(members, mship) {
    return members.find(e => e.pub === mship.pub) !== undefined;
}
export function add_member_data(members, mship) {
    if (members.some(e => e.pub === mship.pub)) {
        throw new Error('member data already exists');
    }
    return [...members, mship];
}
export function upsert_member_data(members, mship) {
    const mbrs = members.filter(e => e.pub !== mship.pub);
    return [...mbrs, mship];
}
export function rem_member_data(members, mship) {
    return members.filter(e => e.pub !== mship.pub);
}
export function create_endorsement(record_id, signer) {
    const pub = signer.pubkey;
    const sig = signer.sign(record_id);
    return Buff.join([pub, sig]);
}
export function verify_endorsement(record_id, signature, throws = false) {
    const bytes = Buff.bytes(signature);
    const pub = bytes.subarray(0, 32);
    const sig = bytes.subarray(32, 96);
    const bool = verify_sig(sig, record_id, pub);
    if (!bool && throws) {
        throw new Error('invalid signature for pubkey: ' + pub.hex);
    }
    return bool;
}
