aboutsummaryrefslogtreecommitdiffstats
path: root/src/bls.cpp
blob: c4a3e691d863645083d03504ba0b0f8a36a87600 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/**
    @file
    @author MITSUNARI Shigeo(@herumi)
    @license modified new BSD license
    http://opensource.org/licenses/BSD-3-Clause
*/
#include <cybozu/crypto.hpp>
#include <cybozu/random_generator.hpp>
#include <vector>
#include <string>
#include <bls/bls.hpp>
#if BLS_MAX_OP_UNIT_SIZE == 4
#include <mcl/bn256.hpp>
using namespace mcl::bn256;
#elif BLS_MAX_OP_UNIT_SIZE == 6
#include <mcl/bn384.hpp>
using namespace mcl::bn384;
#else
    #error "define BLS_MAX_OP_UNIT_SIZE 4(or 6)"
#endif

typedef std::vector<Fr> FrVec;

#define PUT(x) std::cout << #x << "=" << x << std::endl;

static cybozu::RandomGenerator& getRG()
{
    static cybozu::RandomGenerator rg;
    return rg;
}

const std::vector<Fp6> *g_pQcoeff;
const G2 *g_pQ;

namespace bls {

static const G2& getQ() { return *g_pQ; }
static const std::vector<Fp6>& getQcoeff() { return *g_pQcoeff; }

static void HashAndMapToG1(G1& P, const std::string& m)
{
    Fp t;
    t.setMsg(m);
    BN::mapToG1(P, t);
}

template<class T, class G, class Vec>
void evalPoly(G& y, const T& x, const Vec& c)
{
    if (c.size() < 2) throw cybozu::Exception("bls:evalPoly:bad size") << c.size();
    y = c[c.size() - 1];
    for (int i = (int)c.size() - 2; i >= 0; i--) {
        G::mul(y, y, x);
        G::add(y, y, c[i]);
    }
}

template<class T, class G>
struct WrapArray {
    const T *v;
    size_t k;
    WrapArray(const T *v, size_t k) : v(v), k(k) {}
    const G& operator[](size_t i) const
    {
        return v[i].getInner().get();
    }
    size_t size() const { return k; }
};

struct Polynomial {
    FrVec c; // f[x] = sum_{i=0}^{k-1} c[i] x^i
    void init(const Fr& s, int k)
    {
        if (k < 2) throw cybozu::Exception("bls:Polynomial:init:bad k") << k;
        c.resize(k);
        c[0] = s;
        for (size_t i = 1; i < c.size(); i++) {
            c[i].setRand(getRG());
        }
    }
    // y = f(id)
    void eval(Fr& y, const Fr& id) const
    {
        if (id.isZero()) throw cybozu::Exception("bls:Polynomial:eval:id is zero");
        evalPoly(y, id, c);
    }
};

namespace impl {

struct Id {
    Fr v;
    const Fr& get() const { return v; }
};

struct SecretKey {
    Fr s;
    const Fr& get() const { return s; }
};

struct Signature {
    G1 sHm; // s Hash(m)
    const G1& get() const { return sHm; }
};

struct PublicKey {
    G2 sQ;
    const G2& get() const { return sQ; }
    void getStr(std::string& str) const
    {
        sQ.getStr(str, mcl::IoArrayRaw);
    }
};

} // mcl::bls::impl

/*
    recover f(0) by { (x, y) | x = S[i], y = f(x) = vec[i] }
*/
template<class G, class V1, class V2>
void LagrangeInterpolation(G& r, const V1& vec, const V2& S)
{
    /*
        delta_{i,S}(0) = prod_{j != i} S[j] / (S[j] - S[i]) = a / b
        where a = prod S[j], b = S[i] * prod_{j != i} (S[j] - S[i])
    */
    const size_t k = S.size();
    if (vec.size() != k) throw cybozu::Exception("bls:LagrangeInterpolation:bad size") << vec.size() << k;
    if (k < 2) throw cybozu::Exception("bls:LagrangeInterpolation:too small size") << k;
    FrVec delta(k);
    Fr a = S[0];
    for (size_t i = 1; i < k; i++) {
        a *= S[i];
    }
    for (size_t i = 0; i < k; i++) {
        Fr b = S[i];
        for (size_t j = 0; j < k; j++) {
            if (j != i) {
                Fr v = S[j] - S[i];
                if (v.isZero()) throw cybozu::Exception("bls:LagrangeInterpolation:S has same id") << i << j;
                b *= v;
            }
        }
        delta[i] = a / b;
    }

    /*
        f(0) = sum_i f(S[i]) delta_{i,S}(0)
    */
    r.clear();
    G t;
    for (size_t i = 0; i < delta.size(); i++) {
        G::mul(t, vec[i], delta[i]);
        r += t;
    }
}

template<class T>
std::ostream& writeAsHex(std::ostream& os, const T& t)
{
    std::string str;
    t.getStr(str, mcl::IoHexPrefix);
    return os << str;
}

void init(int curve, int maxUnitSize)
{
    if (maxUnitSize != BLS_MAX_OP_UNIT_SIZE) throw cybozu::Exception("bls:init:bad maxUnitSize") << maxUnitSize << BLS_MAX_OP_UNIT_SIZE;
    mcl::bn::CurveParam cp;
    switch (curve) {
    case bls::CurveFp254BNb:
        cp = mcl::bn::CurveFp254BNb;
        break;
#if BLS_MAX_OP_UNIT_SIZE == 6
    case bls::CurveFp382_1:
        cp = mcl::bn::CurveFp382_1;
        break;
    case bls::CurveFp382_2:
        cp = mcl::bn::CurveFp382_2;
        break;
#endif
    default:
        throw cybozu::Exception("bls:init:bad curve") << curve;
    }
    BN::init(cp);
    G1::setCompressedExpression();
    G2::setCompressedExpression();
    Fr::init(BN::param.r);
//  mcl::setIoMode(mcl::IoHeximal);
    assert(sizeof(Id) == sizeof(impl::Id));
    assert(sizeof(SecretKey) == sizeof(impl::SecretKey));
    assert(sizeof(PublicKey) == sizeof(impl::PublicKey));
    assert(sizeof(Signature) == sizeof(impl::Signature));
    static G2 Q;
    if (curve == bls::CurveFp254BNb) {
        Q.set(
            Fp2("12723517038133731887338407189719511622662176727675373276651903807414909099441", "4168783608814932154536427934509895782246573715297911553964171371032945126671"),
            Fp2("13891744915211034074451795021214165905772212241412891944830863846330766296736", "7937318970632701341203597196594272556916396164729705624521405069090520231616")
        );
    } else {
        BN::mapToG2(Q, 1);
    }
    static std::vector<Fp6> Qcoeff;

    BN::precomputeG2(Qcoeff, Q);
    g_pQ = &Q;
    g_pQcoeff = &Qcoeff;
}
size_t getOpUnitSize()
{
    return Fp::getUnitSize() * sizeof(mcl::fp::Unit) / sizeof(uint64_t);
}

void getCurveOrder(std::string& str)
{
    Fr::getModulo(str);
}
void getFieldOrder(std::string& str)
{
    Fp::getModulo(str);
}

Id::Id(unsigned int id)
{
    getInner().v = id;
}

bool Id::operator==(const Id& rhs) const
{
    return getInner().v == rhs.getInner().v;
}

std::ostream& operator<<(std::ostream& os, const Id& id)
{
    return writeAsHex(os, id.getInner().v);
}

std::istream& operator>>(std::istream& is, Id& id)
{
    return is >> id.getInner().v;
}
void Id::getStr(std::string& str, int ioMode) const
{
    getInner().v.getStr(str, ioMode);
}
void Id::setStr(const std::string& str, int ioMode)
{
    getInner().v.setStr(str, ioMode);
}

bool Id::isZero() const
{
    return getInner().v.isZero();
}

void Id::set(const uint64_t *p)
{
    getInner().v.setArrayMask(p, keySize);
}

void Id::setLittleEndian(const void *buf, size_t bufSize)
{
    getInner().v.setArrayMask((const char *)buf, bufSize);
}

bool Signature::operator==(const Signature& rhs) const
{
    return getInner().sHm == rhs.getInner().sHm;
}

std::ostream& operator<<(std::ostream& os, const Signature& s)
{
    return writeAsHex(os, s.getInner().sHm);
}

std::istream& operator>>(std::istream& os, Signature& s)
{
    return os >> s.getInner().sHm;
}
void Signature::getStr(std::string& str, int ioMode) const
{
    getInner().sHm.getStr(str, ioMode);
}
void Signature::setStr(const std::string& str, int ioMode)
{
    getInner().sHm.setStr(str, ioMode);
}

bool Signature::verify(const PublicKey& pub, const std::string& m) const
{
    G1 Hm;
    HashAndMapToG1(Hm, m); // Hm = Hash(m)
#if 1
    /*
        e(P1, Q1) == e(P2, Q2)
        <=> finalExp(ML(P1, Q1)) == finalExp(ML(P2, Q2))
        <=> finalExp(ML(P1, Q1) / ML(P2, Q2)) == 1
        <=> finalExp(ML(P1, Q1) * ML(-P2, Q2)) == 1
        2.1Mclk => 1.5Mclk
    */
    Fp12 e;
    std::vector<Fp6> Q2coeff;
    BN::precomputeG2(Q2coeff, pub.getInner().sQ);
    BN::precomputedMillerLoop2(e, getInner().sHm, getQcoeff(), -Hm, Q2coeff);
    BN::finalExp(e, e);
    return e.isOne();
#else
    Fp12 e1, e2;
    BN::pairing(e1, getInner().sHm, getQ()); // e(s Hm, Q)
    BN::pairing(e2, Hm, pub.getInner().sQ); // e(Hm, sQ)
    return e1 == e2;
#endif
}

bool Signature::verify(const PublicKey& pub) const
{
    std::string str;
    pub.getInner().sQ.getStr(str);
    return verify(pub, str);
}

void Signature::recover(const SignatureVec& sigVec, const IdVec& idVec)
{
    if (sigVec.size() != idVec.size()) throw cybozu::Exception("Signature:recover:bad size") << sigVec.size() << idVec.size();
    recover(sigVec.data(), idVec.data(), sigVec.size());
}

void Signature::recover(const Signature* sigVec, const Id *idVec, size_t n)
{
    WrapArray<Signature, G1> signW(sigVec, n);
    WrapArray<Id, Fr> idW(idVec, n);
    LagrangeInterpolation(getInner().sHm, signW, idW);
}

void Signature::add(const Signature& rhs)
{
    getInner().sHm += rhs.getInner().sHm;
}

bool PublicKey::operator==(const PublicKey& rhs) const
{
    return getInner().sQ == rhs.getInner().sQ;
}

std::ostream& operator<<(std::ostream& os, const PublicKey& pub)
{
    return writeAsHex(os, pub.getInner().sQ);
}

std::istream& operator>>(std::istream& is, PublicKey& pub)
{
    return is >> pub.getInner().sQ;
}

void PublicKey::getStr(std::string& str, int ioMode) const
{
    getInner().sQ.getStr(str, ioMode);
}
void PublicKey::setStr(const std::string& str, int ioMode)
{
    getInner().sQ.setStr(str, ioMode);
}
void PublicKey::set(const PublicKey *mpk, size_t k, const Id& id)
{
    WrapArray<PublicKey, G2> w(mpk, k);
    evalPoly(getInner().sQ, id.getInner().v, w);
}

void PublicKey::recover(const PublicKeyVec& pubVec, const IdVec& idVec)
{
    if (pubVec.size() != idVec.size()) throw cybozu::Exception("PublicKey:recover:bad size") << pubVec.size() << idVec.size();
    recover(pubVec.data(), idVec.data(), pubVec.size());
}
void PublicKey::recover(const PublicKey *pubVec, const Id *idVec, size_t n)
{
    WrapArray<PublicKey, G2> pubW(pubVec, n);
    WrapArray<Id, Fr> idW(idVec, n);
    LagrangeInterpolation(getInner().sQ, pubW, idW);
}

void PublicKey::add(const PublicKey& rhs)
{
    getInner().sQ += rhs.getInner().sQ;
}

bool SecretKey::operator==(const SecretKey& rhs) const
{
    return getInner().s == rhs.getInner().s;
}

std::ostream& operator<<(std::ostream& os, const SecretKey& sec)
{
    return writeAsHex(os, sec.getInner().s);
}

std::istream& operator>>(std::istream& is, SecretKey& sec)
{
    return is >> sec.getInner().s;
}
void SecretKey::getStr(std::string& str, int ioMode) const
{
    getInner().s.getStr(str, ioMode);
}
void SecretKey::setStr(const std::string& str, int ioMode)
{
    getInner().s.setStr(str, ioMode);
}

void SecretKey::init()
{
    getInner().s.setRand(getRG());
}

void SecretKey::set(const uint64_t *p)
{
    getInner().s.setArrayMask(p, keySize);
}
void SecretKey::setLittleEndian(const void *buf, size_t bufSize)
{
    getInner().s.setArrayMask((const char *)buf, bufSize);
}

void SecretKey::getPublicKey(PublicKey& pub) const
{
    G2::mul(pub.getInner().sQ, getQ(), getInner().s);
}

void SecretKey::sign(Signature& sig, const std::string& m) const
{
    G1 Hm;
    HashAndMapToG1(Hm, m);
//  G1::mul(sig.getInner().sHm, Hm, getInner().s);
    G1::mulCT(sig.getInner().sHm, Hm, getInner().s);
}

void SecretKey::getPop(Signature& pop) const
{
    PublicKey pub;
    getPublicKey(pub);
    std::string m;
    pub.getInner().sQ.getStr(m);
    sign(pop, m);
}

void SecretKey::getMasterSecretKey(SecretKeyVec& msk, size_t k) const
{
    if (k <= 1) throw cybozu::Exception("bls:SecretKey:getMasterSecretKey:bad k") << k;
    msk.resize(k);
    msk[0] = *this;
    for (size_t i = 1; i < k; i++) {
        msk[i].init();
    }
}

void SecretKey::set(const SecretKey *msk, size_t k, const Id& id)
{
    WrapArray<SecretKey, Fr> w(msk, k);
    evalPoly(getInner().s, id.getInner().v, w);
}

void SecretKey::recover(const SecretKeyVec& secVec, const IdVec& idVec)
{
    if (secVec.size() != idVec.size()) throw cybozu::Exception("SecretKey:recover:bad size") << secVec.size() << idVec.size();
    recover(secVec.data(), idVec.data(), secVec.size());
}
void SecretKey::recover(const SecretKey *secVec, const Id *idVec, size_t n)
{
    WrapArray<SecretKey, Fr> secW(secVec, n);
    WrapArray<Id, Fr> idW(idVec, n);
    LagrangeInterpolation(getInner().s, secW, idW);
}

void SecretKey::add(const SecretKey& rhs)
{
    getInner().s += rhs.getInner().s;
}

} // bls