github.com/consensys/gnark-crypto@v0.14.0/ecc/bw6-756/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 bw6756
    18  
    19  import (
    20  	"errors"
    21  	"github.com/consensys/gnark-crypto/ecc"
    22  	"github.com/consensys/gnark-crypto/ecc/bw6-756/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, 8, 11, 16}
    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 3:
   228  		return processChunkG1Jacobian[bucketg1JacExtendedC3]
   229  	case 4:
   230  		return processChunkG1Jacobian[bucketg1JacExtendedC4]
   231  	case 5:
   232  		return processChunkG1Jacobian[bucketg1JacExtendedC5]
   233  	case 8:
   234  		return processChunkG1Jacobian[bucketg1JacExtendedC8]
   235  	case 11:
   236  		const batchSize = 150
   237  		// here we could check some chunk statistic (deviation, ...) to determine if calling
   238  		// the batch affine version is worth it.
   239  		if stat.nbBucketFilled < batchSize {
   240  			// clear indicator that batch affine method is not appropriate here.
   241  			return processChunkG1Jacobian[bucketg1JacExtendedC11]
   242  		}
   243  		return processChunkG1BatchAffine[bucketg1JacExtendedC11, bucketG1AffineC11, bitSetC11, pG1AffineC11, ppG1AffineC11, qG1AffineC11, cG1AffineC11]
   244  	case 16:
   245  		const batchSize = 640
   246  		// here we could check some chunk statistic (deviation, ...) to determine if calling
   247  		// the batch affine version is worth it.
   248  		if stat.nbBucketFilled < batchSize {
   249  			// clear indicator that batch affine method is not appropriate here.
   250  			return processChunkG1Jacobian[bucketg1JacExtendedC16]
   251  		}
   252  		return processChunkG1BatchAffine[bucketg1JacExtendedC16, bucketG1AffineC16, bitSetC16, pG1AffineC16, ppG1AffineC16, qG1AffineC16, cG1AffineC16]
   253  	default:
   254  		// panic("will not happen c != previous values is not generated by templates")
   255  		return processChunkG1Jacobian[bucketg1JacExtendedC16]
   256  	}
   257  }
   258  
   259  // msmReduceChunkG1Affine reduces the weighted sum of the buckets into the result of the multiExp
   260  func msmReduceChunkG1Affine(p *G1Jac, c int, chChunks []chan g1JacExtended) *G1Jac {
   261  	var _p g1JacExtended
   262  	totalj := <-chChunks[len(chChunks)-1]
   263  	_p.Set(&totalj)
   264  	for j := len(chChunks) - 2; j >= 0; j-- {
   265  		for l := 0; l < c; l++ {
   266  			_p.double(&_p)
   267  		}
   268  		totalj := <-chChunks[j]
   269  		_p.add(&totalj)
   270  	}
   271  
   272  	return p.unsafeFromJacExtended(&_p)
   273  }
   274  
   275  // Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] *
   276  // combinationCoeff^i and stores the result in p. It returns error in case
   277  // configuration is invalid.
   278  func (p *G1Affine) Fold(points []G1Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G1Affine, error) {
   279  	var _p G1Jac
   280  	if _, err := _p.Fold(points, combinationCoeff, config); err != nil {
   281  		return nil, err
   282  	}
   283  	p.FromJacobian(&_p)
   284  	return p, nil
   285  }
   286  
   287  // Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] *
   288  // combinationCoeff^i and stores the result in p. It returns error in case
   289  // configuration is invalid.
   290  func (p *G1Jac) Fold(points []G1Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G1Jac, error) {
   291  	scalars := make([]fr.Element, len(points))
   292  	scalar := fr.NewElement(1)
   293  	for i := 0; i < len(points); i++ {
   294  		scalars[i].Set(&scalar)
   295  		scalar.Mul(&scalar, &combinationCoeff)
   296  	}
   297  	return p.MultiExp(points, scalars, config)
   298  }
   299  
   300  // MultiExp implements section 4 of https://eprint.iacr.org/2012/549.pdf
   301  //
   302  // This call return an error if len(scalars) != len(points) or if provided config is invalid.
   303  func (p *G2Affine) MultiExp(points []G2Affine, scalars []fr.Element, config ecc.MultiExpConfig) (*G2Affine, error) {
   304  	var _p G2Jac
   305  	if _, err := _p.MultiExp(points, scalars, config); err != nil {
   306  		return nil, err
   307  	}
   308  	p.FromJacobian(&_p)
   309  	return p, nil
   310  }
   311  
   312  // MultiExp implements section 4 of https://eprint.iacr.org/2012/549.pdf
   313  //
   314  // This call return an error if len(scalars) != len(points) or if provided config is invalid.
   315  func (p *G2Jac) MultiExp(points []G2Affine, scalars []fr.Element, config ecc.MultiExpConfig) (*G2Jac, error) {
   316  	// TODO @gbotrel replace the ecc.MultiExpConfig by a Option pattern for maintainability.
   317  	// note:
   318  	// each of the msmCX method is the same, except for the c constant it declares
   319  	// duplicating (through template generation) these methods allows to declare the buckets on the stack
   320  	// the choice of c needs to be improved:
   321  	// there is a theoretical value that gives optimal asymptotics
   322  	// but in practice, other factors come into play, including:
   323  	// * 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
   324  	// * number of CPUs
   325  	// * cache friendliness (which depends on the host, G1 or G2... )
   326  	//	--> for example, on BN254, a G1 point fits into one cache line of 64bytes, but a G2 point don't.
   327  
   328  	// for each msmCX
   329  	// step 1
   330  	// we compute, for each scalars over c-bit wide windows, nbChunk digits
   331  	// if the digit is larger than 2^{c-1}, then, we borrow 2^c from the next window and subtract
   332  	// 2^{c} to the current digit, making it negative.
   333  	// negative digits will be processed in the next step as adding -G into the bucket instead of G
   334  	// (computing -G is cheap, and this saves us half of the buckets)
   335  	// step 2
   336  	// buckets are declared on the stack
   337  	// notice that we have 2^{c-1} buckets instead of 2^{c} (see step1)
   338  	// we use jacobian extended formulas here as they are faster than mixed addition
   339  	// msmProcessChunk places points into buckets base on their selector and return the weighted bucket sum in given channel
   340  	// step 3
   341  	// reduce the buckets weighed sums into our result (msmReduceChunk)
   342  
   343  	// ensure len(points) == len(scalars)
   344  	nbPoints := len(points)
   345  	if nbPoints != len(scalars) {
   346  		return nil, errors.New("len(points) != len(scalars)")
   347  	}
   348  
   349  	// if nbTasks is not set, use all available CPUs
   350  	if config.NbTasks <= 0 {
   351  		config.NbTasks = runtime.NumCPU() * 2
   352  	} else if config.NbTasks > 1024 {
   353  		return nil, errors.New("invalid config: config.NbTasks > 1024")
   354  	}
   355  
   356  	// here, we compute the best C for nbPoints
   357  	// we split recursively until nbChunks(c) >= nbTasks,
   358  	bestC := func(nbPoints int) uint64 {
   359  		// implemented msmC methods (the c we use must be in this slice)
   360  		implementedCs := []uint64{4, 5, 8, 11, 16}
   361  		var C uint64
   362  		// approximate cost (in group operations)
   363  		// cost = bits/c * (nbPoints + 2^{c})
   364  		// this needs to be verified empirically.
   365  		// for example, on a MBP 2016, for G2 MultiExp > 8M points, hand picking c gives better results
   366  		min := math.MaxFloat64
   367  		for _, c := range implementedCs {
   368  			cc := (fr.Bits + 1) * (nbPoints + (1 << c))
   369  			cost := float64(cc) / float64(c)
   370  			if cost < min {
   371  				min = cost
   372  				C = c
   373  			}
   374  		}
   375  		return C
   376  	}
   377  
   378  	C := bestC(nbPoints)
   379  	nbChunks := int(computeNbChunks(C))
   380  
   381  	// should we recursively split the msm in half? (see below)
   382  	// we want to minimize the execution time of the algorithm;
   383  	// splitting the msm will **add** operations, but if it allows to use more CPU, it might be worth it.
   384  
   385  	// costFunction returns a metric that represent the "wall time" of the algorithm
   386  	costFunction := func(nbTasks, nbCpus, costPerTask int) int {
   387  		// cost for the reduction of all tasks (msmReduceChunk)
   388  		totalCost := nbTasks
   389  
   390  		// cost for the computation of each task (msmProcessChunk)
   391  		for nbTasks >= nbCpus {
   392  			nbTasks -= nbCpus
   393  			totalCost += costPerTask
   394  		}
   395  		if nbTasks > 0 {
   396  			totalCost += costPerTask
   397  		}
   398  		return totalCost
   399  	}
   400  
   401  	// costPerTask is the approximate number of group ops per task
   402  	costPerTask := func(c uint64, nbPoints int) int { return (nbPoints + int((1 << c))) }
   403  
   404  	costPreSplit := costFunction(nbChunks, config.NbTasks, costPerTask(C, nbPoints))
   405  
   406  	cPostSplit := bestC(nbPoints / 2)
   407  	nbChunksPostSplit := int(computeNbChunks(cPostSplit))
   408  	costPostSplit := costFunction(nbChunksPostSplit*2, config.NbTasks, costPerTask(cPostSplit, nbPoints/2))
   409  
   410  	// if the cost of the split msm is lower than the cost of the non split msm, we split
   411  	if costPostSplit < costPreSplit {
   412  		config.NbTasks = int(math.Ceil(float64(config.NbTasks) / 2.0))
   413  		var _p G2Jac
   414  		chDone := make(chan struct{}, 1)
   415  		go func() {
   416  			_p.MultiExp(points[:nbPoints/2], scalars[:nbPoints/2], config)
   417  			close(chDone)
   418  		}()
   419  		p.MultiExp(points[nbPoints/2:], scalars[nbPoints/2:], config)
   420  		<-chDone
   421  		p.AddAssign(&_p)
   422  		return p, nil
   423  	}
   424  
   425  	// if we don't split, we use the best C we found
   426  	_innerMsmG2(p, C, points, scalars, config)
   427  
   428  	return p, nil
   429  }
   430  
   431  func _innerMsmG2(p *G2Jac, c uint64, points []G2Affine, scalars []fr.Element, config ecc.MultiExpConfig) *G2Jac {
   432  	// partition the scalars
   433  	digits, chunkStats := partitionScalars(scalars, c, config.NbTasks)
   434  
   435  	nbChunks := computeNbChunks(c)
   436  
   437  	// for each chunk, spawn one go routine that'll loop through all the scalars in the
   438  	// corresponding bit-window
   439  	// note that buckets is an array allocated on the stack and this is critical for performance
   440  
   441  	// each go routine sends its result in chChunks[i] channel
   442  	chChunks := make([]chan g2JacExtended, nbChunks)
   443  	for i := 0; i < len(chChunks); i++ {
   444  		chChunks[i] = make(chan g2JacExtended, 1)
   445  	}
   446  
   447  	// we use a semaphore to limit the number of go routines running concurrently
   448  	// (only if nbTasks < nbCPU)
   449  	var sem chan struct{}
   450  	if config.NbTasks < runtime.NumCPU() {
   451  		// we add nbChunks because if chunk is overweight we split it in two
   452  		sem = make(chan struct{}, config.NbTasks+int(nbChunks))
   453  		for i := 0; i < config.NbTasks; i++ {
   454  			sem <- struct{}{}
   455  		}
   456  		defer func() {
   457  			close(sem)
   458  		}()
   459  	}
   460  
   461  	// the last chunk may be processed with a different method than the rest, as it could be smaller.
   462  	n := len(points)
   463  	for j := int(nbChunks - 1); j >= 0; j-- {
   464  		processChunk := getChunkProcessorG2(c, chunkStats[j])
   465  		if j == int(nbChunks-1) {
   466  			processChunk = getChunkProcessorG2(lastC(c), chunkStats[j])
   467  		}
   468  		if chunkStats[j].weight >= 115 {
   469  			// we split this in more go routines since this chunk has more work to do than the others.
   470  			// else what would happen is this go routine would finish much later than the others.
   471  			chSplit := make(chan g2JacExtended, 2)
   472  			split := n / 2
   473  
   474  			if sem != nil {
   475  				sem <- struct{}{} // add another token to the semaphore, since we split in two.
   476  			}
   477  			go processChunk(uint64(j), chSplit, c, points[:split], digits[j*n:(j*n)+split], sem)
   478  			go processChunk(uint64(j), chSplit, c, points[split:], digits[(j*n)+split:(j+1)*n], sem)
   479  			go func(chunkID int) {
   480  				s1 := <-chSplit
   481  				s2 := <-chSplit
   482  				close(chSplit)
   483  				s1.add(&s2)
   484  				chChunks[chunkID] <- s1
   485  			}(j)
   486  			continue
   487  		}
   488  		go processChunk(uint64(j), chChunks[j], c, points, digits[j*n:(j+1)*n], sem)
   489  	}
   490  
   491  	return msmReduceChunkG2Affine(p, int(c), chChunks[:])
   492  }
   493  
   494  // getChunkProcessorG2 decides, depending on c window size and statistics for the chunk
   495  // to return the best algorithm to process the chunk.
   496  func getChunkProcessorG2(c uint64, stat chunkStat) func(chunkID uint64, chRes chan<- g2JacExtended, c uint64, points []G2Affine, digits []uint16, sem chan struct{}) {
   497  	switch c {
   498  
   499  	case 3:
   500  		return processChunkG2Jacobian[bucketg2JacExtendedC3]
   501  	case 4:
   502  		return processChunkG2Jacobian[bucketg2JacExtendedC4]
   503  	case 5:
   504  		return processChunkG2Jacobian[bucketg2JacExtendedC5]
   505  	case 8:
   506  		return processChunkG2Jacobian[bucketg2JacExtendedC8]
   507  	case 11:
   508  		const batchSize = 150
   509  		// here we could check some chunk statistic (deviation, ...) to determine if calling
   510  		// the batch affine version is worth it.
   511  		if stat.nbBucketFilled < batchSize {
   512  			// clear indicator that batch affine method is not appropriate here.
   513  			return processChunkG2Jacobian[bucketg2JacExtendedC11]
   514  		}
   515  		return processChunkG2BatchAffine[bucketg2JacExtendedC11, bucketG2AffineC11, bitSetC11, pG2AffineC11, ppG2AffineC11, qG2AffineC11, cG2AffineC11]
   516  	case 16:
   517  		const batchSize = 640
   518  		// here we could check some chunk statistic (deviation, ...) to determine if calling
   519  		// the batch affine version is worth it.
   520  		if stat.nbBucketFilled < batchSize {
   521  			// clear indicator that batch affine method is not appropriate here.
   522  			return processChunkG2Jacobian[bucketg2JacExtendedC16]
   523  		}
   524  		return processChunkG2BatchAffine[bucketg2JacExtendedC16, bucketG2AffineC16, bitSetC16, pG2AffineC16, ppG2AffineC16, qG2AffineC16, cG2AffineC16]
   525  	default:
   526  		// panic("will not happen c != previous values is not generated by templates")
   527  		return processChunkG2Jacobian[bucketg2JacExtendedC16]
   528  	}
   529  }
   530  
   531  // msmReduceChunkG2Affine reduces the weighted sum of the buckets into the result of the multiExp
   532  func msmReduceChunkG2Affine(p *G2Jac, c int, chChunks []chan g2JacExtended) *G2Jac {
   533  	var _p g2JacExtended
   534  	totalj := <-chChunks[len(chChunks)-1]
   535  	_p.Set(&totalj)
   536  	for j := len(chChunks) - 2; j >= 0; j-- {
   537  		for l := 0; l < c; l++ {
   538  			_p.double(&_p)
   539  		}
   540  		totalj := <-chChunks[j]
   541  		_p.add(&totalj)
   542  	}
   543  
   544  	return p.unsafeFromJacExtended(&_p)
   545  }
   546  
   547  // Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] *
   548  // combinationCoeff^i and stores the result in p. It returns error in case
   549  // configuration is invalid.
   550  func (p *G2Affine) Fold(points []G2Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G2Affine, error) {
   551  	var _p G2Jac
   552  	if _, err := _p.Fold(points, combinationCoeff, config); err != nil {
   553  		return nil, err
   554  	}
   555  	p.FromJacobian(&_p)
   556  	return p, nil
   557  }
   558  
   559  // Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] *
   560  // combinationCoeff^i and stores the result in p. It returns error in case
   561  // configuration is invalid.
   562  func (p *G2Jac) Fold(points []G2Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G2Jac, error) {
   563  	scalars := make([]fr.Element, len(points))
   564  	scalar := fr.NewElement(1)
   565  	for i := 0; i < len(points); i++ {
   566  		scalars[i].Set(&scalar)
   567  		scalar.Mul(&scalar, &combinationCoeff)
   568  	}
   569  	return p.MultiExp(points, scalars, config)
   570  }
   571  
   572  // selector stores the index, mask and shifts needed to select bits from a scalar
   573  // it is used during the multiExp algorithm or the batch scalar multiplication
   574  type selector struct {
   575  	index uint64 // index in the multi-word scalar to select bits from
   576  	mask  uint64 // mask (c-bit wide)
   577  	shift uint64 // shift needed to get our bits on low positions
   578  
   579  	multiWordSelect bool   // set to true if we need to select bits from 2 words (case where c doesn't divide 64)
   580  	maskHigh        uint64 // same than mask, for index+1
   581  	shiftHigh       uint64 // same than shift, for index+1
   582  }
   583  
   584  // return number of chunks for a given window size c
   585  // the last chunk may be bigger to accommodate a potential carry from the NAF decomposition
   586  func computeNbChunks(c uint64) uint64 {
   587  	return (fr.Bits + c - 1) / c
   588  }
   589  
   590  // return the last window size for a scalar;
   591  // this last window should accommodate a carry (from the NAF decomposition)
   592  // it can be == c if we have 1 available bit
   593  // it can be > c if we have 0 available bit
   594  // it can be < c if we have 2+ available bits
   595  func lastC(c uint64) uint64 {
   596  	nbAvailableBits := (computeNbChunks(c) * c) - fr.Bits
   597  	return c + 1 - nbAvailableBits
   598  }
   599  
   600  type chunkStat struct {
   601  	// relative weight of work compared to other chunks. 100.0 -> nominal weight.
   602  	weight float32
   603  
   604  	// percentage of bucket filled in the window;
   605  	ppBucketFilled float32
   606  	nbBucketFilled int
   607  }
   608  
   609  // partitionScalars  compute, for each scalars over c-bit wide windows, nbChunk digits
   610  // if the digit is larger than 2^{c-1}, then, we borrow 2^c from the next window and subtract
   611  // 2^{c} to the current digit, making it negative.
   612  // negative digits can be processed in a later step as adding -G into the bucket instead of G
   613  // (computing -G is cheap, and this saves us half of the buckets in the MultiExp or BatchScalarMultiplication)
   614  func partitionScalars(scalars []fr.Element, c uint64, nbTasks int) ([]uint16, []chunkStat) {
   615  	// no benefit here to have more tasks than CPUs
   616  	if nbTasks > runtime.NumCPU() {
   617  		nbTasks = runtime.NumCPU()
   618  	}
   619  
   620  	// number of c-bit radixes in a scalar
   621  	nbChunks := computeNbChunks(c)
   622  
   623  	digits := make([]uint16, len(scalars)*int(nbChunks))
   624  
   625  	mask := uint64((1 << c) - 1) // low c bits are 1
   626  	max := int(1<<(c-1)) - 1     // max value (inclusive) we want for our digits
   627  	cDivides64 := (64 % c) == 0  // if c doesn't divide 64, we may need to select over multiple words
   628  
   629  	// compute offset and word selector / shift to select the right bits of our windows
   630  	selectors := make([]selector, nbChunks)
   631  	for chunk := uint64(0); chunk < nbChunks; chunk++ {
   632  		jc := uint64(chunk * c)
   633  		d := selector{}
   634  		d.index = jc / 64
   635  		d.shift = jc - (d.index * 64)
   636  		d.mask = mask << d.shift
   637  		d.multiWordSelect = !cDivides64 && d.shift > (64-c) && d.index < (fr.Limbs-1)
   638  		if d.multiWordSelect {
   639  			nbBitsHigh := d.shift - uint64(64-c)
   640  			d.maskHigh = (1 << nbBitsHigh) - 1
   641  			d.shiftHigh = (c - nbBitsHigh)
   642  		}
   643  		selectors[chunk] = d
   644  	}
   645  
   646  	parallel.Execute(len(scalars), func(start, end int) {
   647  		for i := start; i < end; i++ {
   648  			if scalars[i].IsZero() {
   649  				// everything is 0, no need to process this scalar
   650  				continue
   651  			}
   652  			scalar := scalars[i].Bits()
   653  
   654  			var carry int
   655  
   656  			// for each chunk in the scalar, compute the current digit, and an eventual carry
   657  			for chunk := uint64(0); chunk < nbChunks-1; chunk++ {
   658  				s := selectors[chunk]
   659  
   660  				// init with carry if any
   661  				digit := carry
   662  				carry = 0
   663  
   664  				// digit = value of the c-bit window
   665  				digit += int((scalar[s.index] & s.mask) >> s.shift)
   666  
   667  				if s.multiWordSelect {
   668  					// we are selecting bits over 2 words
   669  					digit += int(scalar[s.index+1]&s.maskHigh) << s.shiftHigh
   670  				}
   671  
   672  				// if the digit is larger than 2^{c-1}, then, we borrow 2^c from the next window and subtract
   673  				// 2^{c} to the current digit, making it negative.
   674  				if digit > max {
   675  					digit -= (1 << c)
   676  					carry = 1
   677  				}
   678  
   679  				// if digit is zero, no impact on result
   680  				if digit == 0 {
   681  					continue
   682  				}
   683  
   684  				var bits uint16
   685  				if digit > 0 {
   686  					bits = uint16(digit) << 1
   687  				} else {
   688  					bits = (uint16(-digit-1) << 1) + 1
   689  				}
   690  				digits[int(chunk)*len(scalars)+i] = bits
   691  			}
   692  
   693  			// for the last chunk, we don't want to borrow from a next window
   694  			// (but may have a larger max value)
   695  			chunk := nbChunks - 1
   696  			s := selectors[chunk]
   697  			// init with carry if any
   698  			digit := carry
   699  			// digit = value of the c-bit window
   700  			digit += int((scalar[s.index] & s.mask) >> s.shift)
   701  			if s.multiWordSelect {
   702  				// we are selecting bits over 2 words
   703  				digit += int(scalar[s.index+1]&s.maskHigh) << s.shiftHigh
   704  			}
   705  			digits[int(chunk)*len(scalars)+i] = uint16(digit) << 1
   706  		}
   707  
   708  	}, nbTasks)
   709  
   710  	// aggregate  chunk stats
   711  	chunkStats := make([]chunkStat, nbChunks)
   712  	if c <= 9 {
   713  		// no need to compute stats for small window sizes
   714  		return digits, chunkStats
   715  	}
   716  	parallel.Execute(len(chunkStats), func(start, end int) {
   717  		// for each chunk compute the statistics
   718  		for chunkID := start; chunkID < end; chunkID++ {
   719  			// indicates if a bucket is hit.
   720  			var b bitSetC16
   721  
   722  			// digits for the chunk
   723  			chunkDigits := digits[chunkID*len(scalars) : (chunkID+1)*len(scalars)]
   724  
   725  			totalOps := 0
   726  			nz := 0 // non zero buckets count
   727  			for _, digit := range chunkDigits {
   728  				if digit == 0 {
   729  					continue
   730  				}
   731  				totalOps++
   732  				bucketID := digit >> 1
   733  				if digit&1 == 0 {
   734  					bucketID -= 1
   735  				}
   736  				if !b[bucketID] {
   737  					nz++
   738  					b[bucketID] = true
   739  				}
   740  			}
   741  			chunkStats[chunkID].weight = float32(totalOps) // count number of ops for now, we will compute the weight after
   742  			chunkStats[chunkID].ppBucketFilled = (float32(nz) * 100.0) / float32(int(1<<(c-1)))
   743  			chunkStats[chunkID].nbBucketFilled = nz
   744  		}
   745  	}, nbTasks)
   746  
   747  	totalOps := float32(0.0)
   748  	for _, stat := range chunkStats {
   749  		totalOps += stat.weight
   750  	}
   751  
   752  	target := totalOps / float32(nbChunks)
   753  	if target != 0.0 {
   754  		// if target == 0, it means all the scalars are 0 everywhere, there is no work to be done.
   755  		for i := 0; i < len(chunkStats); i++ {
   756  			chunkStats[i].weight = (chunkStats[i].weight * 100.0) / target
   757  		}
   758  	}
   759  
   760  	return digits, chunkStats
   761  }