cost_pairing.py 24.1 KB
Newer Older
MASSON Simon's avatar
MASSON Simon committed
1 2 3 4
from sage.all_cmdline import *
from CocksPinchVariant import *
import sage.rings.integer
from BLS12 import *
Emmanuel Thomé's avatar
Emmanuel Thomé committed
5
# from BLS24 import *
MASSON Simon's avatar
MASSON Simon committed
6
from KSS16 import *
Emmanuel Thomé's avatar
Emmanuel Thomé committed
7
# from KSS18 import *
MASSON Simon's avatar
MASSON Simon committed
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
from BN import *
from MNT6 import *
from final_expo_k57 import *


# Set this flag to make sure that the changes we've done to the
# computation code do *NOT* affect the costs that we had computed thus
# far.
#
# Once we check that, we are confident that the change in machinery did
# not introduce new bugs. Then we can set OLDCOUNTS to False (and delete
# the associated code when relevant).
OLDCOUNTS=False

# if OLDCOUNTS is True, these two are ignored (or are forced to False,
# so to say).
mystery_201903151748_simon_a_raison=False

# TODO: take into account h_t not always being 0 in the k=6 or k=8
# cases... [WIP for k=8 -- want to automate a bit]

Qmsi = QQ['m,s,inv']
m,s,inv = Qmsi.gens()

#F_{p^k} arithmetic cost

def cost_m(k) :
    # return the cost of a multiplication over F_{p^k}
    if k%2 == 0 :
        return 3*cost_m(k//2)
    elif k%3 == 0 :
        return 6*cost_m(k//3)
    elif k == 1:
        return m
    elif k == 5 :
        return 13*m
    elif k == 7 :
        return 22*m
    else :
        return 'not done for this embedding degree'
# special cases
def densexsparse_m6(k):
    assert k%6==0
    return 13*cost_m(k//6) # aurore thesis

def densexsparse_m8(k):
    assert k%8==0
    return 8*cost_m(k//4) # ??????????????????????BarDuq18???

sparse_m12 = 13*cost_m(2) # BarDuq 39 = 3*13 and 3 is the cost of Mp2 = 3 Mp
sparse_m16 = 8*cost_m(4)

def cost_s(k) :
    # return the cost of a square over F_{p^k}
    if k%2 == 0 :
        return 2*cost_m(k//2)
    elif k%3 == 0 :
        return 2*cost_m(k//3) + 3 * cost_s(k//3)
    elif k == 1:
        return m
    elif k == 5 :
        return 13*m
    elif k == 7 :
        return 22*m
    else :
        return 'not done for this embedding degree'
# special cases
cyclo_s6 = 3*cost_s(2) # eprint 2009/565
cyclo_s8 = 2*cost_s(4)  # eprint 2009/565 section 3.1
compr_s12 = 12*m # BarDuq
cyclo_s12 = 18*m
cyclo_s16 = 2*cost_s(8)

def cost_i(k) :
    # return the cost of an inversion over F_{p^k}
    if k%2 == 0 :
        return 2*cost_s(k//2) + 2*cost_m(k//2) + cost_i(k//2)
    elif k%3 == 0 :
        return 3*cost_s(k//3) + 9*cost_m(k//3) + cost_i(k//3)
    elif k == 1:
        return inv
#    elif k == 5 :
#        # u1 = frob(a)
#        # u2 = frob(u1)
#        # u3 = frob(u2)
#        # v = u1 * u3   # v = a^(p+p^3)
#        # w = frob(v)   # v = a^(p^2+p^4)
#        # b = v * w
#        # n = coeff(a,0)*coeff(b,0) + alpha*sum([coeff(a,i)*coeff(b,k-i) for i in range(1,k)])
#        # ni = inv(n)
#        # ai = ni * a
#        return 4*cost_f(k) + 2*cost_m(k) + inv + 2*k*m
#    elif k == 7 :
#        # u1 = frob(a)
#        # u2 = frob(u1)
#        # u3 = frob(u2)
#        # u4 = frob(u3)
#        # v = u1 * u4   # v = a^(p+p^4)
#        # w = frob(v)   # v = a^(p^2+p^5)
#        # z = frob(w)   # v = a^(p^3+p^6)
#        # b = v * w * z
#        # n = coeff(a,0)*coeff(b,0) + alpha*sum([coeff(a,i)*coeff(b,k-i) for i in range(1,k)])
#        # ni = inv(n)
#        # ai = ni * a
#        return 6*cost_f(k) + 3*cost_m(k) + inv + 2*k*m
    elif OLDCOUNTS and (k==5 or k==7):
        return (k-1)*cost_f(k) + (k-1)*cost_m(k) + inv
    elif k%2 == 1:
        # generalization of the above.
        # Note that we can go further. If (k-1)/2 >= 4, then we may apply
        # the same trick to save some more multiplications.
        return ((k+1)//2)*cost_f(k) + cost_m(k) + ((k-3)//2)*(cost_f(k)+cost_m(k)) + inv + 2*k*m
    # elif k == 5 or k == 7 :
    #   return (k-1)*cost_f(k) + (k-2)*cost_m(k) + inv + 2*k*m
    else :
        return 'not done for this embedding degree'

def cost_f(k, d=1) :
    # return the cost of a d-Frobenius over F_{p^k}
    assert k % d == 0
    if (k//d) % 2 == 0 and not OLDCOUNTS:
        # for F_{p^{k/d}} a tower defined by binomials, the multipliers in
        # the Frobenius (p^d-th power) expressions are all powers of a
        # k/d-th root of unity. If k/d is even, one of them is -1. At any
        # rate, this root of unity boils down to a scalar, therefore we
        # don't need cost_m(d) but really d * cost_m(1)
        return (k//d-2) * d * cost_m(1)
    else: 
        return (k//d-1) * d * cost_m(1)

def cost_i_and_f(k) :
    if OLDCOUNTS or k % 2 == 0 or k % 3 == 0:
        return cost_i(k) + cost_f(k)
    elif k == 5 or k == 7:
        # Then we know that the inversion computes the Frobenius anyway.
        return cost_i(k)
    else :
        return 'not done for this embedding degree'

def table_costFpk(k_list):
    K = ''.join(["&%d"%k for k in k_list])
    M = ''.join(["&%s"%cost_m(k)(m=1)+r"\bfm" for k in k_list])
    S = ''.join(["&%s"%cost_s(k)(m=1)+r"\bfm" for k in k_list])
    F = ''.join(["&%s"%cost_f(k)(m=1)+r"\bfm" for k in k_list])
    sc_dict = {6:cyclo_s6, 8:cyclo_s8, 12:cyclo_s12, 16:cyclo_s16}
    SC = ''.join(["&%s"%sc_dict[k](m=1)+r"\bfm" if k in sc_dict else "&" for k in k_list])
    I0 = ''.join(["&%s"%cost_i(k)(m=1,inv=0)+r"\bfm" for k in k_list])
    I1 = ''.join(["&%s"%cost_i(k)(m=1,inv=25)+r"\bfm" for k in k_list])
    M = M.replace(r"&1\bfm",r"&\bfm")
    S = S.replace(r"&1\bfm",r"&\bfm")
    I0 = I0.replace(r"&0\bfm",r"&0")
    contents = [
        r"$$\begin{array}{|c|" + "c|" * len(k_list) + "}",
        r"\hline",
        "k" + K + r"\\",
        r"\hline",
        r"\bfm_k" + M + r"\\",
        r"\bfs_k" + S + r"\\",
        r"\bff_k" + F + r"\\",
        r"\bfs_k^{\text{cyclo}}" + SC + r"\\",
        r"\bfi_k-\bfi_1" + I0 + r"\\",
        r"\text{$\bfi_k$, with $\bfi_1=25\bfm$}" + I1 + r"\\",
        r"\hline",
        r"\end{array}$$",
    ]
    print "% This table is generated by:"
Emmanuel Thomé's avatar
Emmanuel Thomé committed
174
    print "%% PYTHONPATH=cocks-pinch-variant/ sage -c 'load(\"cocks-pinch-variant/cost_pairing.py\"); table_costFpk(%s)'" % (k_list)
MASSON Simon's avatar
MASSON Simon committed
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

    for s in contents:
        print s
        
def Hw(x) :
    return len(bit_positions_2naf(x))

proof.arithmetic(False)
C5=CocksPinchVariantResult(5,10000000147,0xe000000000008000,1,ht=3,hy=-0x11e36418c7c8b454,max_B1=600)
C6=CocksPinchVariantResult(6,3,0xefffffffffffffe00000000000000000,1,ht=-1,hy=0xffbbffffffffffffc020,allowed_cofactor=420,allowed_size_cofactor=10,max_B1=600)
C7=CocksPinchVariantResult(7,20,0x5fffb820248,6,ht=-2,allowed_cofactor=1232,allowed_size_cofactor=10,max_B1=600)
C8=CocksPinchVariantResult(8,4,0xffffffffeff7c200,5,ht=5,hy=-0xd700,allowed_cofactor=420,allowed_size_cofactor=10,max_B1=600)

C8old=CocksPinchVariantResult(8,4,0xe000000000001010,5,ht=1,hy=0x177dc)
C6old=CocksPinchVariantResult(6,3,0xc0000000000000000040000000000000,5,hy=0x20000000000000000000f)
C5old=CocksPinchVariantResult(5,1001035,0xe000000000000036,4,ht=1,hy=0xb5f94915f3db71cae)
C7old=CocksPinchVariantResult(7,312916,0x60000000002,5,ht=-1)

if OLDCOUNTS:
    # Curves as they were at least on the printout I have here. But I'm
    # not sure these are the curves we used to base our counts on anyway.
    C5 = C5old
    C6 = C6old
    C7 = C7old
    C8 = C8old


CBN12=BN(eval(preparse("2^114+2^101-2^14-1")))
CBLS12=BLS12(eval(preparse("-2^77+2^50+2^33")))
CKSS16=KSS16(eval(preparse("2^35-2^32-2^18+2^8+1")))
C1=Integer(3072)

def finite_field_cost(logp):
    #time_m
    words = ceil(RR(logp)/64)
    if words == 5 :
        time_m = 35 #relic benchmark
    if words == 6 :
        time_m = 69 #relic benchmark
    if words == 8 :
        if OLDCOUNTS:
            time_m = 130 #relic benchmark
        else:
            time_m = 120 #relic benchmark
    elif words == 9 :
        time_m = 1.9*9**2
    elif words == 10 :
        time_m = 188 #relic benchmark
    elif words == 11 :
        time_m = 1.9*11**2
    elif words == 48 :
        time_m = 4882 #gmp benchmark
    return time_m

def is_one_of_our_known_pairing_friendly_curves(C):
    return isinstance(C, BN) or \
            isinstance(C, BLS12) or \
            isinstance(C, KSS16) or \
            isinstance(C, MNT6) or \
            False;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
235 236
    # isinstance(C, BLS24) or \
    # isinstance(C, KSS18) or \
MASSON Simon's avatar
MASSON Simon committed
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

def polymorphic_get_logp(C):
    if is_one_of_our_known_pairing_friendly_curves(C):
        return C.p().nbits()
    elif isinstance(C, CocksPinchVariantResult):
        return ZZ(C.p).nbits()
    elif isinstance(C, Integer):
        return C
    else:
        raise ValueError("not implemented")

def polymorphic_get_logr(C):
    if is_one_of_our_known_pairing_friendly_curves(C):
        return C.r().nbits()
    elif isinstance(C, CocksPinchVariantResult):
        return ZZ(C.r).nbits()
    elif isinstance(C, Integer):
        return 256
    else:
        raise ValueError("not implemented")

def polymorphic_get_name(C):
    if isinstance(C, CocksPinchVariantResult):
        return "$k=%s$" % C.k
    elif isinstance(C, BN):
        return 'BN'
    elif isinstance(C, MNT6):
        return 'MNT6'
    elif isinstance(C, BLS12):
        return 'BLS12'
Emmanuel Thomé's avatar
Emmanuel Thomé committed
267 268
    # elif isinstance(C, BLS24):
    #     return 'BLS24'
MASSON Simon's avatar
MASSON Simon committed
269 270
    elif isinstance(C, KSS16):
        return 'KSS16'
Emmanuel Thomé's avatar
Emmanuel Thomé committed
271 272
    # elif isinstance(C, KSS18):
    #    return 'KSS18'
MASSON Simon's avatar
MASSON Simon committed
273 274 275 276 277 278 279 280 281 282
    elif isinstance(C, Integer):
        return '$k=1$'
    else:
        raise ValueError("not implemented")

def polymorphic_get_miller_loop_length(C):
    if isinstance(C, CocksPinchVariantResult):
        return C.T
    elif isinstance(C, BN):
        return 6*C.u()+2
Emmanuel Thomé's avatar
Emmanuel Thomé committed
283
    elif isinstance(C, BLS12): # or isinstance(C, BLS24):
MASSON Simon's avatar
MASSON Simon committed
284
        return C.tr() - 1
Emmanuel Thomé's avatar
Emmanuel Thomé committed
285
    elif isinstance(C, KSS16): # or isinstance(C, KSS18):
MASSON Simon's avatar
MASSON Simon committed
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 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        return C.u()
    elif isinstance(C, MNT6):
        # lazy me
        raise ValueError("not implemented")
    elif isinstance(C, Integer):
        raise ValueError("not implemented")
    else:
        raise ValueError("not implemented")

def polymorphic_get_embedding_degree(C):
    if isinstance(C, CocksPinchVariantResult):
        return C.k
    elif is_one_of_our_known_pairing_friendly_curves(C):
        return C.k()
    elif isinstance(C, Integer):
        return 1
    else:
        raise ValueError("not implemented")

def polymorphic_get_fD(C):
    if isinstance(C, CocksPinchVariantResult):
        return C.fD
    elif is_one_of_our_known_pairing_friendly_curves(C):
        # no public accessor :-(
        return C._D
    elif isinstance(C, Integer):
        return 1
    else:
        raise ValueError("not implemented")


def millerLoopCost(C):
    k = polymorphic_get_embedding_degree(C)
    D = polymorphic_get_fD(C)
    name = polymorphic_get_name(C)

    # k, D, name, logp, logT, HwT) :

    #extra computations for BN, BLS and KSS (see BarDuq Table2)
    miller_fixup = 0
    
    if k == 5 or k == 7 :
        cost_addline = 10*cost_m(k) + 3*cost_s(k)
        cost_doubleline = 6*cost_m(k) + 4*cost_s(k) + 2*k*cost_m(1)
        cost_verticalline = k*cost_m(1)
        cost_update1 = 4*cost_m(k) + 2*cost_s(k)
        cost_update2 = 4*cost_m(k)
    elif k == 6 and D == 3 :
        cost_addline =   10*cost_m(k//6) + 2*cost_s(k//6) + (k//3)*cost_m(1)
        cost_doubleline = 2*cost_m(k//6) + 7*cost_s(k//6) + (k//3)*cost_m(1)
        cost_verticalline = 0
        cost_update1 = cost_s(k)+densexsparse_m6(k)
        cost_update2 = densexsparse_m6(k)
    elif k%4 == 0 and D == 4 :
        cost_addline =    9*cost_m(k//4) + 5*cost_s(k//4) + (k//2)*cost_m(1)
        cost_doubleline = 2*cost_m(k//4) + 8*cost_s(k//4) + (k//2)*cost_m(1)
        cost_verticalline = 0
        cost_update1 = cost_s(k)+densexsparse_m8(k)
        cost_update2 = densexsparse_m8(k)
        if name == 'KSS16' : # extra partial add and partial double + 3 frob and 2 multiplications
            if not OLDCOUNTS and mystery_201903151748_simon_a_raison:
                miller_fixup = (cost_m(k//4) + 5 *cost_s(k//4) + k//2 * cost_m(1)) + \
                             + (5*cost_m(k//4) + 2*cost_s(k//4) + k//2 * cost_m(1))
            else:
                miller_fixup = 5*cost_m(k//4) + cost_s(k//4) + k  * cost_m(1)

            miller_fixup += 3*cost_f(k) + 2*sparse_m16
    elif k == 12 and D == 3:
        cost_doubleline = 3*cost_m(k//6) + 6*cost_s(k//6) + (k//3)*cost_m(1)
        cost_addline = 11*cost_m(k//6) + 2*cost_s(k//6) + (k//3)*cost_m(1)
        cost_verticalline = 0
        cost_update1 = cost_s(k)+densexsparse_m6(k)
        cost_update2 = densexsparse_m6(k)
        if name == 'BN':
            # for Q1 = [p]Q and Q2=[p]Q1
            # first extra add
            # second light add
            # 2 multiplications
            miller_fixup = 4*cost_f(k) + \
                         + cost_addline + \
                         + 4*cost_m(k//6) + 4*cost_m(1) + \
                         + 2*sparse_m12 
    elif k == 1:
        cost_addline=None
        cost_doubleline=None
        cost_verticalline=None
        cost_update1=None
        cost_update2=None
        tot_miller = 4626 * m + cost_i(k)
        
    if k!= 1 :
        T = polymorphic_get_miller_loop_length(C)
        logT = T.nbits()
        HwT = Hw(T)

        if OLDCOUNTS:
            if k==8:
                HwT=3

        tot_miller = (logT-1) * (cost_doubleline + cost_verticalline) \
                         + (logT-2) * cost_update1 \
                         + (HwT-1) * (cost_addline + cost_verticalline + cost_update2) \
                         + (cost_i(k) if k%2==1 else 0) \
                         + miller_fixup

    return [cost_addline, cost_doubleline, cost_verticalline, cost_update1, cost_update2, ZZ(tot_miller(m=1,s=1,inv=25))]

def cost_firstexp(k):
    assert k in [5,6,7,8]
    if Integer(k).is_prime():
        return cost_i_and_f(k)+cost_m(k)
    if OLDCOUNTS and k==6 :
        return 4*cost_f(k) + cost_i(k) + 3*cost_m(k)
    if k == 6 :
        # a <- a^(1+p)
        c0 = cost_f(k) + cost_m(k)
        # a = a0 + a1y ; a^(p^3) = a0-a1y ; norm_{6/3}(a) = a0^2-y^2a1^2
        # with cheap multiplication by y^2; then a^(p^3-1) =
        # 1/norm*(a0^2+y^2a1^2-2ya0a1)
        c1 = 2*cost_s(k//2)
        c1 += cost_m(k//2)
        c1 += cost_i(k//2)
        c1 += 2*cost_m(k//2)
        return c0 + c1
    if k == 8 :
        return cost_i(k) + cost_m(k)

def finalExpoCost(C):
    k = polymorphic_get_embedding_degree(C)
    name = polymorphic_get_name(C)

    if isinstance(C, Integer):
        tot_expo = 4100 * cost_m(1)
        return tot_expo(m=1,s=1,inv=25)
    elif name == 'BN':
        BN_expo_z = 4*(114 - 1)*cost_m(2) + (6*3 - 3)*cost_m(2) + 3*cost_m(12) + 3*3*cost_s(2) + cost_i(2)
        #BarDuq says 114*compr_s12 + 3* cost_m(12) + (i + (24*4 - 5)*cost_m(1))
        tot_expo = cost_i(12) + 12*cost_m(12) + 3*cyclo_s12 + 4* cost_f(12) + 3*BN_expo_z
        return tot_expo(m=1,s=1,inv=25)
    elif name == 'BLS12':
        BLS_expo_z = 4*(77 - 1)*cost_m(2)+ (6*1 - 3)*cost_m(2) + 2*cost_m(12) + 3*2*cost_s(2) + cost_i(2)
        #BarDuq says 77*compr_s12 + 2*cost_m(12) + (i + (24*3 - 5)*cost_m(1))
        tot_expo = cost_i(12) + 12*cost_m(12) + 2*cyclo_s12 + 4*cost_f(12) + 5*BLS_expo_z
        return tot_expo(m=1,s=1,inv=25)
    elif name == 'KSS16':
        KSS16_expo_z = 34*cyclo_s16 + 4*cost_m(16)
        tot_expo = 34*cyclo_s16 + 32*cost_m(16)+24*cost_m(4)+8*cost_f(16)+cost_i(16) + 9*KSS16_expo_z
        return tot_expo(m=1,s=1,inv=25)

    if not isinstance(C, CocksPinchVariantResult):
        # FE for MNT6 BLS24 KSS18 not done
        raise ValueError("not implemented")

    logp = C.p.nbits()
    logr = C.r.nbits()
    T = C.T
    D = C.fD
    i = C.i
    logT = T.nbits()
    HwT = Hw(T)
    HwCofr=Hw(C.twist(0)['card']//C.r)
    hy = ZZ(C.hy)
    ht = ZZ(C.ht)
    loghy=hy.nbits(); Hwhy=Hw(hy)
    loght=ht.nbits(); Hwht=Hw(ht)


    if OLDCOUNTS:
        if k==5:
            logp=665
            HwCofr=206
        elif k==7:
            HwCofr=133
            # This had us trip over word size limits.
            logp=513
        elif k==8:
            HwT=3
            loghy=18

    c1 = cost_firstexp(k)

    # Now compute c2 (second part of FE)
    if k==5 or k==7:
        assert isinstance(C, CocksPinchVariantResult)

        cost_T = (logT-1)*cost_s(k) +  (HwT-1)*cost_m(k)

        if OLDCOUNTS:
            # number of frobenius exponentiations in the second part
            c_frobenius = (k - 2) * cost_f(k)
            c2 = c_frobenius

            # k-2 exponentations to T:
            c2 += (k - 2) * cost_T
            # exponentation to cofactor c:
            logc = logp - logr
            c2 += (logc -1)*cost_s(k) + (HwCofr-1)*cost_m(k)

            # FIXME: the formulas below are not generic. They're specific
            # to one chosen value of i. And among the different
            # possibilities, i=1 is arguably nicest, so that we're
            # tempted to use that as a default. Maybe it's unwanted
            # pressure for the k=7 case, though.

            # multiplying together the (k - 2) terms costs (k - 3) M:
            c2 += (k - 3)*cost_m(k)
            ### XXX ? really ? I count (k-1) terms, not (k-2)

            # assume one inversion costs (k-1) Frobenius since the norm is 1 at this point
            if OLDCOUNTS:
                cost_inv_torus = (k-1) * c_frobenius
            else:
                # 99% sure that the formula above is a bug.
                cost_inv_torus = (k-1) * cost_f(k)

            # This adds (k-1)*cost_m(k) (don't know where this comes
            # from, but anyway this seems to match our 2(k-2)) and
            # cost_inv_torus, which I think is potentially unneeded
            if k == 5:
                c2 += 4*cost_m(k) + cost_inv_torus
            elif k == 7:
                c2 += 6*cost_m(k) + 3*cost_inv_torus
            # checked in sage, see params-k7-512.sage and params-k5-664.sage
        else:
            # see final-expo-k57.sage
            c2 = (k-2)*(cost_f(k) + cost_T + 2*cost_m(k)) + cost_m(k)
            logc = logp - logr
            c2 += (logc -1)*cost_s(k) + (HwCofr-1)*cost_m(k)
            # one inversion costs (k-1) Frobenius since norm == 1
            cost_inv_torus = (k-1) * cost_f(k)
            if i > 1:
                c2 += cost_inv_torus
                if i < k-1 and 2*i > k:
                    # this just happens to match the formulas that we have.
                    c2 += cost_inv_torus
            # cost for k=5 i=1: 1c + 3T + 7M + 3p
            # cost for k=5 i=2: 1I + 1c + 3T + 7M + 3p
            # cost for k=5 i=3: 2I + 1c + 3T + 7M + 3p
            # cost for k=5 i=4: 1I + 1c + 3T + 7M + 3p
            # cost for k=7 i=1: 1c + 5T + 11M + 5p
            # cost for k=7 i=2: 1I + 1c + 5T + 11M + 5p
            # cost for k=7 i=3: 1I + 1c + 5T + 11M + 5p
            # cost for k=7 i=4: 2I + 1c + 5T + 11M + 5p
            # cost for k=7 i=5: 2I + 1c + 5T + 11M + 5p
            # cost for k=7 i=6: 1I + 1c + 5T + 11M + 5p
    elif k == 6 :

        # See:
        # sage: attach("formules-familles-CocksPinch.sage")
        # sage: formulas(6)

        assert D==3

        if OLDCOUNTS:
            c_exp_T = (logT-1)*cyclo_s6 + (HwT-1)*cost_m(k)
            c_exp_hy = (loghy-1)*cyclo_s6 + (Hwhy-1)*cost_m(k)

            c21 = 2*c_exp_T + 2*c_exp_hy + cyclo_s6 + 5*cost_m(k)
            c22 = 0
            c23 = c_exp_T + cost_f(k) + cyclo_s6 + 4*cost_m(k)

    #
    #        c21 = 2*c_exp_T + 2*c_exp_hy + 5*cyclo_s6 + 8*cost_m(k) #  + cost_i(k) NO inversions are free at this point
    #        c22 = c_exp_T + cost_m(k) #  + cost_i(k) NO inversion
    #        c23 = 2*cost_m(k) + cost_f(k)
            
            c2 = c21 + c22+c23
        else:
            # start with this:

            c_exp_T = (logT-1)*cyclo_s6 + (HwT-1)*cost_m(k)
            c2 = c_exp_T + cost_f(k) + cyclo_s6 + 4*cost_m(k)
            if i == 5:
                # extra cost for raising to the power p+t0 = p+2-T: we
                # need a square...
                c2 += cyclo_s6

            # Then, see code/formules-familles-CocksPinch.sage
            # it's a slight mess, to be honest.

            assert (1 + ht + hy) % 2 == 0
            if ht % 2 == 0:
                hu = ht//2
                hz = -1 if T%3 == 0 else 1
                hw = (hy-hz)//2
            else:
                hu = (ht+1)//2
		hw = hy//2
            U = T - (T % 3)
            logU=U.nbits(); HwU=Hw(U)
            loghu=hu.nbits(); Hwhu=Hw(hu)
            loghw=hw.nbits(); Hwhw=Hw(hw)
            c_exp_U = (logU-1)*cyclo_s6 + (HwU-1)*cost_m(k)
            c_exp_hu = (loghu-1)*cyclo_s6 + (Hwhu-1)*cost_m(k)
            c_exp_hw = (loghw-1)*cyclo_s6 + (Hwhw-1)*cost_m(k)

            c2 += 12*cost_m(k) + 2*cost_s(k) + 2*(c_exp_U + c_exp_hu + c_exp_hw)
    elif k == 8 :
        # See:
        # sage: attach("formules-familles-CocksPinch.sage")
        # sage: formulas(8)

        assert D==4
        assert T%2==0
        assert ht % 2 == 1

        # t0 is odd, so that ht must be odd too. Raising to the power
        # ht+1 or ht-1 costs at most as much as raising to the power ht,
        # and maybe one multiplication less. Note also that ht+1 is
        # necessarily even.

        if OLDCOUNTS:
            c21 = 0 # c21 = 2*cost_s(k)
            c_exp_hy = (loghy-1)*cyclo_s8 + (Hwhy-1)*cost_m(k)
            c_exp_T = (logT-1)*cyclo_s8 + (HwT-1)*cost_m(k)
            c22 = 2*c_exp_hy + 4*c_exp_T + 6*cost_m(k) #+ 3*cyclo_s8 not needed if we compute C/4 instead of C
            c23 = 3*c_exp_T + 3*cost_f(8) + 3*cost_m(k) #+ 2*cost_i(k) inversions are free at this point !
            c24 = 0 # c24 = cost_m(k)
            
            c2 = c21+c22+c23+c24
        else:
            c_exp_T = (logT-1)*cyclo_s8 + (HwT-1)*cost_m(k)

            # first, this: (because phi_8(p)/r = 1 + c(T^2+p^2)(p-T))
            c2 = 3*c_exp_T + 2*cost_f(8) + 3*cost_m(k)

            # Then, see code/formules-familles-CocksPinch.sage

            # for raising to the power c, we get:
            # 11M + 2u + 4T + 2y
            # with one of the multiplies that (for i=3 and i=7) can be
            # elided if T=0 mod 4. This is with u = multiplication by
            # (h_t+1)//2.
            hu = (ht+1)//2;
            loghu=hu.nbits(); Hwhu=Hw(hu)
            c_exp_hy = (loghy-1)*cyclo_s8 + (Hwhy-1)*cost_m(k)
            c_exp_hu = (loghu-1)*cyclo_s8 + (Hwhu-1)*cost_m(k)

            c2 += 4 * c_exp_T + 2 * c_exp_hu + 2 * c_exp_hy + 10 * cost_m(k)
            if (T%4 == 2 or i == 1 or i == 5):
                c2 += cost_m(k)

    tot_expo = c1 + c2
    
    return tot_expo(m=1,s=1,inv=25)

def pairingCost(C):
    costMiller = millerLoopCost(C)
    costFinalExp = finalExpoCost(C)
    
    logp = polymorphic_get_logp(C)
    if OLDCOUNTS:
        k = polymorphic_get_embedding_degree(C)
        if k==5:
            logp=665
        elif k==7:
            logp=513

    time_m = finite_field_cost(logp)

    tot_miller = costMiller[-1]
    time_miller = round(tot_miller * time_m/1000000, 1)
    tot_expo = costFinalExp
    time_expo = round(tot_expo * time_m/1000000, 1)
    return dict(
		k=polymorphic_get_embedding_degree(C),
		D=polymorphic_get_fD(C),
                name=polymorphic_get_name(C),
		logp=polymorphic_get_logp(C),
		time_m=time_m,
		tot_miller=tot_miller,
		time_miller=time_miller,
		tot_expo=tot_expo,
		time_expo=time_expo,
                tot_pairing = tot_miller + tot_expo,
                time_pairing = round(time_miller+time_expo, 1),
                )

def table_cost_pairing() :
    timing_recap = []
    
    for C in [C5,C6,C7,C8,CBN12,CBLS12,CKSS16,C1]:
        L=pairingCost(C)

        if OLDCOUNTS:
            if L['k'] == 7:
                scale = 130/L['time_m']
                for kk in L.keys():
                    if re.match("^time_.*", kk):
                        L[kk] = round(L[kk] * scale, 1)

        timing_recap.append(L)
        
    #timing recap is generated

    print "% This table is generated by:"
682
    print "% PYTHONPATH=cocks-pinch-variant sage -c 'load(\"cocks-pinch-variant/cost_pairing.py\"); table_cost_pairing()'"
MASSON Simon's avatar
MASSON Simon committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700

    def wrap_cell(cell):
        return "\\begin{tabular}{@{}c@{}} %s \\end{tabular}" % cell

    for L in timing_recap :
        cell0 = "%s & %d-bit" % (L['name'], L['logp'])

        cell_miller = "%d\\bfm \\\\ %sms" % (L['tot_miller'], L['time_miller'])
        cell_miller = wrap_cell(cell_miller)

        cell_expo = "%d\\bfm \\\\ %sms" % (L['tot_expo'], L['time_expo'])
        cell_expo = wrap_cell(cell_expo)

        cell_pairing = " %d\\bfm & %sms" % (L['tot_pairing'], L['time_pairing'])
        print cell0 + " & " + cell_miller + " &"
        print "                  " + cell_expo + " & "
        print "                  " + cell_pairing + " \\\\"
        print " \\hline "