// StrongMillerRabin checks if N is a // strong Miller-Rabin pseudoprime in base a. // That is, it checks if a is a witness // for compositeness of N or if N is a strong // pseudoprime base a. // // Use builtin ProbablyPrime if you want to do a lot // of random tests, this is for one specific // base value. func StrongMillerRabin(N *big.Int, a int64) int { // Step 0: parse input if N.Sign() < 0 || N.Bit(0) == 0 || a < 2 { panic("MR is for positive odd integers with a >= 2") } A := big.NewInt(a) if (a == 2 && N.Bit(0) == 0) || new(big.Int).GCD(nil, nil, N, A).Cmp(one) != 0 { return IsComposite } // Step 1: find d,s, so that n - 1 = d*2^s // with d odd d := new(big.Int).Sub(N, one) s := trailingZeroBits(d) d.Rsh(d, s) // Step 2: compute powers a^d // and then a^(d*2^r) for 0<r<s nm1 := new(big.Int).Sub(N, one) Ad := new(big.Int).Exp(A, d, N) if Ad.Cmp(one) == 0 || Ad.Cmp(nm1) == 0 { return Undetermined } for r := uint(1); r < s; r++ { Ad.Exp(Ad, two, N) if Ad.Cmp(nm1) == 0 { return Undetermined } } // Step 3: a is a witness for compositeness return IsComposite }
// p256FromBig sets out = R*in. func p256FromBig(out *[p256Limbs]uint32, in *big.Int) { tmp := new(big.Int).Lsh(in, 257) tmp.Mod(tmp, p256.P) for i := 0; i < p256Limbs; i++ { if bits := tmp.Bits(); len(bits) > 0 { out[i] = uint32(bits[0]) & bottom29Bits } else { out[i] = 0 } tmp.Rsh(tmp, 29) i++ if i == p256Limbs { break } if bits := tmp.Bits(); len(bits) > 0 { out[i] = uint32(bits[0]) & bottom28Bits } else { out[i] = 0 } tmp.Rsh(tmp, 28) } }
func factor(n *big.Int) (pf []pExp) { var e int64 for ; n.Bit(int(e)) == 0; e++ { } if e > 0 { n.Rsh(n, uint(e)) pf = []pExp{{big.NewInt(2), e}} } s := sqrt(n) q, r := new(big.Int), new(big.Int) for d := big.NewInt(3); n.Cmp(one) > 0; d.Add(d, two) { if d.Cmp(s) > 0 { d.Set(n) } for e = 0; ; e++ { q.QuoRem(n, d, r) if r.BitLen() > 0 { break } n.Set(q) } if e > 0 { pf = append(pf, pExp{new(big.Int).Set(d), e}) s = sqrt(n) } } return }
// polyPowMod computes ``f**n`` in ``GF(p)[x]/(g)`` using repeated squaring. // Given polynomials ``f`` and ``g`` in ``GF(p)[x]`` and a non-negative // integer ``n``, efficiently computes ``f**n (mod g)`` i.e. the remainder // of ``f**n`` from division by ``g``, using the repeated squaring algorithm. // This function was ported from sympy.polys.galoistools. func polyPowMod(f *Poly, n *big.Int, g *Poly) (h *Poly, err error) { zero := big.NewInt(int64(0)) one := big.NewInt(int64(1)) n = big.NewInt(int64(0)).Set(n) if n.BitLen() < 3 { // Small values of n not useful for recon err = powModSmallN return } h = NewPoly(Zi(f.p, 1)) for { if n.Bit(0) > 0 { h = NewPoly().Mul(h, f) h, err = PolyMod(h, g) if err != nil { return } n.Sub(n, one) } n.Rsh(n, 1) if n.Cmp(zero) == 0 { break } f = NewPoly().Mul(f, f) f, err = PolyMod(f, g) if err != nil { return } } return }
func TestModAdc(t *testing.T) { A := new(big.Int) B := new(big.Int) C := new(big.Int) Carry := new(big.Int) Mask := new(big.Int) for _, a := range numbers { A.SetUint64(a) for _, b := range numbers { B.SetUint64(b) for width := uint8(1); width < 64; width++ { carry := b c := mod_adc(a, width, &carry) C.Add(A, B) Carry.Rsh(C, uint(width)) expectedCarry := Carry.Uint64() Mask.SetUint64(uint64(1)<<width - 1) C.And(C, Mask) expected := C.Uint64() if c != expected || expectedCarry != carry { t.Fatalf("adc(%d,%d,%d): Expecting %d carry %d but got %d carry %d", a, b, width, expected, expectedCarry, c, carry) } } } } }
func bigRsh(z, x, y *big.Int) *big.Int { i := y.Int64() if i < 0 { panic("negative shift") } return z.Rsh(x, uint(i)) }
// ProbablyPrimeBigInt returns true if n is prime or n is a pseudoprime to base // a. It implements the Miller-Rabin primality test for one specific value of // 'a' and k == 1. See also ProbablyPrimeUint32. func ProbablyPrimeBigInt(n, a *big.Int) bool { var d big.Int d.Set(n) d.Sub(&d, _1) // d <- n-1 s := 0 for ; d.Bit(s) == 0; s++ { } nMinus1 := big.NewInt(0).Set(&d) d.Rsh(&d, uint(s)) x := ModPowBigInt(a, &d, n) if x.Cmp(_1) == 0 || x.Cmp(nMinus1) == 0 { return true } for ; s > 1; s-- { if x = x.Mod(x.Mul(x, x), n); x.Cmp(_1) == 0 { return false } if x.Cmp(nMinus1) == 0 { return true } } return false }
func (self *Encoder) encode_int(number *big.Int, size uint) []byte { if size == 1 { return []byte{uint8(int8(number.Int64()))} } else if size == 2 { number_buf := uint16(int16(number.Int64())) return []byte{ uint8(number_buf >> 8), uint8(number_buf), } } else if size == 4 { number_buf := uint32(int32(number.Int64())) return []byte{ uint8(number_buf >> 24), uint8(number_buf >> 16), uint8(number_buf >> 8), uint8(number_buf), } } else if size == 0 { if number.Sign() < 0 { panic("jksn: number < 0") } result := []byte{uint8(new(big.Int).And(number, big.NewInt(0x7f)).Uint64())} number.Rsh(number, 7) for number.Sign() != 0 { result = append(result, uint8(new(big.Int).And(number, big.NewInt(0x7f)).Uint64())|0x80) number.Rsh(number, 7) } for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 { result[i], result[j] = result[j], result[i] } return result } else { panic("jksn: size not in (1, 2, 4, 0)") } }
// pow sets d to x ** y and returns z. func (z *Big) pow(x *Big, y *big.Int) *Big { switch { case y.Sign() < 0, (x.ez() || y.Sign() == 0): return z.SetMantScale(1, 0) case y.Cmp(oneInt) == 0: return z.Set(x) case x.ez(): if x.isOdd() { return z.Set(x) } z.form = zero return z } x0 := new(Big).Set(x) y0 := new(big.Int).Set(y) ret := New(1, 0) var odd big.Int for y0.Sign() > 0 { if odd.And(y0, oneInt).Sign() != 0 { ret.Mul(ret, x0) } y0.Rsh(y0, 1) x0.Mul(x0, x0) } *z = *ret return ret }
/* FromFactorBigInt returns n such that d | Mn if n <= max and d is odd. In other cases zero is returned. It is conjectured that every odd d ∊ N divides infinitely many Mersenne numbers. The returned n should be the exponent of smallest such Mn. NOTE: The computation of n from a given d performs roughly in O(n). It is thus highly recomended to use the 'max' argument to limit the "searched" exponent upper bound as appropriate. Otherwise the computation can take a long time as a large factor can be a divisor of a Mn with exponent above the uint32 limits. The FromFactorBigInt function is a modification of the original Will Edgington's "reverse method", discussed here: http://tech.groups.yahoo.com/group/primenumbers/message/15061 */ func FromFactorBigInt(d *big.Int, max uint32) (n uint32) { if d.Bit(0) == 0 { return } var m big.Int for n < max { m.Add(&m, d) i := 0 for ; m.Bit(i) == 1; i++ { if n == math.MaxUint32 { return 0 } n++ } m.Rsh(&m, uint(i)) if m.Sign() == 0 { if n > max { n = 0 } return } } return 0 }
func (self *Decoder) unsigned_to_signed(x *big.Int, bits uint) *big.Int { // return x - ((x >> (bits - 1)) << bits) temp := new(big.Int) temp.Rsh(x, bits-1) temp.Lsh(temp, bits) return temp.Sub(x, temp) }
// Shift returns the result of the shift expression x op s // with op == token.SHL or token.SHR (<< or >>). x must be // an Int. // func Shift(x Value, op token.Token, s uint) Value { switch x := x.(type) { case unknownVal: return x case int64Val: if s == 0 { return x } switch op { case token.SHL: z := big.NewInt(int64(x)) return normInt(z.Lsh(z, s)) case token.SHR: return x >> s } case intVal: if s == 0 { return x } var z big.Int switch op { case token.SHL: return normInt(z.Lsh(x.val, s)) case token.SHR: return normInt(z.Rsh(x.val, s)) } } panic(fmt.Sprintf("invalid shift %v %s %d", x, op, s)) }
func ratProb(mode int) func(*big.Rat) *big.Rat { return func(x *big.Rat) *big.Rat { lo := big.NewInt(0) hi := new(big.Int).Set(big2p63) n := 0 for lo.Cmp(hi) != 0 { m := new(big.Int).Add(lo, hi) m = m.Rsh(m, 1) if n++; n > 100 { fmt.Printf("??? %v %v %v\n", lo, hi, m) break } v := new(big.Rat).SetFrac(m, big2p63) f, _ := v.Float64() v.SetFloat64(f) if v.Cmp(x) < 0 { lo.Add(m, bigOne) } else { hi.Set(m) } } switch mode { default: // case 0 return new(big.Rat).SetFrac(lo, big2p63) case 1: if lo.Cmp(big.NewInt(cutoff1)) <= 0 { lo.Add(lo, big.NewInt(1<<63-cutoff1)) } return new(big.Rat).SetFrac(lo, big2p63) case 2: return new(big.Rat).SetFrac(lo, big.NewInt(cutoff1)) } } }
// ISqrt returns the greatest number x such that x^2 <= n. n must be // non-negative. // // See https://www.akalin.com/computing-isqrt for an analysis. func ISqrt(n *big.Int) *big.Int { s := n.Sign() if s < 0 { panic("negative radicand") } if s == 0 { return &big.Int{} } // x = 2^ceil(Bits(n)/2) var x big.Int x.Lsh(big.NewInt(1), (uint(n.BitLen())+1)/2) for { // y = floor((x + floor(n/x))/2) var y big.Int y.Div(n, &x) y.Add(&y, &x) y.Rsh(&y, 1) if y.Cmp(&x) >= 0 { return &x } x = y } }
// JacobiSymbol returns the jacobi symbol ( N / D ) of // N (numerator) over D (denominator). // See http://en.wikipedia.org/wiki/Jacobi_symbol func JacobiSymbol(N *big.Int, D *big.Int) int { //Step 0: parse input / easy cases if D.Sign() <= 0 || D.Bit(0) == 0 { // we will assume D is positive // wolfram is ok with negative denominator // im not sure what is standard though panic("JacobiSymbol defined for positive odd denominator only") } var n, d, tmp big.Int n.Set(N) d.Set(D) j := 1 for { // Step 1: Reduce the numerator mod the denominator n.Mod(&n, &d) if n.Sign() == 0 { // if n,d not relatively prime return 0 } if len(n.Bits()) >= len(d.Bits())-1 { // n > d/2 so swap n with d-n // and multiply j by JacobiSymbol(-1 / d) n.Sub(&d, &n) if d.Bits()[0]&3 == 3 { // if d = 3 mod 4 j = -1 * j } } // Step 2: extract factors of 2 s := trailingZeroBits(&n) n.Rsh(&n, s) if s&1 == 1 { switch d.Bits()[0] & 7 { case 3, 5: // d = 3,5 mod 8 j = -1 * j } } // Step 3: check numerator if len(n.Bits()) == 1 && n.Bits()[0] == 1 { // if n = 1 were done return j } // Step 4: flip and go back to step 1 if n.Bits()[0]&3 != 1 { // n = 3 mod 4 if d.Bits()[0]&3 != 1 { // d = 3 mod 4 j = -1 * j } } tmp.Set(&n) n.Set(&d) d.Set(&tmp) } }
func ParseId(id *big.Int) (timestamp, workerid, sequence int64) { bigS := big.NewInt(0) bigW := big.NewInt(0) bigS.And(id, big.NewInt((1<<defaultSequenceBits)-1)) id.Rsh(id, uint(defaultSequenceBits)) bigW.And(id, big.NewInt((1<<defaultWorkerIdBits)-1)) id.Rsh(id, uint(defaultWorkerIdBits)) return id.Int64(), bigW.Int64(), bigS.Int64() }
func sqrt(n *big.Int) *big.Int { a := new(big.Int) for b := new(big.Int).Set(n); ; { a.Set(b) b.Rsh(b.Add(b.Quo(n, a), a), 1) if b.Cmp(a) >= 0 { return a } } return a.SetInt64(0) }
// StakePoolTicketFee determines the stake pool ticket fee for a given ticket // from the passed percentage. Pool fee as a percentage is truncated from 0.01% // to 100.00%. This all must be done with integers, so bear with the big.Int // usage below. // // See the included doc.go of this package for more information about the // calculation of this fee. func StakePoolTicketFee(stakeDiff dcrutil.Amount, relayFee dcrutil.Amount, height int32, poolFee float64, params *chaincfg.Params) dcrutil.Amount { // Shift the decimal two places, e.g. 1.00% // to 100. This assumes that the proportion // is already multiplied by 100 to give a // percentage, thus making the entirety // be a multiplication by 10000. poolFeeAbs := math.Floor(poolFee * 100.0) poolFeeInt := int64(poolFeeAbs) // Subsidy is fetched from the blockchain package, then // pushed forward a number of adjustment periods for // compensation in gradual subsidy decay. Recall that // the average time to claiming 50% of the tickets as // votes is the approximately the same as the ticket // pool size (params.TicketPoolSize), so take the // ceiling of the ticket pool size divided by the // reduction interval. adjs := int(math.Ceil(float64(params.TicketPoolSize) / float64(params.ReductionInterval))) initSubsidyCacheOnce.Do(func() { subsidyCache = blockchain.NewSubsidyCache(int64(height), params) }) subsidy := blockchain.CalcStakeVoteSubsidy(subsidyCache, int64(height), params) for i := 0; i < adjs; i++ { subsidy *= 100 subsidy /= 101 } // The numerator is (p*10000*s*(v+z)) << 64. shift := uint(64) s := new(big.Int).SetInt64(subsidy) v := new(big.Int).SetInt64(int64(stakeDiff)) z := new(big.Int).SetInt64(int64(relayFee)) num := new(big.Int).SetInt64(poolFeeInt) num.Mul(num, s) vPlusZ := new(big.Int).Add(v, z) num.Mul(num, vPlusZ) num.Lsh(num, shift) // The denominator is 10000*(s+v). // The extra 10000 above cancels out. den := new(big.Int).Set(s) den.Add(den, v) den.Mul(den, new(big.Int).SetInt64(10000)) // Divide and shift back. num.Div(num, den) num.Rsh(num, shift) return dcrutil.Amount(num.Int64()) }
func legendre(a, p *big.Int) int { var r big.Int r.Rsh(p, 1) r.Exp(a, &r, p) switch r.BitLen() { case 0: return 0 case 1: return 1 } return -1 }
//intToBase64 makes string from int. func intToBase64(n *big.Int) string { var result string and := big.NewInt(0x3f) var tmp, nn big.Int nn.Set(n) for nn.Cmp(big.NewInt(0)) > 0 { bit := tmp.And(&nn, and).Uint64() result += string(base64en[bit]) nn.Rsh(&nn, 6) } return result + string(base64en[0]*byte(86-len(result))) }
// convert hash value to integer // [http://www.secg.org/download/aid-780/sec1-v2.pdf] func convertHash(hash []byte) *big.Int { // trim hash value (if required) maxSize := (curveN.BitLen() + 7) / 8 if len(hash) > maxSize { hash = hash[:maxSize] } // convert to integer val := new(big.Int).SetBytes(hash) val.Rsh(val, uint(maxSize*8-curveN.BitLen())) return val }
func basedSolovayStrassen(N, a *big.Int) int { // we assume N is odd x := JacobiSymbol(a, N) if x == 0 { return IsComposite } z := new(big.Int) z.Exp(a, z.Rsh(z.Sub(N, one), 1), N) // this step is expensive if (x == 1 && z.Cmp(one) == 0) || (x == -1 && z.Sub(N, z).Cmp(one) == 0) { return Undetermined } return IsComposite }
// hashToInt converts a hash value to an integer. There is some disagreement // about how this is done. [NSA] suggests that this is done in the obvious // manner, but [SECG] truncates the hash to the bit-length of the curve order // first. We follow [SECG] because that's what OpenSSL does. func hashToInt(hash []byte, c *ec256k1.BitCurve) *big.Int { orderBits := c.N.BitLen() orderBytes := (orderBits + 7) / 8 if len(hash) > orderBytes { hash = hash[:orderBytes] } ret := new(big.Int).SetBytes(hash) excess := orderBytes*8 - orderBits if excess > 0 { ret.Rsh(ret, uint(excess)) } return ret }
// IsSquare returns true if N = m^2 // for some positive integer m. // It uses newtons method and other checks. func IsSquare(N *big.Int) bool { // Step -1: check inputs if N.Sign() <= 0 { // 0 is a square if N.Sign() == 0 { return true } // negative numbers are not return false } // Step 0: Easy case if N.BitLen() < 62 { // need padding, 63 is too close to limit n := N.Int64() a := int64(math.Sqrt(float64(n))) if a*a == n { return true } return false } // Step 1.1: check if it is a square mod small power of 2 if _, ok := squaresMod128[uint8(N.Uint64())]; !ok { return false } // Setp 1.2: check if it is a square mod a small number _z := uint16(new(big.Int).Mod(N, smallSquareMod).Uint64()) if _, ok := smallSquares[_z]; !ok { return false } // Step 2: run newtons method, see // Cohen's book computational alg. number theory // Ch. 1, algorithm 1.7.1 z := new(big.Int) x := new(big.Int).Lsh(one, uint(N.BitLen()+2)>>1) y := new(big.Int) for { // Set y = [(x + [N/x])/2] y := y.Rsh(z.Add(x, z.Div(N, x)), 1) // if y < x, set x to y // else return x if y.Cmp(x) == -1 { x.Set(y) } else { return z.Mul(x, x).Cmp(N) == 0 } } }
// hashToInt converts a hash value to an integer. There is some disagreement // about how this is done. [NSA] suggests that this is done in the obvious // manner, but [SECG] truncates the hash to the bit-length of the curve order // first. We follow [SECG] because that's what OpenSSL does. Additionally, // OpenSSL right shifts excess bits from the number if the hash is too large // and we mirror that too. func hashToInt(hash []byte, c elliptic.Curve) *big.Int { orderBits := c.Params().N.BitLen() orderBytes := (orderBits + 7) / 8 if len(hash) > orderBytes { hash = hash[:orderBytes] } ret := new(big.Int).SetBytes(hash) excess := len(hash)*8 - orderBits if excess > 0 { ret.Rsh(ret, uint(excess)) } return ret }
func binaryIntOp(x *big.Int, op token.Token, y *big.Int) interface{} { var z big.Int switch op { case token.ADD: return z.Add(x, y) case token.SUB: return z.Sub(x, y) case token.MUL: return z.Mul(x, y) case token.QUO: return z.Quo(x, y) case token.REM: return z.Rem(x, y) case token.AND: return z.And(x, y) case token.OR: return z.Or(x, y) case token.XOR: return z.Xor(x, y) case token.AND_NOT: return z.AndNot(x, y) case token.SHL: // The shift length must be uint, or untyped int and // convertible to uint. // TODO 32/64bit if y.BitLen() > 32 { panic("Excessive shift length") } return z.Lsh(x, uint(y.Int64())) case token.SHR: if y.BitLen() > 32 { panic("Excessive shift length") } return z.Rsh(x, uint(y.Int64())) case token.EQL: return x.Cmp(y) == 0 case token.NEQ: return x.Cmp(y) != 0 case token.LSS: return x.Cmp(y) < 0 case token.LEQ: return x.Cmp(y) <= 0 case token.GTR: return x.Cmp(y) > 0 case token.GEQ: return x.Cmp(y) >= 0 } panic("unreachable") }
// BinomialS computes the binomial coefficient C(n,k) using prime number // sieve p. BinomialS returns nil if p is too small. Otherwise it leaves // the result in z, replacing the existing value of z, and returning z. func BinomialS(z *big.Int, p *sieve.Sieve, n, k uint) *big.Int { if uint64(n) > p.Lim { return nil } if k > n { return z.SetInt64(0) } if k > n/2 { k = n - k } if k < 3 { switch k { case 0: return z.SetInt64(1) case 1: return z.SetInt64(int64(n)) case 2: var n1 big.Int return z.Rsh(z.Mul(z.SetInt64(int64(n)), n1.SetInt64(int64(n-1))), 1) } } rootN := uint64(xmath.FloorSqrt(n)) var factors []uint64 p.Iterate(2, rootN, func(p uint64) (terminate bool) { var r, nn, kk uint64 = 0, uint64(n), uint64(k) for nn > 0 { if nn%p < kk%p+r { r = 1 factors = append(factors, p) } else { r = 0 } nn /= p kk /= p } return }) p.Iterate(rootN+1, uint64(n/2), func(p uint64) (terminate bool) { if uint64(n)%p < uint64(k)%p { factors = append(factors, p) } return }) p.Iterate(uint64(n-k+1), uint64(n), func(p uint64) (terminate bool) { factors = append(factors, p) return }) return xmath.Product(z, factors) }
// sqrtMod computes z = sqrt(x) % p. func sqrtMod(x *big.Int, p *big.Int) (z *big.Int) { /* assert that p % 4 == 3 */ if new(big.Int).Mod(p, big.NewInt(4)).Cmp(big.NewInt(3)) != 0 { panic("p is not equal to 3 mod 4!") } /* z = sqrt(x) % p = x^((p+1)/4) % p */ /* e = (p+1)/4 */ e := new(big.Int).Add(p, big.NewInt(1)) e = e.Rsh(e, 2) z = expMod(x, e, p) return z }
func (enc *Encoding) decodeBlock(dst []byte, src []byte, baseOffset int) (int, int, error) { si := 0 // source index numGoodChars := 0 res := new(big.Int) for i, b := range src { v := enc.decodeMap[b] si++ if v == invalidByte { return 0, 0, CorruptInputError(i + baseOffset) } if v == skipByte { continue } numGoodChars++ res.Mul(res, enc.baseBig) res.Add(res, big.NewInt(int64(v))) if numGoodChars == enc.baseXBlockLen { break } } if !enc.IsValidEncodingLength(numGoodChars) { return 0, 0, ErrInvalidEncodingLength } paddedLen := enc.DecodedLen(numGoodChars) // Compute the corresponding right shift, to move the number // over to its natural base. res = res.Rsh(res, enc.extraBits(paddedLen, numGoodChars)) // Use big-endian representation (the default with Go's library) raw := res.Bytes() p := 0 if len(raw) < paddedLen { p = paddedLen - len(raw) copy(dst, bytes.Repeat([]byte{0}, p)) } copy(dst[p:paddedLen], raw) return paddedLen, si, nil }
// Mod sets mod to n % Mexp and returns mod. It panics for exp == 0 || exp >= // math.MaxInt32 || n < 0. func Mod(mod, n *big.Int, exp uint32) *big.Int { if exp == 0 || exp >= math.MaxInt32 || n.Sign() < 0 { panic(0) } m := New(exp) mod.Set(n) var x big.Int for mod.BitLen() > int(exp) { x.Set(mod) x.Rsh(&x, uint(exp)) mod.And(mod, m) mod.Add(mod, &x) } if mod.BitLen() == int(exp) && mod.Cmp(m) == 0 { mod.SetInt64(0) } return mod }