示例#1
1
func floor(n *big.Rat) *big.Rat {
	f := &big.Rat{}
	z := new(big.Int)
	z.Div(n.Num(), n.Denom())
	f.SetInt(z)
	return f
}
示例#2
0
// Encode encodes src into EncodedMaxLen(len(src))
// or fewer bytes of dst. It returns the number of bytes written to dst.
func Encode(dst, src []byte) int {
	zeros := 0
	for _, b := range src {
		if int(b) == 0 {
			zeros++
		} else {
			break
		}
	}
	i := new(big.Int).SetBytes(src)
	big58 := big.NewInt(58)
	big0 := big.NewInt(0)

	var index int
	for i.Cmp(big0) > 0 {
		tmp := new(big.Int).Mod(i, big58)
		i.Div(i, big58)
		dst[index] = base58alphabet[tmp.Int64()]
		index++
	}
	for ; zeros > 0; zeros-- {
		dst[index] = base58alphabet[0]
		index++
	}
	reverseInplace(dst[0:index])
	return index
}
示例#3
0
func (self *GasPriceOracle) SuggestPrice() *big.Int {
	self.lastBaseMutex.Lock()
	base := self.lastBase
	self.lastBaseMutex.Unlock()

	if base == nil {
		base = self.eth.GpoMinGasPrice
	}
	if base == nil {
		return big.NewInt(10000000000000) // apparently MinGasPrice is not initialized during some tests
	}

	baseCorr := new(big.Int).Mul(base, big.NewInt(int64(self.eth.GpobaseCorrectionFactor)))
	baseCorr.Div(baseCorr, big.NewInt(100))

	if baseCorr.Cmp(self.eth.GpoMinGasPrice) < 0 {
		return self.eth.GpoMinGasPrice
	}

	if baseCorr.Cmp(self.eth.GpoMaxGasPrice) > 0 {
		return self.eth.GpoMaxGasPrice
	}

	return baseCorr
}
示例#4
0
func calcDifficultyFrontier(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
	diff := new(big.Int)
	adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
	bigTime := new(big.Int)
	bigParentTime := new(big.Int)

	bigTime.SetUint64(time)
	bigParentTime.SetUint64(parentTime)

	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
		diff.Add(parentDiff, adjust)
	} else {
		diff.Sub(parentDiff, adjust)
	}
	if diff.Cmp(params.MinimumDifficulty) < 0 {
		diff.Set(params.MinimumDifficulty)
	}

	periodCount := new(big.Int).Add(parentNumber, common.Big1)
	periodCount.Div(periodCount, ExpDiffPeriod)
	if periodCount.Cmp(common.Big1) > 0 {
		// diff = diff + 2^(periodCount - 2)
		expDiff := periodCount.Sub(periodCount, common.Big2)
		expDiff.Exp(common.Big2, expDiff, nil)
		diff.Add(diff, expDiff)
		diff = common.BigMax(diff, params.MinimumDifficulty)
	}

	return diff
}
示例#5
0
文件: isqrt.go 项目: akalin/iroot
// 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
	}
}
示例#6
0
文件: header.go 项目: martindale/lnd
/* calcDiff returns a bool given two block headers.  This bool is
true if the correct dificulty adjustment is seen in the "next" header.
Only feed it headers n-2016 and n-1, otherwise it will calculate a difficulty
when no adjustment should take place, and return false.
Note that the epoch is actually 2015 blocks long, which is confusing. */
func calcDiffAdjust(start, end wire.BlockHeader, p *chaincfg.Params) uint32 {
	duration := end.Timestamp.UnixNano() - start.Timestamp.UnixNano()
	if duration < minRetargetTimespan {
		log.Printf("whoa there, block %s off-scale high 4X diff adjustment!",
			end.BlockSha().String())
		duration = minRetargetTimespan
	} else if duration > maxRetargetTimespan {
		log.Printf("Uh-oh! block %s off-scale low 0.25X diff adjustment!\n",
			end.BlockSha().String())
		duration = maxRetargetTimespan
	}

	// calculation of new 32-byte difficulty target
	// first turn the previous target into a big int
	prevTarget := blockchain.CompactToBig(start.Bits)
	// new target is old * duration...
	newTarget := new(big.Int).Mul(prevTarget, big.NewInt(duration))
	// divided by 2 weeks
	newTarget.Div(newTarget, big.NewInt(int64(targetTimespan)))

	// clip again if above minimum target (too easy)
	if newTarget.Cmp(p.PowLimit) > 0 {
		newTarget.Set(p.PowLimit)
	}

	// calculate and return 4-byte 'bits' difficulty from 32-byte target
	return blockchain.BigToCompact(newTarget)
}
示例#7
0
func (d *biasedEcdsa) Sign(m []byte) (*big.Int, *big.Int) {
	h := sha1.New()
	if n, err := h.Write(m); n != len(m) || err != nil {
		log.Fatal("Error calculating hash")
	}
	e := h.Sum(nil)
	r, s := new(big.Int), new(big.Int)
	n := d.g.Size()
	z := new(big.Int).SetBytes(e)
	z.Mod(z, n)
	for r.Cmp(new(big.Int)) == 0 || s.Cmp(new(big.Int)) == 0 {
		k := new(big.Int).Rand(rnd, n)
		if k.Cmp(new(big.Int)) == 0 {
			continue
		}
		log.Printf("Original k: %x", k)
		k.Div(k, big.NewInt(1<<d.bias)).Mul(k, big.NewInt(1<<d.bias))
		log.Printf("Biased k:   %x", k)
		p := d.g.Pow(d.g.Generator(), k)
		r.Mod(p.(*ellipticCurveElement).x, n)

		k.ModInverse(k, n)
		s.Mul(r, d.key)
		s.Add(s, z)
		s.Mul(s, k)
		s.Mod(s, n)
	}
	return r, s
}
示例#8
0
// CalcGasLimit computes the gas limit of the next block after parent.
// The result may be modified by the caller.
// This is miner strategy, not consensus protocol.
func CalcGasLimit(parent *types.Block) *big.Int {
	// contrib = (parentGasUsed * 3 / 2) / 1024
	contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
	contrib = contrib.Div(contrib, big.NewInt(2))
	contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)

	// decay = parentGasLimit / 1024 -1
	decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
	decay.Sub(decay, big.NewInt(1))

	/*
		strategy: gasLimit of block-to-mine is set based on parent's
		gasUsed value.  if parentGasUsed > parentGasLimit * (2/3) then we
		increase it, otherwise lower it (or leave it unchanged if it's right
		at that usage) the amount increased/decreased depends on how far away
		from parentGasLimit * (2/3) parentGasUsed is.
	*/
	gl := new(big.Int).Sub(parent.GasLimit(), decay)
	gl = gl.Add(gl, contrib)
	gl.Set(common.BigMax(gl, params.MinGasLimit))

	// however, if we're now below the target (TargetGasLimit) we increase the
	// limit as much as we can (parentGasLimit / 1024 -1)
	if gl.Cmp(params.TargetGasLimit) < 0 {
		gl.Add(parent.GasLimit(), decay)
		gl.Set(common.BigMin(gl, params.TargetGasLimit))
	}
	return gl
}
示例#9
0
文件: combat.go 项目: BenLubar/Rnoadm
func (o *CombatObject) Think() {
	o.LivingObject.Think()

	max := o.Outer().(Combat).MaxHealth()

	o.mtx.Lock()
	if o.combatTicks > 0 {
		o.combatTicks--
	}

	if o.damaged.Sign() > 0 && o.damaged.Cmp(max) < 0 {
		var regen big.Int
		if o.combatTicks > 0 {
			regen.Div(o.Outer().(StatLike).Stat(StatHealthRegen), TuningHealthRegenDivisorCombat)
		} else {
			regen.Div(o.Outer().(StatLike).Stat(StatHealthRegen), TuningHealthRegenDivisorNonCombat)
		}
		o.damaged.Sub(&o.damaged, &regen)
		if o.damaged.Sign() < 0 {
			o.damaged.SetUint64(0)
		}
		if pos := o.Position(); pos != nil {
			o.mtx.Unlock()
			pos.Zone().Update(pos, o.Outer())
			return
		}
	}

	if o.damaged.Cmp(max) >= 0 {
		o.mtx.Unlock()
		o.Outer().(Combat).Die()
		return
	}
	o.mtx.Unlock()
}
示例#10
0
// normalizeBigInt divides off all trailing zeros from the provided big.Int.
// It will only modify the provided big.Int if copyOnWrite is not set, and
// it will use the formatted representation of the big.Int if it is provided.
func normalizeBigInt(bi *big.Int, copyOnWrite bool, formatted, tmp []byte) *big.Int {
	tens := 0
	if formatted != nil {
		tens = trailingZerosFromBytes(formatted)
	} else {
		tens = trailingZeros(bi, tmp)
	}
	if tens > 0 {
		// If the decimal's big.Int hasn't been copied already, copy
		// it now because we will be modifying it.
		from := bi
		if copyOnWrite {
			bi = new(big.Int)
		}

		var div *big.Int
		switch tens {
		case 1:
			div = bigInt10
		case 2:
			div = bigInt100
		case 3:
			div = bigInt1000
		default:
			div = big.NewInt(10)
			pow := big.NewInt(int64(tens))
			div.Exp(div, pow, nil)
		}
		bi.Div(from, div)
	}
	return bi
}
示例#11
0
// String returns a float string representation of a Decimal
func (d Decimal) String() string {
	// Retrieve a copy of the Decimal's internal big.Rat denominator
	denom := new(big.Int)
	denom.Set(d.rational.Denom())
	// Discover the precision of the denominator and use it to fix
	// the precision of the string conversion
	var precision = 0
	one := big.NewInt(1)
	ten := big.NewInt(10)
	for denom.Cmp(one) > 0 {
		denom = denom.Div(denom, ten)
		precision++
	}

	if !d.finite {
		if d.rational.Sign() == 1 {
			return "Infinity"
		} else if d.rational.Sign() == -1 {
			return "-Infinity"
		} else {
			return "NaN"
		}
	}

	return d.rational.FloatString(precision)
}
示例#12
0
文件: comma.go 项目: BenLubar/Rnoadm
// Ported to math/big.Int from github.com/dustin/go-humanize
func Comma(v *big.Int) string {
	{
		var copy big.Int
		copy.Set(v)
		v = &copy
	}
	sign := ""
	if v.Sign() < 0 {
		sign = "-"
		v.Abs(v)
	}

	tmp := &big.Int{}
	herman := big.NewInt(999)
	thousand := big.NewInt(1000)
	var parts []string

	for v.Cmp(herman) > 0 {
		part := tmp.Mod(v, thousand).String()
		switch len(part) {
		case 2:
			part = "0" + part
		case 1:
			part = "00" + part
		}
		v.Div(v, thousand)
		parts = append(parts, part)
	}
	parts = append(parts, v.String())
	for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
		parts[i], parts[j] = parts[j], parts[i]
	}
	return sign + strings.Join(parts, ",")
}
示例#13
0
文件: paillier.go 项目: bfix/gospel
// NewPaillierPrivateKey generates a new Paillier private key (key pair).
//
// The key used in the Paillier crypto system consists of four integer
// values. The public key has two parameters; the private key has three
// parameters (one parameter is shared between the keys). As in RSA it
// starts with two random primes 'p' and 'q'; the public key parameter
// are computed as:
//
//   n := p * q
//   g := random number from interval [0,n^2[
//
// The private key parameters are computed as:
//
//   n := p * q
//   l := lcm (p-1,q-1)
//   u := (((g^l mod n^2)-1)/n) ^-1 mod n
//
// N.B. The division by n is integer based and rounds toward zero!
func NewPaillierPrivateKey(bits int) (key *PaillierPrivateKey, err error) {

	// generate primes 'p' and 'q' and their factor 'n'
	// repeat until the requested factor bitsize is reached
	var p, q, n *big.Int
	for {
		bitsP := (bits - 5) / 2
		bitsQ := bits - bitsP

		p, err = rand.Prime(rand.Reader, bitsP)
		if err != nil {
			return nil, err
		}
		q, err = rand.Prime(rand.Reader, bitsQ)
		if err != nil {
			return nil, err
		}

		n = new(big.Int).Mul(p, q)
		if n.BitLen() == bits {
			break
		}
	}

	// initialize variables
	one := big.NewInt(1)
	n2 := new(big.Int).Mul(n, n)

	// compute public key parameter 'g' (generator)
	g, err := rand.Int(rand.Reader, n2)
	if err != nil {
		return nil, err
	}

	// compute private key parameters
	p1 := new(big.Int).Sub(p, one)
	q1 := new(big.Int).Sub(q, one)
	l := new(big.Int).Mul(q1, p1)
	l.Div(l, new(big.Int).GCD(nil, nil, p1, q1))

	a := new(big.Int).Exp(g, l, n2)
	a.Sub(a, one)
	a.Div(a, n)
	u := new(big.Int).ModInverse(a, n)

	// return key pair
	pubkey := &PaillierPublicKey{
		N: n,
		G: g,
	}
	prvkey := &PaillierPrivateKey{
		PaillierPublicKey: pubkey,
		L:                 l,
		U:                 u,
		P:                 p,
		Q:                 q,
	}
	return prvkey, nil
}
示例#14
0
func c(n int64, k int64) *big.Int {
	var result *big.Int
	var denominator big.Int
	result = big.NewInt(0)
	denominator.Mul(fact(k), fact(n-k))
	result.Div(fact(n), &denominator)
	return result
}
示例#15
0
func (t *lft) safe(n *big.Int) bool {
	r := t.extr(four)
	var f big.Int
	if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {
		return true
	}
	return false
}
示例#16
0
func (m *Material) Info() [][][2]string {
	var info [][][2]string

	maybe := func(name string, stat world.Stat) {
		var total, volume, tmp big.Int
		for _, c := range m.components {
			tmp.SetUint64(c.volume)
			volume.Add(&volume, &tmp)
			total.Add(&total, tmp.Mul(c.data().Stat(stat), &tmp))
		}
		if volume.Sign() == 0 {
			return
		}
		total.Div(tmp.Mul(&total, &m.quality), &volume)
		switch total.Sign() {
		case 0:
			return
		case 1:
			info = append(info, [][2]string{
				{"+" + Comma(&total), "#4f4"},
				{name, "#ccc"},
			})
		case -1:
			info = append(info, [][2]string{
				{Comma(&total), "#f44"},
				{name, "#ccc"},
			})
		}
	}

	maybe(" power", world.StatPower)
	maybe(" magic", world.StatMagic)
	maybe(" agility", world.StatAgility)
	maybe(" luck", world.StatLuck)
	maybe(" intelligence", world.StatIntelligence)
	maybe(" stamina", world.StatStamina)
	maybe(" integrity", world.StatIntegrity)

	maybe(" melee damage", world.StatMeleeDamage)
	maybe(" magic damage", world.StatMagicDamage)
	maybe(" mana", world.StatMana)
	maybe(" mana regen", world.StatManaRegen)
	maybe(" crit chance", world.StatCritChance)
	maybe(" attack speed", world.StatAttackSpeed)

	maybe(" melee armor", world.StatMeleeArmor)
	maybe(" magic armor", world.StatMagicArmor)
	maybe(" health", world.StatHealth)
	maybe(" health regen", world.StatHealthRegen)
	maybe(" resistance", world.StatResistance)
	maybe(" movement speed", world.StatMovementSpeed)

	maybe(" gathering", world.StatGathering)
	maybe(" structure health", world.StatStructureHealth)

	return info
}
示例#17
0
func FindCoFactors(q, n *big.Int, G Group) map[int64]Element {
	j := new(big.Int)
	j.Sub(n, big.NewInt(1))
	j.Div(j, q)

	groupSize := new(big.Int).Sub(n, big.NewInt(1))

	return FindFactors(j, groupSize, q, G)
}
示例#18
0
文件: sqrt.go 项目: Liamsi/crypto
// Set z to one of the square roots of a modulo p if a square root exists.
// The modulus p must be an odd prime.
// Returns true on success, false if input a is not a square modulo p.
func Sqrt(z *big.Int, a *big.Int, p *big.Int) bool {

	if a.Sign() == 0 {
		z.SetInt64(0) // sqrt(0) = 0
		return true
	}
	if Jacobi(a, p) != 1 {
		return false // a is not a square mod M
	}

	// Break p-1 into s*2^e such that s is odd.
	var s big.Int
	var e int
	s.Sub(p, one)
	for s.Bit(0) == 0 {
		s.Div(&s, two)
		e++
	}

	// Find some non-square n
	var n big.Int
	n.SetInt64(2)
	for Jacobi(&n, p) != -1 {
		n.Add(&n, one)
	}

	// Heart of the Tonelli-Shanks algorithm.
	// Follows the description in
	// "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra Brown.
	var x, b, g, t big.Int
	x.Add(&s, one).Div(&x, two).Exp(a, &x, p)
	b.Exp(a, &s, p)
	g.Exp(&n, &s, p)
	r := e
	for {
		// Find the least m such that ord_p(b) = 2^m
		var m int
		t.Set(&b)
		for t.Cmp(one) != 0 {
			t.Exp(&t, two, p)
			m++
		}

		if m == 0 {
			z.Set(&x)
			return true
		}

		t.SetInt64(0).SetBit(&t, r-m-1, 1).Exp(&g, &t, p)
		// t = g^(2^(r-m-1)) mod p
		g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
		x.Mul(&x, &t).Mod(&x, p)
		b.Mul(&b, &g).Mod(&b, p)
		r = m
	}
}
示例#19
0
文件: int.go 项目: Liamsi/crypto
// Compute the Legendre symbol of i, if modulus M is prime,
// using the Euler criterion (which involves exponentiation).
func (i *Int) legendre() int {
	var Pm1, v big.Int
	Pm1.Sub(i.M, one)
	v.Div(&Pm1, two)
	v.Exp(&i.V, &v, i.M)
	if v.Cmp(&Pm1) == 0 {
		return -1
	}
	return v.Sign()
}
示例#20
0
// Takes two large base 10 numeric strings a and b, and returns (a + b)/2
func getMiddle(lowStr, highStr string) *big.Int {
	low := bigIntFromStr(lowStr, 10)
	high := bigIntFromStr(highStr, 10)
	if low.Cmp(high) != -1 {
		die(false, "Error: %s is not smaller than %s", lowStr, highStr)
	}
	middle := new(big.Int)
	middle = middle.Div(middle.Add(low, high), big.NewInt(2))
	return middle
}
示例#21
0
// If y dividable to x without without remains
// then it  returns true and pointer to divided x parameter with final result
func IsBigDividable(x, y *big.Int) (bool, *big.Int) {
	div := big.Int{}
	div.Mod(x, y)
	if div.Int64() == 0 {
		x.Div(x, y)
		return true, x
	}

	return false, x
}
示例#22
0
func CalcGasLimit(parent *types.Block) *big.Int {
	// ((1024-1) * parent.gasLimit + (gasUsed * 6 / 5)) / 1024
	previous := new(big.Int).Mul(big.NewInt(1024-1), parent.GasLimit())
	current := new(big.Rat).Mul(new(big.Rat).SetInt(parent.GasUsed()), big.NewRat(6, 5))
	curInt := new(big.Int).Div(current.Num(), current.Denom())

	result := new(big.Int).Add(previous, curInt)
	result.Div(result, big.NewInt(1024))
	return common.BigMax(params.GenesisGasLimit, result)
}
示例#23
0
// returns (P / Q, P % Q)
func (p Poly) Div(q Poly, m *big.Int) (quo, rem Poly) {
	if m != nil {
		p.sanitize(m)
		q.sanitize(m)
	}
	if p.GetDegree() < q.GetDegree() || q.isZero() {
		quo = NewPolyInts(0)
		rem = p.Clone(0)
		return
	}
	quo = make([]*big.Int, p.GetDegree()-q.GetDegree()+1)
	rem = p.Clone(0)
	for i := 0; i < len(quo); i++ {
		quo[i] = big.NewInt(0)
	}
	t := p.Clone(0)
	qd := q.GetDegree()
	for {
		td := t.GetDegree()
		rd := td - qd
		if rd < 0 || t.isZero() {
			rem = t
			break
		}
		r := new(big.Int)
		if m != nil {
			r.ModInverse(q[qd], m)
			r.Mul(r, t[td])
			r.Mod(r, m)
		} else {
			r.Div(t[td], q[qd])
		}
		// if r == 0, it means that the highest coefficient of the result is not an integer
		// this polynomial library handles integer coefficients
		if r.Cmp(big.NewInt(0)) == 0 {
			quo = NewPolyInts(0)
			rem = p.Clone(0)
			return
		}
		u := q.Clone(rd)
		for i := rd; i < len(u); i++ {
			u[i].Mul(u[i], r)
			if m != nil {
				u[i].Mod(u[i], m)
			}
		}
		t = t.Sub(u, m)
		t.trim()
		quo[rd] = r
	}
	quo.trim()
	rem.trim()
	return
}
示例#24
0
// intToBytes conversts a big.Int to a []byte, following the conventions
// documented at bytesToInt.
func intToBytes(bi *big.Int) (bs []byte) {
	base := big.NewInt(256)
	for bi.Cmp(base) >= 0 {
		i := new(big.Int).Mod(bi, base).Int64()
		bs = append(bs, byte(i))
		bi.Sub(bi, base)
		bi.Div(bi, base)
	}
	bs = append(bs, byte(bi.Int64()))
	return bs
}
示例#25
0
func FindFactors(j, groupSize, target *big.Int, G Group) map[int64]Element {
	zero := new(big.Int)
	factors := make(map[int64]Element, 0)
	total := big.NewInt(1)
	for prime := int64(2); total.Cmp(target) < 0; prime++ {
		// Some quick exits that cover the majority of cases
		if prime > 11 {
			if prime%2 == 0 || prime%3 == 0 || prime%5 == 0 || prime%7 == 0 || prime%11 == 0 {
				continue
			}
		}
		pr := big.NewInt(prime)
		pr.Rem(j, pr)
		if pr.Cmp(zero) == 0 {
			if !big.NewInt(prime).ProbablyPrime(20) {
				continue
			}
			j2 := new(big.Int).Set(j)
			j2.Div(j, big.NewInt(prime))
			pr.Rem(j2, big.NewInt(prime))
			if pr.Cmp(zero) == 0 {
				log.Printf("Skipping double divisor %d", prime)
			} else {
				log.Printf("Found divisor %d", prime)
				factors[prime] = nil
				total.Mul(total, big.NewInt(prime))
			}
		}
		if prime > 1<<22 {
			log.Printf("Giving up with total=%s", total)
			break
		}
	}

	if G != nil {
		for factor, _ := range factors {
			var h Element = nil
			groupSize := new(big.Int).Set(groupSize)
			pow := new(big.Int)
			pow.Div(groupSize, big.NewInt(factor))
			log.Printf("Finding an element of order %d...", factor)
			for {
				h = G.Pow(G.Random(), pow)
				if h.Cmp(G.Identity()) != 0 {
					//log.Printf("%s^%d == %s", h, factor, G.Pow(h, big.NewInt(factor)))
					break
				}
			}
			factors[factor] = h
		}
	}

	return factors
}
示例#26
0
文件: dh1080.go 项目: nickvanw/bogon
// New begins the process of a Diffie-Hellman exchange for a key
// It also chooses a secret integer to return
func New() *DH1080 {
	data, _ := base64Decode(prime1080) // "a curious 1080 bit prime number"
	DH1080Ctx := &DH1080{}
	DH1080Ctx.p = new(big.Int).SetBytes(data) // p, from the curious number above
	DH1080Ctx.g = new(big.Int).SetInt64(2)    // g = 2, agreed on in a spec somewhere
	// p = 2q + 1, so q = (p - 1)/2
	sub := new(big.Int).Sub(DH1080Ctx.p, big.NewInt(1))
	DH1080Ctx.q = sub.Div(sub, big.NewInt(2))
	DH1080Ctx.State = 0
	DH1080Ctx.genPrivateKey()
	return DH1080Ctx
}
示例#27
0
func main() {
	pi := new(big.Int)
	pi.SetString("7199773997391911030609999317773941274322764333428698921736339643928346453700085358802973900485592910475480089726140708102474957429903531369589969318716771", 10)
	gi := new(big.Int)
	gi.SetString("4565356397095740655436854503483826832136106141639563487732438195343690437606117828318042418238184896212352329118608100083187535033402010599512641674644143", 10)
	q := new(big.Int)
	q.SetString("236234353446506858198510045061214171961", 10)

	G := dh.NewFiniteGroup(*pi)
	g := dh.NewFiniteElement(G, *gi)
	GG := dh.NewGeneratedGroup(G, g, *q)
	d := dh.NewDiffieHellman(GG)

	factors := dh.FindCoFactors(q, pi, G)

	moduli := make(map[int64]int64)
	total := big.NewInt(1)

	for factor, h := range factors {
		total.Mul(total, big.NewInt(factor))
		mac := Bob(d, h)
		log.Printf("Guessing the shared secret in the subgroup of order %d", factor)
		found := false
		for i := int64(1); i <= factor; i++ {
			k := G.Pow(h, big.NewInt(i))
			if hmac.Equal(mac, Sign(secretMessage, k)) {
				//log.Printf("%d^%d", elt, i)
				found = true
				moduli[factor] = i
				break
			}
		}
		if !found {
			panic("Could not guess the shared secret")
		}
	}

	// From Wikipedia CRT page
	x := new(big.Int)
	for n, a := range moduli {
		N := new(big.Int).Set(total)
		N.Div(N, big.NewInt(n))
		N.ModInverse(N, big.NewInt(n))
		N.Mul(N, total)
		N.Div(N, big.NewInt(n))
		N.Mul(N, big.NewInt(a))
		x.Add(x, N)
		x.Mod(x, total)
	}
	log.Printf("Predicted key: %d", x)

	log.Printf("%s", d)
}
示例#28
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())
}
示例#29
0
文件: p65.go 项目: benjgibbs/Go
func sumDigits(toSum *big.Int) int64 {
	sum := big.NewInt(0)
	ten := big.NewInt(10)
	add := big.NewInt(0)
	zero := big.NewInt(0)
	for toSum.Cmp(zero) > 0 {
		add.Mod(toSum, ten)
		sum.Add(sum, add)
		toSum.Div(toSum, ten)
	}
	return sum.Int64()
}
// Split splits the NamespaceRange into two nearly equal-sized ranges
// If this NamespaceRange contains a single namespace then a list containing
// this NamespaceRange is returned. Otherwise a two-element list containing
// two NamespaceRanges whose total range is identical to this
// NamespaceRange's is returned.
func (n *NamespaceRange) Split() (*NamespaceRange, *NamespaceRange) {
	if n.IsSingleNamespace() {
		return n, nil
	}
	midPoint := new(big.Int)
	midPoint.Add(namespaceToOrd(n.Start), namespaceToOrd(n.End))
	midPoint.Div(midPoint, big.NewInt(2))

	left := newNamespaceRange(n.Start, ordToNamespace(midPoint, 0))
	right := newNamespaceRange(ordToNamespace(midPoint.Add(midPoint, big.NewInt(1)), 0), n.End)

	return left, right
}