github.com/consensys/gnark-crypto@v0.14.0/ecc/secp256k1/multiexp.go (about) 1 // Copyright 2020 Consensys Software Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Code generated by consensys/gnark-crypto DO NOT EDIT 16 17 package secp256k1 18 19 import ( 20 "errors" 21 "github.com/consensys/gnark-crypto/ecc" 22 "github.com/consensys/gnark-crypto/ecc/secp256k1/fr" 23 "github.com/consensys/gnark-crypto/internal/parallel" 24 "math" 25 "runtime" 26 ) 27 28 // MultiExp implements section 4 of https://eprint.iacr.org/2012/549.pdf 29 // 30 // This call return an error if len(scalars) != len(points) or if provided config is invalid. 31 func (p *G1Affine) MultiExp(points []G1Affine, scalars []fr.Element, config ecc.MultiExpConfig) (*G1Affine, error) { 32 var _p G1Jac 33 if _, err := _p.MultiExp(points, scalars, config); err != nil { 34 return nil, err 35 } 36 p.FromJacobian(&_p) 37 return p, nil 38 } 39 40 // MultiExp implements section 4 of https://eprint.iacr.org/2012/549.pdf 41 // 42 // This call return an error if len(scalars) != len(points) or if provided config is invalid. 43 func (p *G1Jac) MultiExp(points []G1Affine, scalars []fr.Element, config ecc.MultiExpConfig) (*G1Jac, error) { 44 // TODO @gbotrel replace the ecc.MultiExpConfig by a Option pattern for maintainability. 45 // note: 46 // each of the msmCX method is the same, except for the c constant it declares 47 // duplicating (through template generation) these methods allows to declare the buckets on the stack 48 // the choice of c needs to be improved: 49 // there is a theoretical value that gives optimal asymptotics 50 // but in practice, other factors come into play, including: 51 // * if c doesn't divide 64, the word size, then we're bound to select bits over 2 words of our scalars, instead of 1 52 // * number of CPUs 53 // * cache friendliness (which depends on the host, G1 or G2... ) 54 // --> for example, on BN254, a G1 point fits into one cache line of 64bytes, but a G2 point don't. 55 56 // for each msmCX 57 // step 1 58 // we compute, for each scalars over c-bit wide windows, nbChunk digits 59 // if the digit is larger than 2^{c-1}, then, we borrow 2^c from the next window and subtract 60 // 2^{c} to the current digit, making it negative. 61 // negative digits will be processed in the next step as adding -G into the bucket instead of G 62 // (computing -G is cheap, and this saves us half of the buckets) 63 // step 2 64 // buckets are declared on the stack 65 // notice that we have 2^{c-1} buckets instead of 2^{c} (see step1) 66 // we use jacobian extended formulas here as they are faster than mixed addition 67 // msmProcessChunk places points into buckets base on their selector and return the weighted bucket sum in given channel 68 // step 3 69 // reduce the buckets weighed sums into our result (msmReduceChunk) 70 71 // ensure len(points) == len(scalars) 72 nbPoints := len(points) 73 if nbPoints != len(scalars) { 74 return nil, errors.New("len(points) != len(scalars)") 75 } 76 77 // if nbTasks is not set, use all available CPUs 78 if config.NbTasks <= 0 { 79 config.NbTasks = runtime.NumCPU() * 2 80 } else if config.NbTasks > 1024 { 81 return nil, errors.New("invalid config: config.NbTasks > 1024") 82 } 83 84 // here, we compute the best C for nbPoints 85 // we split recursively until nbChunks(c) >= nbTasks, 86 bestC := func(nbPoints int) uint64 { 87 // implemented msmC methods (the c we use must be in this slice) 88 implementedCs := []uint64{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} 89 var C uint64 90 // approximate cost (in group operations) 91 // cost = bits/c * (nbPoints + 2^{c}) 92 // this needs to be verified empirically. 93 // for example, on a MBP 2016, for G2 MultiExp > 8M points, hand picking c gives better results 94 min := math.MaxFloat64 95 for _, c := range implementedCs { 96 cc := (fr.Bits + 1) * (nbPoints + (1 << c)) 97 cost := float64(cc) / float64(c) 98 if cost < min { 99 min = cost 100 C = c 101 } 102 } 103 return C 104 } 105 106 C := bestC(nbPoints) 107 nbChunks := int(computeNbChunks(C)) 108 109 // should we recursively split the msm in half? (see below) 110 // we want to minimize the execution time of the algorithm; 111 // splitting the msm will **add** operations, but if it allows to use more CPU, it might be worth it. 112 113 // costFunction returns a metric that represent the "wall time" of the algorithm 114 costFunction := func(nbTasks, nbCpus, costPerTask int) int { 115 // cost for the reduction of all tasks (msmReduceChunk) 116 totalCost := nbTasks 117 118 // cost for the computation of each task (msmProcessChunk) 119 for nbTasks >= nbCpus { 120 nbTasks -= nbCpus 121 totalCost += costPerTask 122 } 123 if nbTasks > 0 { 124 totalCost += costPerTask 125 } 126 return totalCost 127 } 128 129 // costPerTask is the approximate number of group ops per task 130 costPerTask := func(c uint64, nbPoints int) int { return (nbPoints + int((1 << c))) } 131 132 costPreSplit := costFunction(nbChunks, config.NbTasks, costPerTask(C, nbPoints)) 133 134 cPostSplit := bestC(nbPoints / 2) 135 nbChunksPostSplit := int(computeNbChunks(cPostSplit)) 136 costPostSplit := costFunction(nbChunksPostSplit*2, config.NbTasks, costPerTask(cPostSplit, nbPoints/2)) 137 138 // if the cost of the split msm is lower than the cost of the non split msm, we split 139 if costPostSplit < costPreSplit { 140 config.NbTasks = int(math.Ceil(float64(config.NbTasks) / 2.0)) 141 var _p G1Jac 142 chDone := make(chan struct{}, 1) 143 go func() { 144 _p.MultiExp(points[:nbPoints/2], scalars[:nbPoints/2], config) 145 close(chDone) 146 }() 147 p.MultiExp(points[nbPoints/2:], scalars[nbPoints/2:], config) 148 <-chDone 149 p.AddAssign(&_p) 150 return p, nil 151 } 152 153 // if we don't split, we use the best C we found 154 _innerMsmG1(p, C, points, scalars, config) 155 156 return p, nil 157 } 158 159 func _innerMsmG1(p *G1Jac, c uint64, points []G1Affine, scalars []fr.Element, config ecc.MultiExpConfig) *G1Jac { 160 // partition the scalars 161 digits, chunkStats := partitionScalars(scalars, c, config.NbTasks) 162 163 nbChunks := computeNbChunks(c) 164 165 // for each chunk, spawn one go routine that'll loop through all the scalars in the 166 // corresponding bit-window 167 // note that buckets is an array allocated on the stack and this is critical for performance 168 169 // each go routine sends its result in chChunks[i] channel 170 chChunks := make([]chan g1JacExtended, nbChunks) 171 for i := 0; i < len(chChunks); i++ { 172 chChunks[i] = make(chan g1JacExtended, 1) 173 } 174 175 // we use a semaphore to limit the number of go routines running concurrently 176 // (only if nbTasks < nbCPU) 177 var sem chan struct{} 178 if config.NbTasks < runtime.NumCPU() { 179 // we add nbChunks because if chunk is overweight we split it in two 180 sem = make(chan struct{}, config.NbTasks+int(nbChunks)) 181 for i := 0; i < config.NbTasks; i++ { 182 sem <- struct{}{} 183 } 184 defer func() { 185 close(sem) 186 }() 187 } 188 189 // the last chunk may be processed with a different method than the rest, as it could be smaller. 190 n := len(points) 191 for j := int(nbChunks - 1); j >= 0; j-- { 192 processChunk := getChunkProcessorG1(c, chunkStats[j]) 193 if j == int(nbChunks-1) { 194 processChunk = getChunkProcessorG1(lastC(c), chunkStats[j]) 195 } 196 if chunkStats[j].weight >= 115 { 197 // we split this in more go routines since this chunk has more work to do than the others. 198 // else what would happen is this go routine would finish much later than the others. 199 chSplit := make(chan g1JacExtended, 2) 200 split := n / 2 201 202 if sem != nil { 203 sem <- struct{}{} // add another token to the semaphore, since we split in two. 204 } 205 go processChunk(uint64(j), chSplit, c, points[:split], digits[j*n:(j*n)+split], sem) 206 go processChunk(uint64(j), chSplit, c, points[split:], digits[(j*n)+split:(j+1)*n], sem) 207 go func(chunkID int) { 208 s1 := <-chSplit 209 s2 := <-chSplit 210 close(chSplit) 211 s1.add(&s2) 212 chChunks[chunkID] <- s1 213 }(j) 214 continue 215 } 216 go processChunk(uint64(j), chChunks[j], c, points, digits[j*n:(j+1)*n], sem) 217 } 218 219 return msmReduceChunkG1Affine(p, int(c), chChunks[:]) 220 } 221 222 // getChunkProcessorG1 decides, depending on c window size and statistics for the chunk 223 // to return the best algorithm to process the chunk. 224 func getChunkProcessorG1(c uint64, stat chunkStat) func(chunkID uint64, chRes chan<- g1JacExtended, c uint64, points []G1Affine, digits []uint16, sem chan struct{}) { 225 switch c { 226 227 case 2: 228 return processChunkG1Jacobian[bucketg1JacExtendedC2] 229 case 3: 230 return processChunkG1Jacobian[bucketg1JacExtendedC3] 231 case 4: 232 return processChunkG1Jacobian[bucketg1JacExtendedC4] 233 case 5: 234 return processChunkG1Jacobian[bucketg1JacExtendedC5] 235 case 6: 236 return processChunkG1Jacobian[bucketg1JacExtendedC6] 237 case 7: 238 return processChunkG1Jacobian[bucketg1JacExtendedC7] 239 case 8: 240 return processChunkG1Jacobian[bucketg1JacExtendedC8] 241 case 9: 242 return processChunkG1Jacobian[bucketg1JacExtendedC9] 243 case 10: 244 const batchSize = 80 245 // here we could check some chunk statistic (deviation, ...) to determine if calling 246 // the batch affine version is worth it. 247 if stat.nbBucketFilled < batchSize { 248 // clear indicator that batch affine method is not appropriate here. 249 return processChunkG1Jacobian[bucketg1JacExtendedC10] 250 } 251 return processChunkG1BatchAffine[bucketg1JacExtendedC10, bucketG1AffineC10, bitSetC10, pG1AffineC10, ppG1AffineC10, qG1AffineC10, cG1AffineC10] 252 case 11: 253 const batchSize = 150 254 // here we could check some chunk statistic (deviation, ...) to determine if calling 255 // the batch affine version is worth it. 256 if stat.nbBucketFilled < batchSize { 257 // clear indicator that batch affine method is not appropriate here. 258 return processChunkG1Jacobian[bucketg1JacExtendedC11] 259 } 260 return processChunkG1BatchAffine[bucketg1JacExtendedC11, bucketG1AffineC11, bitSetC11, pG1AffineC11, ppG1AffineC11, qG1AffineC11, cG1AffineC11] 261 case 12: 262 const batchSize = 200 263 // here we could check some chunk statistic (deviation, ...) to determine if calling 264 // the batch affine version is worth it. 265 if stat.nbBucketFilled < batchSize { 266 // clear indicator that batch affine method is not appropriate here. 267 return processChunkG1Jacobian[bucketg1JacExtendedC12] 268 } 269 return processChunkG1BatchAffine[bucketg1JacExtendedC12, bucketG1AffineC12, bitSetC12, pG1AffineC12, ppG1AffineC12, qG1AffineC12, cG1AffineC12] 270 case 13: 271 const batchSize = 350 272 // here we could check some chunk statistic (deviation, ...) to determine if calling 273 // the batch affine version is worth it. 274 if stat.nbBucketFilled < batchSize { 275 // clear indicator that batch affine method is not appropriate here. 276 return processChunkG1Jacobian[bucketg1JacExtendedC13] 277 } 278 return processChunkG1BatchAffine[bucketg1JacExtendedC13, bucketG1AffineC13, bitSetC13, pG1AffineC13, ppG1AffineC13, qG1AffineC13, cG1AffineC13] 279 case 14: 280 const batchSize = 400 281 // here we could check some chunk statistic (deviation, ...) to determine if calling 282 // the batch affine version is worth it. 283 if stat.nbBucketFilled < batchSize { 284 // clear indicator that batch affine method is not appropriate here. 285 return processChunkG1Jacobian[bucketg1JacExtendedC14] 286 } 287 return processChunkG1BatchAffine[bucketg1JacExtendedC14, bucketG1AffineC14, bitSetC14, pG1AffineC14, ppG1AffineC14, qG1AffineC14, cG1AffineC14] 288 case 15: 289 const batchSize = 500 290 // here we could check some chunk statistic (deviation, ...) to determine if calling 291 // the batch affine version is worth it. 292 if stat.nbBucketFilled < batchSize { 293 // clear indicator that batch affine method is not appropriate here. 294 return processChunkG1Jacobian[bucketg1JacExtendedC15] 295 } 296 return processChunkG1BatchAffine[bucketg1JacExtendedC15, bucketG1AffineC15, bitSetC15, pG1AffineC15, ppG1AffineC15, qG1AffineC15, cG1AffineC15] 297 default: 298 // panic("will not happen c != previous values is not generated by templates") 299 return processChunkG1Jacobian[bucketg1JacExtendedC15] 300 } 301 } 302 303 // msmReduceChunkG1Affine reduces the weighted sum of the buckets into the result of the multiExp 304 func msmReduceChunkG1Affine(p *G1Jac, c int, chChunks []chan g1JacExtended) *G1Jac { 305 var _p g1JacExtended 306 totalj := <-chChunks[len(chChunks)-1] 307 _p.Set(&totalj) 308 for j := len(chChunks) - 2; j >= 0; j-- { 309 for l := 0; l < c; l++ { 310 _p.double(&_p) 311 } 312 totalj := <-chChunks[j] 313 _p.add(&totalj) 314 } 315 316 return p.unsafeFromJacExtended(&_p) 317 } 318 319 // Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] * 320 // combinationCoeff^i and stores the result in p. It returns error in case 321 // configuration is invalid. 322 func (p *G1Affine) Fold(points []G1Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G1Affine, error) { 323 var _p G1Jac 324 if _, err := _p.Fold(points, combinationCoeff, config); err != nil { 325 return nil, err 326 } 327 p.FromJacobian(&_p) 328 return p, nil 329 } 330 331 // Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] * 332 // combinationCoeff^i and stores the result in p. It returns error in case 333 // configuration is invalid. 334 func (p *G1Jac) Fold(points []G1Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G1Jac, error) { 335 scalars := make([]fr.Element, len(points)) 336 scalar := fr.NewElement(1) 337 for i := 0; i < len(points); i++ { 338 scalars[i].Set(&scalar) 339 scalar.Mul(&scalar, &combinationCoeff) 340 } 341 return p.MultiExp(points, scalars, config) 342 } 343 344 // selector stores the index, mask and shifts needed to select bits from a scalar 345 // it is used during the multiExp algorithm or the batch scalar multiplication 346 type selector struct { 347 index uint64 // index in the multi-word scalar to select bits from 348 mask uint64 // mask (c-bit wide) 349 shift uint64 // shift needed to get our bits on low positions 350 351 multiWordSelect bool // set to true if we need to select bits from 2 words (case where c doesn't divide 64) 352 maskHigh uint64 // same than mask, for index+1 353 shiftHigh uint64 // same than shift, for index+1 354 } 355 356 // return number of chunks for a given window size c 357 // the last chunk may be bigger to accommodate a potential carry from the NAF decomposition 358 func computeNbChunks(c uint64) uint64 { 359 return (fr.Bits + c - 1) / c 360 } 361 362 // return the last window size for a scalar; 363 // this last window should accommodate a carry (from the NAF decomposition) 364 // it can be == c if we have 1 available bit 365 // it can be > c if we have 0 available bit 366 // it can be < c if we have 2+ available bits 367 func lastC(c uint64) uint64 { 368 nbAvailableBits := (computeNbChunks(c) * c) - fr.Bits 369 return c + 1 - nbAvailableBits 370 } 371 372 type chunkStat struct { 373 // relative weight of work compared to other chunks. 100.0 -> nominal weight. 374 weight float32 375 376 // percentage of bucket filled in the window; 377 ppBucketFilled float32 378 nbBucketFilled int 379 } 380 381 // partitionScalars compute, for each scalars over c-bit wide windows, nbChunk digits 382 // if the digit is larger than 2^{c-1}, then, we borrow 2^c from the next window and subtract 383 // 2^{c} to the current digit, making it negative. 384 // negative digits can be processed in a later step as adding -G into the bucket instead of G 385 // (computing -G is cheap, and this saves us half of the buckets in the MultiExp or BatchScalarMultiplication) 386 func partitionScalars(scalars []fr.Element, c uint64, nbTasks int) ([]uint16, []chunkStat) { 387 // no benefit here to have more tasks than CPUs 388 if nbTasks > runtime.NumCPU() { 389 nbTasks = runtime.NumCPU() 390 } 391 392 // number of c-bit radixes in a scalar 393 nbChunks := computeNbChunks(c) 394 395 digits := make([]uint16, len(scalars)*int(nbChunks)) 396 397 mask := uint64((1 << c) - 1) // low c bits are 1 398 max := int(1<<(c-1)) - 1 // max value (inclusive) we want for our digits 399 cDivides64 := (64 % c) == 0 // if c doesn't divide 64, we may need to select over multiple words 400 401 // compute offset and word selector / shift to select the right bits of our windows 402 selectors := make([]selector, nbChunks) 403 for chunk := uint64(0); chunk < nbChunks; chunk++ { 404 jc := uint64(chunk * c) 405 d := selector{} 406 d.index = jc / 64 407 d.shift = jc - (d.index * 64) 408 d.mask = mask << d.shift 409 d.multiWordSelect = !cDivides64 && d.shift > (64-c) && d.index < (fr.Limbs-1) 410 if d.multiWordSelect { 411 nbBitsHigh := d.shift - uint64(64-c) 412 d.maskHigh = (1 << nbBitsHigh) - 1 413 d.shiftHigh = (c - nbBitsHigh) 414 } 415 selectors[chunk] = d 416 } 417 418 parallel.Execute(len(scalars), func(start, end int) { 419 for i := start; i < end; i++ { 420 if scalars[i].IsZero() { 421 // everything is 0, no need to process this scalar 422 continue 423 } 424 scalar := scalars[i].Bits() 425 426 var carry int 427 428 // for each chunk in the scalar, compute the current digit, and an eventual carry 429 for chunk := uint64(0); chunk < nbChunks-1; chunk++ { 430 s := selectors[chunk] 431 432 // init with carry if any 433 digit := carry 434 carry = 0 435 436 // digit = value of the c-bit window 437 digit += int((scalar[s.index] & s.mask) >> s.shift) 438 439 if s.multiWordSelect { 440 // we are selecting bits over 2 words 441 digit += int(scalar[s.index+1]&s.maskHigh) << s.shiftHigh 442 } 443 444 // if the digit is larger than 2^{c-1}, then, we borrow 2^c from the next window and subtract 445 // 2^{c} to the current digit, making it negative. 446 if digit > max { 447 digit -= (1 << c) 448 carry = 1 449 } 450 451 // if digit is zero, no impact on result 452 if digit == 0 { 453 continue 454 } 455 456 var bits uint16 457 if digit > 0 { 458 bits = uint16(digit) << 1 459 } else { 460 bits = (uint16(-digit-1) << 1) + 1 461 } 462 digits[int(chunk)*len(scalars)+i] = bits 463 } 464 465 // for the last chunk, we don't want to borrow from a next window 466 // (but may have a larger max value) 467 chunk := nbChunks - 1 468 s := selectors[chunk] 469 // init with carry if any 470 digit := carry 471 // digit = value of the c-bit window 472 digit += int((scalar[s.index] & s.mask) >> s.shift) 473 if s.multiWordSelect { 474 // we are selecting bits over 2 words 475 digit += int(scalar[s.index+1]&s.maskHigh) << s.shiftHigh 476 } 477 digits[int(chunk)*len(scalars)+i] = uint16(digit) << 1 478 } 479 480 }, nbTasks) 481 482 // aggregate chunk stats 483 chunkStats := make([]chunkStat, nbChunks) 484 if c <= 9 { 485 // no need to compute stats for small window sizes 486 return digits, chunkStats 487 } 488 parallel.Execute(len(chunkStats), func(start, end int) { 489 // for each chunk compute the statistics 490 for chunkID := start; chunkID < end; chunkID++ { 491 // indicates if a bucket is hit. 492 var b bitSetC15 493 494 // digits for the chunk 495 chunkDigits := digits[chunkID*len(scalars) : (chunkID+1)*len(scalars)] 496 497 totalOps := 0 498 nz := 0 // non zero buckets count 499 for _, digit := range chunkDigits { 500 if digit == 0 { 501 continue 502 } 503 totalOps++ 504 bucketID := digit >> 1 505 if digit&1 == 0 { 506 bucketID -= 1 507 } 508 if !b[bucketID] { 509 nz++ 510 b[bucketID] = true 511 } 512 } 513 chunkStats[chunkID].weight = float32(totalOps) // count number of ops for now, we will compute the weight after 514 chunkStats[chunkID].ppBucketFilled = (float32(nz) * 100.0) / float32(int(1<<(c-1))) 515 chunkStats[chunkID].nbBucketFilled = nz 516 } 517 }, nbTasks) 518 519 totalOps := float32(0.0) 520 for _, stat := range chunkStats { 521 totalOps += stat.weight 522 } 523 524 target := totalOps / float32(nbChunks) 525 if target != 0.0 { 526 // if target == 0, it means all the scalars are 0 everywhere, there is no work to be done. 527 for i := 0; i < len(chunkStats); i++ { 528 chunkStats[i].weight = (chunkStats[i].weight * 100.0) / target 529 } 530 } 531 532 return digits, chunkStats 533 }