Beispiel #1
0
func MakeRandom(gen *rand.Rand, degree int) *Polynomial {
	if degree == 0 {
		return NewPolynomialFromInt(gen.Int63n(2))
	}

	coeffs := new(big.Int)
	// x^0 + x^1 + ... + x^n => n + 1 terms
	// However, only the first n terms are variable.  (x^n is fixed to
	// have degree n.)  Thus, we randomly generate the first n terms
	// and fix the final term x^n.
	numBits := degree
	numBlocks := numBits / 32
	for ii := 0; ii < numBlocks; ii++ {
		v := gen.Uint32()

		// Merge.
		bigV := big.NewInt(int64(v))
		coeffs.Lsh(coeffs, 32).Or(coeffs, bigV)
	}
	// Handle the remainder.
	numRemainingBits := uint(numBits % 32)
	if numRemainingBits > 0 {
		mask := (int64(1) << numRemainingBits) - 1
		v := int64(gen.Uint32()) & mask
		coeffs.Lsh(coeffs, numRemainingBits).Or(coeffs, big.NewInt(v))
	}
	coeffs.SetBit(coeffs, degree, 1)
	return NewPolynomial(uint(degree), coeffs)
}
Beispiel #2
0
func (p *Polynomial) String() string {
	zero := new(big.Int)

	// As a special case, we need to handle the zero term.
	if p.degree == 0 && p.coeffs.Cmp(zero) == 0 {
		return "0"
	}

	terms := make([]string, 0)

	// We deal with sparse polynomials using big.Int's BitLen(), which
	// should be optimized for word-sized operations.  Thus, copy p and then
	// walk through the 1 bits, MSB first.
	coeffs := new(big.Int).Set(&p.coeffs)
	for coeffs.Cmp(zero) > 0 {
		deg := calcDegree(coeffs)
		if deg == 0 {
			terms = append(terms, "1")
		} else {
			terms = append(terms, fmt.Sprintf("x^%v", deg))
		}
		coeffs.SetBit(coeffs, int(deg), 0)
	}

	return strings.Join(terms, " + ")
}
Beispiel #3
0
func (z *Polynomial) Mul(x, y *Polynomial) *Polynomial {
	var zCoeffs *big.Int
	if z == x || z == y {
		// Ensure that we do not modify z if it's a parameter.
		zCoeffs = new(big.Int)
	} else {
		zCoeffs = &z.coeffs
		zCoeffs.SetInt64(0)
	}

	small, large := x, y
	if y.degree < x.degree {
		small, large = y, x
	}

	// Walk through small coeffs, shift large by the corresponding amount,
	// and accumulate in z.
	coeffs := new(big.Int).Set(&small.coeffs)
	zero := new(big.Int)
	for coeffs.Cmp(zero) > 0 {
		deg := calcDegree(coeffs)
		factor := new(big.Int).Lsh(&large.coeffs, deg)
		zCoeffs.Xor(zCoeffs, factor)

		// Prepare for next iteration.
		coeffs.SetBit(coeffs, int(deg), 0)
	}

	z.degree = calcDegree(zCoeffs)
	z.coeffs = *zCoeffs
	return z
}
func main() {
	c := exec.Command("ft", "1000000", "2", `17/91 78/85 19/51 23/38
        29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1`)
	c.Stderr = os.Stderr
	r, err := c.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}
	if err = c.Start(); err != nil {
		log.Fatal(err)
	}
	var n big.Int
	for primes := 0; primes < 20; {
		if _, err = fmt.Fscan(r, &n); err != nil {
			log.Fatal(err)
		}
		l := n.BitLen() - 1
		n.SetBit(&n, l, 0)
		if n.BitLen() == 0 && l > 1 {
			fmt.Printf("%d ", l)
			primes++
		}
	}
	fmt.Println()
}
Beispiel #5
0
func TestModPow2(t *testing.T) {
	const N = 1e3
	data := []struct{ e, m uint32 }{
		// e == 0 -> x == 0
		{0, 2},
		{0, 3},
		{0, 4},

		{1, 2},
		{1, 3},
		{1, 4},
		{1, 5},

		{2, 2},
		{2, 3},
		{2, 4},
		{2, 5},

		{3, 2},
		{3, 3},
		{3, 4},
		{3, 5},
		{3, 6},
		{3, 7},
		{3, 8},
		{3, 9},

		{4, 2},
		{4, 3},
		{4, 4},
		{4, 5},
		{4, 6},
		{4, 7},
		{4, 8},
		{4, 9},
	}

	var got big.Int
	f := func(e, m uint32) {
		x := ModPow2(e, m)
		exp := ModPow(2, e, m)
		got.SetInt64(0)
		got.SetBit(&got, int(x), 1)
		if got.Cmp(exp) != 0 {
			t.Fatalf("\ne %d, m %d\ng: %s\ne: %s", e, m, &got, exp)
		}
	}

	for _, v := range data {
		f(v.e, v.m)
	}

	rg, _ := mathutil.NewFC32(2, 1<<10, true)
	for i := 0; i < N; i++ {
		f(uint32(rg.Next()), uint32(rg.Next()))
	}
}
Beispiel #6
0
// Sets q = x / y.  Returns q and the remainder r.
func (q *Polynomial) Div(x, y *Polynomial) (*Polynomial, *Polynomial) {
	zero := new(big.Int)
	if y.degree == 0 {
		// y is 0 or 1.
		if y.coeffs.Cmp(zero) == 0 {
			panic("divide by 0")
		}
		q.Set(x)
		r := NewPolynomial(0, zero)
		return q, r
	}
	if x.degree == 0 {
		// 0 / y = 0.
		if x.coeffs.Cmp(zero) == 0 {
			q.degree = 0
			q.coeffs.Set(zero)

			r := NewPolynomial(0, zero)
			return q, r
		}
	}

	var qCoeffs *big.Int
	// Be careful not to modify any of the input parameters.
	if q == x || q == y {
		qCoeffs = new(big.Int)
	} else {
		// Re-use q to minimize allocations.
		qCoeffs = &q.coeffs
		qCoeffs.SetInt64(0)
	}

	// The remainder, which is x initially.
	r := new(Polynomial).Set(x)

	// This is just elementary long division in GF(2).
	for r.degree >= y.degree {
		// s(x) = y(x) * x^{shift_len}
		// Then, r'(x) = r(x) - s(x)

		// Record the new component in the quotient.
		shiftLen := int(r.degree - y.degree)
		qCoeffs.SetBit(qCoeffs, shiftLen, 1)

		sCoeffs := new(big.Int).Lsh(&y.coeffs, uint(shiftLen))

		// Determine r'(x) by subtracting s(x) from the remainder.
		r.coeffs.Xor(&r.coeffs, sCoeffs)
		r.degree = calcDegree(&r.coeffs)
	}
	// r.degree < y.degree at this point.

	q.coeffs = *qCoeffs
	q.degree = calcDegree(&q.coeffs)
	return q, r
}
Beispiel #7
0
func regionQuery(p int, ret *big.Int, dist *mat64.Dense, eps float64) *big.Int {
	rows, _ := dist.Dims()
	// Return any points within the Eps neighbourhood
	for i := 0; i < rows; i++ {
		if dist.At(p, i) <= eps {
			ret = ret.SetBit(ret, i, 1) // Mark as neighbour
		}
	}
	return ret
}
Beispiel #8
0
// coeffs must contain the degree of each non-zero element.
func NewPolynomialFromCoeffs(degrees []uint) *Polynomial {
	maxDegree := uint(0)
	coeffs := new(big.Int)
	for _, deg := range degrees {
		coeffs.SetBit(coeffs, int(deg), 1)
		if deg > maxDegree {
			maxDegree = deg
		}
	}
	return &Polynomial{degree: maxDegree, coeffs: *coeffs}
}
Beispiel #9
0
func benchmarkMod(b *testing.B, w, exp uint32) {
	b.StopTimer()
	var n, mod big.Int
	n.Rand(rand.New(rand.NewSource(1)), New(w))
	n.SetBit(&n, int(w), 1)
	runtime.GC()
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		Mod(&mod, &n, exp)
	}
}
Beispiel #10
0
func SetEntry(hv *big.Int, numBits int, entry *Entry) {
	mask := new(big.Int)
	for i := 0; i < numBits; i++ {
		mask.SetBit(mask, i, 1)
	}
	mv := uint64(mask.And(mask, hv).Int64())
	hv2 := new(big.Int).Rsh(hv, uint(numBits))

	entry.MValue = mv
	entry.Rank = rank(hv2)
}
Beispiel #11
0
// Set z to x, but with the bit-field from bit i
// up or down to bit j filled with bit value b.
func BitFill(z, x *big.Int, i, j int, b uint) {
	if z != x {
		z.Set(x)
	}
	inc := 1
	if i > j {
		inc = -1
	}
	for ; i != j; i += inc {
		z.SetBit(z, i, b)
	}
}
Beispiel #12
0
func main() {

	var bitVector big.Int

	var number int64 = 15
	var bitValue uint = 0
	var bitIndex int = 3

	//Setting the 3rd bit of 15 to zero
	bitVector.SetBit(big.NewInt(number), bitIndex, bitValue)

	fmt.Printf("\nSetting the bit at %d of %b to %b \n", bitIndex, number, bitValue)

	fmt.Printf("\nThe new value %d => %b \n\n", bitVector.Uint64(), bitVector.Uint64())
}
Beispiel #13
0
func instantiateINTEGER(inst *Instance, data interface{}, p *pathNode) (*Instance, error) {
	switch data := data.(type) {
	case *UnmarshalledPrimitive:
		if len(data.Data) == 0 {
			return nil, fmt.Errorf("%vAttempt to instantiate INTEGER from empty DER data", p)
		}
		var b big.Int
		b.SetBytes(data.Data)
		if data.Data[0]&128 != 0 { // negative number
			var x big.Int
			x.SetBit(&x, len(data.Data)*8, 1)
			x.Sub(&x, &b)
			b.Neg(&x)
		}
		return instantiateINTEGER(inst, &b, p)
	case *Instance:
		inst.value = data.value
	case *big.Int:
		i := int(data.Int64())
		if big.NewInt(int64(i)).Cmp(data) == 0 {
			inst.value = i // store as int if possible
		} else {
			inst.value = data // use *big.Int if necessary
		}
	case int:
		inst.value = data
	case float64:
		if math.Floor(data) != data {
			return nil, fmt.Errorf("%vAttempt to instantiate INTEGER with non-integral float64: %v", p, data)
		}
		inst.value = int(data)
	case string:
		if i, found := inst.namedints[data]; found {
			inst.value = i
		} else {
			bi := new(big.Int)
			_, ok := bi.SetString(data, 10)
			if ok {
				return instantiateINTEGER(inst, bi, p)
			} else {
				return nil, fmt.Errorf("%vAttempt to instantiate INTEGER/ENUMERATED from illegal string: %v", p, data)
			}
		}
	default:
		return nil, instantiateTypeError(p, "INTEGER", data)
	}
	return inst, nil
}
Beispiel #14
0
// Compute the inverse of the Burrows-Wheeler-Scott transform. This is done
// out-of-place.
func UnBWST(b []byte) []byte {
	sorted := make([]byte, len(b))
	copy(sorted, b)
	sort.Sort(bytesorter(sorted))
	used := new(big.Int)
	used.SetBit(used, len(b), 1) // reserve capacity
	links := make([]int, len(b))
	// TODO: use O(lg(N)) search in sorted instead of O(N) search in b
	for i, c := range sorted {
		// find the first unused index in b of c
		for j, c2 := range b {
			if c == c2 && used.Bit(j) == 0 {
				links[i] = j
				used.SetBit(used, j, 1)
				break
			}
		}
	}
	// We need to know once again whether each byte is used, so instead of
	// resetting the bitset or using more memory, we can just ask whether it's
	// unused.
	unused := used
	words := multibytesorter{}
	for i := range sorted {
		if unused.Bit(i) == 1 {
			word := []byte{}
			x := i
			for unused.Bit(x) == 1 {
				word = append(word, sorted[x])
				unused.SetBit(unused, x, 0)
				x = links[x]
			}
			words = append(words, nil)
			copy(words[1:], words)
			words[0] = word
		}
	}
	if !sort.IsSorted(words) {
		sort.Sort(words)
	}
	x := len(b)
	s := make([]byte, len(b))
	for _, word := range words {
		x -= len(word)
		copy(s[x:], word)
	}
	return s
}
Beispiel #15
0
func Test_PowerTable(t *testing.T) {
	p := NewPolynomialFromUint64(kIrreduciblePolyDegree, kIrreduciblePolyCoeffs)
	// Offset by a little bit to test forwarding.
	pt := makePowerTable(70)
	for ii := 0; ii < len(pt); ii++ {
		coeffs := new(big.Int)
		coeffs.SetBit(coeffs, 70+ii, 1)
		powerPoly := NewPolynomialFromBigInt(coeffs)
		powerPoly.Mod(powerPoly, p)
		_, cmpCoeffs := powerPoly.Uint64()
		if cmpCoeffs != pt[ii] {
			t.Error(fmt.Sprintf("mismatch term %d (0x%x, 0x%x)",
				ii, cmpCoeffs, pt[ii]))
		}
	}
}
Beispiel #16
0
// Bign produces a uniformly distributed random number in the range [0, max).
// It panics if max <= 0.
func (r RNG) Bign(max *big.Int) *big.Int {
	if max.Sign() <= 0 {
		panic("maximum zero or below")
	}
	nbits := max.BitLen() + 1
	m := new(big.Int)
	m.Sub(m.SetBit(m, nbits, 1), big.NewInt(1))
	k := new(big.Int)
	k.Rem(m, max)
	k.Sub(m, k)
	x := r.Big(nbits)
	for x.Cmp(k) > 0 {
		x = r.Big(nbits)
	}
	return x.Rem(x, max)
}
Beispiel #17
0
func generateKey(privBytes []byte) (priv *PrivateKey, err error) {
	// This function does all of the actual heavy lifting of creating a public
	// key from a raw 192 byte private key.  It is split so that the KAT tests
	// can be written easily, and not exposed since non-ephemeral keys are a
	// terrible idea.

	if len(privBytes) != Size {
		return nil, fmt.Errorf("invalid private key size %d", len(privBytes))
	}

	// To pick a private UniformDH key, we pick a random 1536-bit number,
	// and make it even by setting its low bit to 0
	privBn := new(big.Int).SetBytes(privBytes)
	wasEven := privBn.Bit(0) == 0
	privBn = privBn.SetBit(privBn, 0, 0)

	// Let x be that private key, and X = g^x (mod p).
	pubBn := new(big.Int).Exp(gen, privBn, modpGroup)
	pubAlt := new(big.Int).Sub(modpGroup, pubBn)

	// When someone sends her public key to the other party, she randomly
	// decides whether to send X or p-X.  Use the lowest most bit of the
	// private key here as the random coin flip since it is masked out and not
	// used.
	//
	// Note: The spec doesn't explicitly specify it, but here we prepend zeros
	// to the key so that it is always exactly Size bytes.
	pubBytes := make([]byte, Size)
	if wasEven {
		err = prependZeroBytes(pubBytes, pubBn.Bytes())
	} else {
		err = prependZeroBytes(pubBytes, pubAlt.Bytes())
	}
	if err != nil {
		return
	}

	priv = new(PrivateKey)
	priv.PublicKey.bytes = pubBytes
	priv.PublicKey.publicKey = pubBn
	priv.privateKey = privBn

	return
}
Beispiel #18
0
// InitParam25519 initializes an instance of the Ed25519 curve.
func (curve *TwistedEdwardsCurve) InitParam25519() {
	// The prime modulus of the field.
	// P = 2^255-19
	curve.CurveParams = new(elliptic.CurveParams)
	curve.P = new(big.Int)
	curve.P.SetBit(zero, 255, 1).Sub(curve.P, big.NewInt(19))

	// The prime order for the base point.
	// N = 2^252 + 27742317777372353535851937790883648493
	qs, _ := new(big.Int).SetString("27742317777372353535851937790883648493", 10)
	curve.N = new(big.Int)
	curve.N.SetBit(zero, 252, 1).Add(curve.N, qs) // AKA Q

	curve.A = new(big.Int)
	curve.A.SetInt64(-1).Add(curve.P, curve.A)

	// d = -121665 * inv(121666)
	da := new(big.Int).SetInt64(-121665)
	ds := new(big.Int).SetInt64(121666)
	di := curve.invert(ds)
	curve.D = new(big.Int).Mul(da, di)

	// I = expmod(2,(q-1)/4,q)
	psn := new(big.Int)
	psn.SetBit(zero, 255, 1).Sub(psn, big.NewInt(19))
	psn.Sub(psn, one)
	psn.Div(psn, four)
	curve.I = psn.Exp(two, psn, curve.P)

	// The base point.
	curve.Gx = new(big.Int)
	curve.Gx.SetString("151122213495354007725011514095885315"+
		"11454012693041857206046113283949847762202", 10)
	curve.Gy = new(big.Int)
	curve.Gy.SetString("463168356949264781694283940034751631"+
		"41307993866256225615783033603165251855960", 10)

	curve.BitSize = 256
	curve.H = 8

	// Provided for convenience since this gets computed repeatedly.
	curve.byteSize = curve.BitSize / 8
}
Beispiel #19
0
//MakePrivateKey makes privatekey from keystr
func MakePrivateKey(keystr string) (*PrivateKey, error) {
	var seedbuf [64]byte
	seed1 := md5.Sum([]byte(keystr))
	seed2 := md5.Sum([]byte(keystr + "pad1"))
	seed3 := md5.Sum([]byte(keystr + "pad2"))
	seed4 := md5.Sum([]byte(keystr + "pad3"))

	copy(seedbuf[0:16], seed1[:])
	copy(seedbuf[16:32], seed2[:])
	copy(seedbuf[32:48], seed3[:])
	copy(seedbuf[48:64], seed4[:])

	var p, q big.Int
	setBytesReverse(&p, seedbuf[0:28])
	setBytesReverse(&q, seedbuf[28:64])
	p.SetBit(&p, 215, 1)
	q.SetBit(&q, 279, 1)
	return newPrivateKey(p, q)
}
Beispiel #20
0
// Returns (degree, coefficients).
// Coefficients holds the state of the variable bits (0, 1, ..., degree - 1).
// Note that the k-th degree of a k degree polynomial is fixed (ie., 1) in
// GF(2).
//
// The result is undefined if degree > 64.
func (p *Polynomial) Uint64() (uint, uint64) {
	if p.degree > 64 {
		panic(fmt.Sprint("degree is too large", p.degree))
	}
	tmp := new(big.Int).Set(&p.coeffs)
	if p.degree == 64 {
		// First, clear the MSB (bit), since we're interested in the
		// lower bits.
		tmp.SetBit(tmp, int(p.degree), 0)
	}

	mask := big.NewInt(int64(0xffffffff))

	half := new(big.Int)
	lower := uint32(half.And(tmp, mask).Int64())
	upper := uint32(half.Rsh(tmp, 32).And(half, mask).Int64())

	v := uint64(lower) | (uint64(upper) << 32)
	return p.degree, v
}
Beispiel #21
0
// Sets p to f^2 and returns p.
func (p *Polynomial) Square(f *Polynomial) *Polynomial {
	// (\sum_i a_i x_i)^2 = \sum_i (a_i x_i \sum_j a_j x_j)
	// = \sum_i (a_i x_i * (\sum_{j \ne i} a_j x_j + a_i x_i))
	// = \sum_i (a_i^2 x_i^2) + \sum_i(a_i x_i \sum_{j \ne i} a_j x_j)
	// = \sum_i (a_i^2 x_i^2) \in GF(2)
	//
	// The cross terms will cancel out: one pair for each.

	newDeg := 2 * f.degree
	var newCoeffs *big.Int
	if f == p {
		// f can be p, so be careful not to overwrite the input.
		newCoeffs = new(big.Int)
	} else {
		// Reuse to avoid allocation.
		newCoeffs = &p.coeffs
		newCoeffs.SetInt64(0)
	}

	zero := new(big.Int)

	// Walk through each set bit and double the degree.
	coeffs := new(big.Int).Set(&f.coeffs)
	for coeffs.Cmp(zero) > 0 {
		deg := calcDegree(coeffs)
		if deg == 0 {
			newCoeffs.SetBit(newCoeffs, 0, 1)
		} else {
			newCoeffs.SetBit(newCoeffs, int(2*deg), 1)
		}
		// Eliminate.
		coeffs.SetBit(coeffs, int(deg), 0)
	}

	p.degree = newDeg
	p.coeffs = *newCoeffs
	return p
}
Beispiel #22
0
// GeneratePQ implements [2.2.1.1. Generation of p, q] in page 8
func GeneratePQ(m, L int) (p, q *big.Int) {
	// step 1: Set m' = m/160
	mp := m/160 + 1
	// step 2: Set L' = L/160
	Lp := L/160 + 1
	// step 3: Set N' = L/1024
	Np := L/1024 + 1

	var SEED *big.Int
	for {
		// step 4: Select an arbitrary bit string SEED such that the length of SEED >= m
		SEED = cryptoRandomBigInt(m / 8)
		if SEED == nil {
			continue
		}
		// step 5: Set U = 0
		U := big.NewInt(0)
		// step 6: For i = 0 to m' - 1
		//         U = U + (SHA1[SEED + i] XOR SHA1[SEED + m' + 1]) * 2^(160*i)
		for i := 0; i < mp; i++ {
			Up := new(big.Int)
			xorPart1 := new(big.Int)
			t := new(big.Int)
			t.Add(SEED, big.NewInt(int64(i))) // SEED + i
			sha := sha1.Sum(t.Bytes())
			xorPart1.SetBytes(sha[:]) // SHA1[SEED + i] -> xorPart1
			xorPart2 := new(big.Int)
			t.Add(t, big.NewInt(int64(mp))) // SEED + i + m'
			sha = sha1.Sum(t.Bytes())
			xorPart2.SetBytes(sha[:])  // SHA1[SEED + m' + i] -> xorPart2
			Up.Xor(xorPart1, xorPart2) // XOR
			v := new(big.Int)
			v.Mul(big.NewInt(160), big.NewInt(int64(i)))
			v.Exp(big.NewInt(2), v, nil) // 2^(160*i)
			Up.Mul(Up, v)
			U.Add(U, Up) // U = U + ...
		}
		// step 5: Form q from U mod (2^m), and setting MSB and LSB to 1
		t := big.NewInt(2)
		t.Exp(t, big.NewInt(160), nil)
		U.Mod(U, t)

		q = new(big.Int)
		q.Set(U)
		q.SetBit(q, 0, 1)
		q.SetBit(q, m-1, 1)

		// step 6: test whether q is prime
		if q.ProbablyPrime(100) {
			// step 7: If q is not prime then go to step 4
			break
		}
	}
	// step 8: Let counter = 0
	counter := 0
	for {
		// step 9: Set R = seed + 2*m' + (L' * counter)
		R := new(big.Int)
		R.Set(SEED)
		t := new(big.Int)
		t.Mul(big.NewInt(2), big.NewInt(int64(mp)))
		R.Add(R, t)
		t.Mul(big.NewInt(int64(Lp)), big.NewInt(int64(counter)))
		R.Add(R, t)
		// step 10: Set V = 0
		V := big.NewInt(0)
		// step 12: For i = 0 to L'-1 do V = V + SHA1(R + i) * 2^(160*i)
		for i := 0; i < Lp; i++ {
			sha := new(big.Int)
			sha.Add(R, big.NewInt(int64(i)))
			shaBytes := sha1.Sum(sha.Bytes())
			sha.SetBytes(shaBytes[:])
			second := new(big.Int)
			second.Mul(big.NewInt(160), big.NewInt(int64(i)))
			second.Exp(big.NewInt(2), second, nil)
			sha.Mul(sha, second)
			V.Add(V, sha)
		}
		// step 13: W = V mod 2^L
		W := new(big.Int)
		t.Exp(big.NewInt(2), big.NewInt(int64(L)), nil)
		W.Mod(V, t)
		// step 14: X = W OR 2^(L-1)
		X := new(big.Int)
		X.SetBit(W, L-1, 1)
		// step 15: Set p = X - (X mod (2*q)) + 1
		p = new(big.Int)
		p.Set(X)
		t.Mul(big.NewInt(2), q)
		X.Mod(X, t)
		p.Sub(p, X)
		p.Add(p, big.NewInt(1))
		// step 16: If p > 2^(L-1), test whether p is prime
		t.Exp(big.NewInt(2), big.NewInt(int64(L-1)), nil)
		if p.Cmp(t) == 1 {
			if p.ProbablyPrime(100) {
				// step 17: If p is prime, output p, q, seed, counter and stop
				break
			}
		}
		// step 18: Set counter = counter + 1
		counter++
		// step 19: If counter < (4096 * N) then go to 8
		if counter >= 4096*Np { // !! where is N? !!
			return nil, nil
		}
	}
	return
}
Beispiel #23
0
func TestOccupy(t *testing.T) {
	cases := []struct {
		clusterCIDRStr    string
		subNetMaskSize    int
		subNetCIDRStr     string
		expectedUsedBegin int
		expectedUsedEnd   int
		expectErr         bool
	}{
		{
			clusterCIDRStr:    "127.0.0.0/8",
			subNetMaskSize:    16,
			subNetCIDRStr:     "127.0.0.0/8",
			expectedUsedBegin: 0,
			expectedUsedEnd:   256,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/8",
			subNetMaskSize:    16,
			subNetCIDRStr:     "127.0.0.0/2",
			expectedUsedBegin: 0,
			expectedUsedEnd:   256,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/8",
			subNetMaskSize:    16,
			subNetCIDRStr:     "127.0.0.0/16",
			expectedUsedBegin: 0,
			expectedUsedEnd:   0,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/8",
			subNetMaskSize:    32,
			subNetCIDRStr:     "127.0.0.0/16",
			expectedUsedBegin: 0,
			expectedUsedEnd:   65535,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/7",
			subNetMaskSize:    16,
			subNetCIDRStr:     "127.0.0.0/15",
			expectedUsedBegin: 256,
			expectedUsedEnd:   257,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/7",
			subNetMaskSize:    15,
			subNetCIDRStr:     "127.0.0.0/15",
			expectedUsedBegin: 128,
			expectedUsedEnd:   128,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/7",
			subNetMaskSize:    18,
			subNetCIDRStr:     "127.0.0.0/15",
			expectedUsedBegin: 1024,
			expectedUsedEnd:   1031,
			expectErr:         false,
		},
	}

	for _, tc := range cases {
		_, clusterCIDR, err := net.ParseCIDR(tc.clusterCIDRStr)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}

		cs := newCIDRSet(clusterCIDR, tc.subNetMaskSize)

		_, subnetCIDR, err := net.ParseCIDR(tc.subNetCIDRStr)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}

		err = cs.occupy(subnetCIDR)
		if err == nil && tc.expectErr {
			t.Errorf("expected error but got none")
			continue
		}
		if err != nil && !tc.expectErr {
			t.Errorf("unexpected error: %v", err)
			continue
		}

		expectedUsed := big.Int{}
		for i := tc.expectedUsedBegin; i <= tc.expectedUsedEnd; i++ {
			expectedUsed.SetBit(&expectedUsed, i, 1)
		}
		if expectedUsed.Cmp(&cs.used) != 0 {
			t.Errorf("error")
		}
	}
}
Beispiel #24
0
// Optimized modular square root for P-256 curve, from
// "Mathematical routines for the NIST prime elliptic curves" (April 2010)
func (curve *p256) sqrt(c *big.Int) *big.Int {
	m := curve.p.P

	t1 := new(big.Int)
	t1.Mul(c, c)
	t1.Mul(t1, c) // t1 = c^(2^2-1)

	p2 := new(big.Int)
	p2.SetBit(p2, 2, 1)
	t2 := new(big.Int)
	t2.Exp(t1, p2, m)
	t2.Mul(t2, t1) // t2 = c^(2^4-1)

	p3 := new(big.Int)
	p3.SetBit(p3, 4, 1)
	t3 := new(big.Int)
	t3.Exp(t2, p3, m)
	t3.Mul(t3, t2) // t3 = c^(2^8-1)

	p4 := new(big.Int)
	p4.SetBit(p4, 8, 1)
	t4 := new(big.Int)
	t4.Exp(t3, p4, m)
	t4.Mul(t4, t3) // t4 = c^(2^16-1)

	p5 := new(big.Int)
	p5.SetBit(p5, 16, 1)
	r := new(big.Int)
	r.Exp(t4, p5, m)
	r.Mul(r, t4) // r = c^(2^32-1)

	p6 := new(big.Int)
	p6.SetBit(p6, 32, 1)
	r.Exp(r, p6, m)
	r.Mul(r, c) // r = c^(2^64-2^32+1)

	p7 := new(big.Int)
	p7.SetBit(p7, 96, 1)
	r.Exp(r, p7, m)
	r.Mul(r, c) // r = c^(2^160-2^128+2^96+1)

	p8 := new(big.Int)
	p8.SetBit(p8, 94, 1)
	r.Exp(r, p8, m)

	// r = c^(2^254-2^222+2^190+2^94) = sqrt(c) mod p256
	return r
}
Beispiel #25
0
func clearBit(n *big.Int, bitIndex int) {
	n.SetBit(n, bitIndex, 0)
}
Beispiel #26
0
func setBit(n *big.Int, bitIndex int) {
	n.SetBit(n, bitIndex, 1)
}
Beispiel #27
0
func (p *wireProtocol) paramsToBlr(transHandle int32, params []driver.Value, protocolVersion int32) ([]byte, []byte) {
	// Convert parameter array to BLR and values format.
	var v, blr []byte
	bi256 := big.NewInt(256)

	ln := len(params) * 2
	blrList := list.New()
	valuesList := list.New()
	blrList.PushBack([]byte{5, 2, 4, 0, byte(ln & 255), byte(ln >> 8)})

	if protocolVersion >= PROTOCOL_VERSION13 {
		null_indicator := new(big.Int)
		for i := len(params) - 1; i > 0; i-- {
			if params[i] == nil {
				null_indicator.SetBit(null_indicator, i, 1)
			}
		}
		n := len(params) / 8
		if len(params)%8 != 0 {
			n++
		}
		if n%4 != 0 { // padding
			n += 4 - n%4
		}
		for i := 0; i < n; i++ {
			valuesList.PushBack([]byte{byte(null_indicator.Mod(null_indicator, bi256).Int64())})
			null_indicator = null_indicator.Div(null_indicator, bi256)
		}
	}

	for _, param := range params {
		switch f := param.(type) {
		case string:
			b := str_to_bytes(f)
			if len(b) < MAX_CHAR_LENGTH {
				blr, v = _bytesToBlr(b)
			} else {
				v, _ = p.createBlob(b, transHandle)
				blr = []byte{9, 0}
			}
		case int:
			blr, v = _int32ToBlr(int32(f))
		case int16:
			blr, v = _int32ToBlr(int32(f))
		case int32:
			blr, v = _int32ToBlr(f)
		case int64:
			blr, v = _int32ToBlr(int32(f))
		case time.Time:
			if f.Year() == 0 {
				blr, v = _timeToBlr(f)
			} else {
				blr, v = _timestampToBlr(f)
			}
		case bool:
			if f {
				v = []byte{1, 0, 0, 0}
			} else {
				v = []byte{0, 0, 0, 0}
			}
			blr = []byte{23}
		case nil:
			v = []byte{}
			blr = []byte{14, 0, 0}
		case []byte:
			if len(f) < MAX_CHAR_LENGTH {
				blr, v = _bytesToBlr(f)
			} else {
				v, _ = p.createBlob(f, transHandle)
				blr = []byte{9, 0}
			}
		default:
			// can't convert directory
			b := str_to_bytes(fmt.Sprintf("%v", f))
			if len(b) < MAX_CHAR_LENGTH {
				blr, v = _bytesToBlr(b)
			} else {
				v, _ = p.createBlob(b, transHandle)
				blr = []byte{9, 0}
			}
		}
		valuesList.PushBack(v)
		if protocolVersion < PROTOCOL_VERSION13 {
			if param == nil {
				valuesList.PushBack([]byte{0xff, 0xff, 0xff, 0xff})
			} else {
				valuesList.PushBack([]byte{0, 0, 0, 0})
			}
		}
		blrList.PushBack(blr)
		blrList.PushBack([]byte{7, 0})
	}
	blrList.PushBack([]byte{255, 76}) // [blr_end, blr_eoc]

	blr = flattenBytes(blrList)
	v = flattenBytes(valuesList)

	return blr, v
}
Beispiel #28
0
// sanityCheckDomTree checks the correctness of the dominator tree
// computed by the LT algorithm by comparing against the dominance
// relation computed by a naive Kildall-style forward dataflow
// analysis (Algorithm 10.16 from the "Dragon" book).
//
func sanityCheckDomTree(f *Function) {
	n := len(f.Blocks)

	// D[i] is the set of blocks that dominate f.Blocks[i],
	// represented as a bit-set of block indices.
	D := make([]big.Int, n)

	one := big.NewInt(1)

	// all is the set of all blocks; constant.
	var all big.Int
	all.Set(one).Lsh(&all, uint(n)).Sub(&all, one)

	// Initialization.
	for i, b := range f.Blocks {
		if i == 0 || b == f.Recover {
			// A root is dominated only by itself.
			D[i].SetBit(&D[0], 0, 1)
		} else {
			// All other blocks are (initially) dominated
			// by every block.
			D[i].Set(&all)
		}
	}

	// Iteration until fixed point.
	for changed := true; changed; {
		changed = false
		for i, b := range f.Blocks {
			if i == 0 || b == f.Recover {
				continue
			}
			// Compute intersection across predecessors.
			var x big.Int
			x.Set(&all)
			for _, pred := range b.Preds {
				x.And(&x, &D[pred.Index])
			}
			x.SetBit(&x, i, 1) // a block always dominates itself.
			if D[i].Cmp(&x) != 0 {
				D[i].Set(&x)
				changed = true
			}
		}
	}

	// Check the entire relation.  O(n^2).
	// The Recover block (if any) must be treated specially so we skip it.
	ok := true
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			b, c := f.Blocks[i], f.Blocks[j]
			if c == f.Recover {
				continue
			}
			actual := b.Dominates(c)
			expected := D[j].Bit(i) == 1
			if actual != expected {
				fmt.Fprintf(os.Stderr, "dominates(%s, %s)==%t, want %t\n", b, c, actual, expected)
				ok = false
			}
		}
	}

	preorder := f.DomPreorder()
	for _, b := range f.Blocks {
		if got := preorder[b.dom.pre]; got != b {
			fmt.Fprintf(os.Stderr, "preorder[%d]==%s, want %s\n", b.dom.pre, got, b)
			ok = false
		}
	}

	if !ok {
		panic("sanityCheckDomTree failed for " + f.String())
	}

}
Beispiel #29
0
// 3f 80 80 01 UNIVERSAL 1 (BOOLEAN), CONSTRUCTED
// returns the index of the next undecoded byte
func analyseDER(der []byte, idx int, indent string, output *[]string) int {
	for idx < len(der) {
		*output = append(*output, indent)
		tag := int(der[idx])
		*output = append(*output, fmt.Sprintf("%02X", tag))
		class := tag & (128 + 64)
		constructed := (tag & 32) != 0
		tagnum := tag & 31
		if tagnum == 31 {
			tagnum = 0
			for {
				idx++
				if idx == len(der) {
					*output = append(*output, prematureEnd)
					return idx
				}
				*output = append(*output, fmt.Sprintf(" %02X", der[idx]))
				tagnum = (tagnum << 7) + int(der[idx]&127)
				if der[idx]&128 == 0 {
					break
				}
				if tagnum > 0xFFFFFF { // arbitrary cutoff for tag sizes to prevent overflow of tagnum
					*output = append(*output, " !TAG OUT OF RANGE!")
					return idx
				}
			}
		}

		classstr := TagClass[class]
		if classstr == "" {
			classstr = "CONTEXT-SPECIFIC "
		}
		*output = append(*output, fmt.Sprintf(" %v%v", classstr, tagnum))

		if class == 0 && tagnum > 0 && tagnum < 31 { // UNIVERSAL (except 0 which is reserved)
			*output = append(*output, fmt.Sprintf(" (%v)", UniversalTagName[tagnum]))
		}

		if constructed {
			*output = append(*output, " CONSTRUCTED")
		} else {
			*output = append(*output, " PRIMITIVE")
		}
		*output = append(*output, "\n")

		idx++
		if idx == len(der) {
			*output = append(*output, prematureEnd)
			return idx
		}

		*output = append(*output, fmt.Sprintf("%v%02X", indent, der[idx]))

		length := int(der[idx])
		if length <= 127 {
			*output = append(*output, fmt.Sprintf(" LENGTH %v", length))
		} else {
			length &= 127
			if length == 0 { // indefinite length
				length = -1
				if !constructed {
					*output = append(*output, fmt.Sprintf(" !PRIMITIVE ENCODING WITH INDEFINITE LENGTH!"))
					return idx
				}
				*output = append(*output, fmt.Sprintf(" INDEFINITE LENGTH"))
			} else {
				if length > 3 { // reject data structures larger than 16MB (or incorrectly encoded length)
					*output = append(*output, " !TOO MANY LENGTH OCTETS!")
					return idx
				}

				l := 0
				for length > 0 {
					idx++
					if idx == len(der) {
						*output = append(*output, prematureEnd)
						return idx
					}
					*output = append(*output, fmt.Sprintf(" %02X", der[idx]))
					l = (l << 8) + int(der[idx])
					length--
				}
				length = l
				*output = append(*output, fmt.Sprintf(" LENGTH %v", length))
			}
		}

		if tag == 0 && length == 0 { // end of contents marker
			return idx + 1
		}

		*output = append(*output, "\n")

		if constructed {
			idx++
			if length < 0 { // indefinite length
				idx = analyseDER(der, idx, indent+indentStep, output)
			} else if idx+length > len(der) { // length exceeds available data
				*output = append(*output, " !LENGTH EXCEEDS AVAILABLE DATA!")
			} else {
				idx2 := analyseDER(der[0:idx+length], idx, indent+indentStep, output)
				if idx2 != idx+length {
					*output = append(*output, " !SHORT DATA!")
				}
				idx = idx2
			}

			// if a decoding error occurred, do not continue
			if strings.HasSuffix((*output)[len(*output)-1], "!") {
				return idx
			}

		} else { // primitive
			*output = append(*output, indent)
			if length == 0 {
				*output = append(*output, "EMPTY ")
			}

			contents := ""
			already_decoded := false
			decoding := []string{}
			if length > 0 && idx+length < len(der) && ((tag&(128+64) == 128) || tag == 19 || tag == 4 || tag == 6 || tag == 12 || tag == 23 || tag == 22 || tag == 2) {
				cont := der[idx+1 : idx+1+length]
				if tag == 2 { // INTEGER
					var b big.Int
					b.SetBytes(cont)
					if cont[0]&128 != 0 { // negative number
						var x big.Int
						x.SetBit(&x, len(cont)*8, 1)
						x.Sub(&x, &b)
						b.Neg(&x)
					}
					contents = " " + b.String()
				}
				if contents == "" && (tag == 4 || tag > 31) { // try to parse as DER
					idx2 := analyseDER(cont, 0, indent+indentStep, &decoding)
					if idx2 == len(cont) && len(decoding) > 0 && !strings.HasSuffix(decoding[len(decoding)-1], "!") {
						contents = " ARE VALID DER => DECODING\n"
						already_decoded = true
						length -= len(cont)
						idx += len(cont)
					}
				}
				if contents == "" && tag != 6 && length < 80 { // try to parse as string
					contents = fmt.Sprintf(" %q", cont)
					if strings.Contains(contents, `\x`) {
						contents = ""
					}
				}
				if contents == "" && (tag == 6 || (length < 16 && length >= 4)) { // Try to parse as OID
					contents = " " + oidString(cont)
					if strings.HasSuffix(contents, "!") {
						contents = ""
					}
				}
			} // no else for error reporting here because error will be reported further below

			for !already_decoded && length > 0 {
				idx++
				if idx == len(der) {
					*output = append(*output, prematureEnd)
					return idx
				}
				*output = append(*output, fmt.Sprintf("%02X ", der[idx]))
				length--
			}

			*output = append(*output, "CONTENTS")
			if contents != "" {
				*output = append(*output, contents)

			}
			if already_decoded {
				*output = append(*output, decoding...)
			} else {
				*output = append(*output, "\n")
			}
			idx++
		}
	}

	return idx
}
func TestOccupy(t *testing.T) {
	cases := []struct {
		clusterCIDRStr    string
		subNetMaskSize    int
		subNetCIDRStr     string
		expectedUsedBegin int
		expectedUsedEnd   int
		expectErr         bool
	}{
		{
			clusterCIDRStr:    "127.0.0.0/8",
			subNetMaskSize:    16,
			subNetCIDRStr:     "127.0.0.0/8",
			expectedUsedBegin: 0,
			expectedUsedEnd:   256,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/8",
			subNetMaskSize:    16,
			subNetCIDRStr:     "127.0.0.0/2",
			expectedUsedBegin: 0,
			expectedUsedEnd:   256,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/8",
			subNetMaskSize:    16,
			subNetCIDRStr:     "127.0.0.0/16",
			expectedUsedBegin: 0,
			expectedUsedEnd:   0,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/8",
			subNetMaskSize:    32,
			subNetCIDRStr:     "127.0.0.0/16",
			expectedUsedBegin: 0,
			expectedUsedEnd:   65535,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/7",
			subNetMaskSize:    16,
			subNetCIDRStr:     "127.0.0.0/15",
			expectedUsedBegin: 256,
			expectedUsedEnd:   257,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/7",
			subNetMaskSize:    15,
			subNetCIDRStr:     "127.0.0.0/15",
			expectedUsedBegin: 128,
			expectedUsedEnd:   128,
			expectErr:         false,
		},
		{
			clusterCIDRStr:    "127.0.0.0/7",
			subNetMaskSize:    18,
			subNetCIDRStr:     "127.0.0.0/15",
			expectedUsedBegin: 1024,
			expectedUsedEnd:   1031,
			expectErr:         false,
		},
	}

	for _, tc := range cases {
		_, clusterCIDR, err := net.ParseCIDR(tc.clusterCIDRStr)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		clusterMask := clusterCIDR.Mask
		clusterMaskSize, _ := clusterMask.Size()

		ra := &rangeAllocator{
			clusterCIDR:     clusterCIDR,
			clusterIP:       clusterCIDR.IP.To4(),
			clusterMaskSize: clusterMaskSize,
			subNetMaskSize:  tc.subNetMaskSize,
			maxCIDRs:        1 << uint32(tc.subNetMaskSize-clusterMaskSize),
		}

		_, subnetCIDR, err := net.ParseCIDR(tc.subNetCIDRStr)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}

		err = ra.Occupy(subnetCIDR)
		if err == nil && tc.expectErr {
			t.Errorf("expected error but got none")
			continue
		}
		if err != nil && !tc.expectErr {
			t.Errorf("unexpected error: %v", err)
			continue
		}

		expectedUsed := big.Int{}
		for i := tc.expectedUsedBegin; i <= tc.expectedUsedEnd; i++ {
			expectedUsed.SetBit(&expectedUsed, i, 1)
		}
		if expectedUsed.Cmp(&ra.used) != 0 {
			t.Errorf("error")
		}
	}
}