herumi / mcl

a portable and fast pairing-based cryptography library
BSD 3-Clause "New" or "Revised" License
450 stars 151 forks source link

Initialize EC curve (C++ doc is lack) #180

Closed XinwenXiang closed 1 year ago

XinwenXiang commented 1 year ago

hi,

I'm trying to use secp256k1 in a C++ project , it seems that the initPairing() only support curves that support Pairing . mcl::bn::initPairing(mcl::BLS12_381); and I have read ecdsa.hpp, it uses this to init curve:

inline void init(bool *pb)
{
    local::Param& p = local::getParam();
    mcl::initCurve<Ec, Zn>(pb, MCL_SECP256K1, &p.P);
    if (!*pb) return;
    p.bitSize = 256;
    p.Pbase.init(pb, p.P, p.bitSize, local::winSize);
    // isValid() checks the order
    Ec::setOrder(Zn::getOp().mp);
    Fp::setETHserialization(true);
    Zn::setETHserialization(true);
    p.serializeMode = SerializeBitcoin;
//  Ec::setIoMode(mcl::IoEcAffineSerialize);
}

should i use the same way to init secp256k1 in my project, and how can i get random element of G1?

herumi commented 1 year ago

You can use the initialization,

#include <mcl/ecdsa.hpp>

int main()
    try
{
    using namespace mcl::ecdsa;
    init();
    Fp r;
    r.setByCSPRNG();
    Ec P;
    mcl::ec::tryAndIncMapTo(P, r);
    printf("P=%s\n", P.getStr().c_str());
} catch (std::exception& e) {
    printf("err %s\n", e.what());
    return 1;
}

Or

#include <mcl/bn.hpp>

int main()
    try
{
    using namespace mcl::bn;
    bool b;
    initG1only(&b, mcl::ecparam::secp256k1);
    if (!b) {
        puts("ERR");
        return 1;
    }
    Fp r;
    r.setByCSPRNG();
    G1 P;
    mapToG1(P, r);
    printf("P=%s\n", P.getStr().c_str());
} catch (std::exception& e) {
    printf("err %s\n", e.what());
    return 1;
}
XinwenXiang commented 1 year ago

I have tried above, and I want to ask:

  1. r is setByCSPRNG, it shoule be a rand number less than the Group order of secp256k1, if tryAndIncMap() same as maptoG1()?

  2. Both file print P=1, it means P is the base point of G1? image

herumi commented 1 year ago

The first 1 means that the following strings are affine coordinates. https://github.com/herumi/mcl/blob/master/api.md#string-conversion

1 <x> <y> ; affine coordinate
herumi commented 1 year ago

r is setByCSPRNG, it shoule be a rand number less than the Group order of secp256k1, if tryAndIncMap() same as maptoG1()?

The r is an element of the base field of G1, so it may be greater than the group order. tryAndIncMap() is same as maptoG1() for secp256k1 on the current version.

XinwenXiang commented 1 year ago

got it! thanks for your answer