Esempio n. 1
0
// 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, ",")
}
Esempio n. 2
0
// BigComma produces a string form of the given big.Int in base 10
// with commas after every three orders of magnitude.
func BigComma(b *big.Int) string {
	sign := ""
	if b.Sign() < 0 {
		sign = "-"
		b.Abs(b)
	}

	athousand := big.NewInt(1000)
	c := (&big.Int{}).Set(b)
	_, m := oom(c, athousand)
	parts := make([]string, m+1)
	j := len(parts) - 1

	mod := &big.Int{}
	for b.Cmp(athousand) >= 0 {
		b.DivMod(b, athousand, mod)
		parts[j] = strconv.FormatInt(mod.Int64(), 10)
		switch len(parts[j]) {
		case 2:
			parts[j] = "0" + parts[j]
		case 1:
			parts[j] = "00" + parts[j]
		}
		j--
	}
	parts[j] = strconv.Itoa(int(b.Int64()))
	return sign + strings.Join(parts[j:len(parts)], ",")
}
Esempio n. 3
0
func EncodeBase58(ba []byte) []byte {
	if len(ba) == 0 {
		return nil
	}

	// Expected size increase from base58 conversion is approximately 137%, use 138% to be safe
	ri := len(ba) * 138 / 100
	ra := make([]byte, ri+1)

	x := new(big.Int).SetBytes(ba) // ba is big-endian
	x.Abs(x)
	y := big.NewInt(58)
	m := new(big.Int)

	for x.Sign() > 0 {
		x, m = x.DivMod(x, y, m)
		ra[ri] = base58[int32(m.Int64())]
		ri--
	}

	// Leading zeroes encoded as base58 zeros
	for i := 0; i < len(ba); i++ {
		if ba[i] != 0 {
			break
		}
		ra[ri] = '1'
		ri--
	}
	return ra[ri+1:]
}
Esempio n. 4
0
func (p randomPartitioner) Hash(partitionKey []byte) token {
	hash := md5.New()
	sum := hash.Sum(partitionKey)

	val := new(big.Int)
	val = val.SetBytes(sum)
	val = val.Abs(val)

	return (*randomToken)(val)
}
Esempio n. 5
0
func (p randomPartitioner) Hash(partitionKey []byte) token {
	sum := md5.Sum(partitionKey)
	val := new(big.Int)
	val.SetBytes(sum[:])
	if sum[0] > 127 {
		val.Sub(val, maxHashInt)
		val.Abs(val)
	}

	return (*randomToken)(val)
}
Esempio n. 6
0
func (p randomPartitioner) Hash(partitionKey []byte) token {
	// 2 ** 128
	maxInt := new(big.Int)
	maxInt.SetString("340282366920938463463374607431768211456", 10)

	sum := md5.Sum(partitionKey)
	val := new(big.Int)
	val.SetBytes(sum[:])
	if sum[0] > 127 {
		val.Sub(val, maxInt)
		val.Abs(val)
	}

	return (*randomToken)(val)
}
Esempio n. 7
0
// See YP section 4.3.4. "Block Header Validity"
// Validates a block. Returns an error if the block is invalid.
func ValidateHeader(pow pow.PoW, block *types.Header, parent *types.Block, checkPow, uncle bool) error {
	if big.NewInt(int64(len(block.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
		return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
	}

	if uncle {
		if block.Time.Cmp(common.MaxBig) == 1 {
			return BlockTSTooBigErr
		}
	} else {
		if block.Time.Cmp(big.NewInt(time.Now().Unix())) == 1 {
			return BlockFutureErr
		}
	}
	if block.Time.Cmp(parent.Time()) != 1 {
		return BlockEqualTSErr
	}

	expd := CalcDifficulty(block.Time.Uint64(), parent.Time().Uint64(), parent.Number(), parent.Difficulty())
	if expd.Cmp(block.Difficulty) != 0 {
		return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
	}

	var a, b *big.Int
	a = parent.GasLimit()
	a = a.Sub(a, block.GasLimit)
	a.Abs(a)
	b = parent.GasLimit()
	b = b.Div(b, params.GasLimitBoundDivisor)
	if !(a.Cmp(b) < 0) || (block.GasLimit.Cmp(params.MinGasLimit) == -1) {
		return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
	}

	num := parent.Number()
	num.Sub(block.Number, num)
	if num.Cmp(big.NewInt(1)) != 0 {
		return BlockNumberErr
	}

	if checkPow {
		// Verify the nonce of the block. Return an error if it's not valid
		if !pow.Verify(types.NewBlockWithHeader(block)) {
			return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
		}
	}

	return nil
}
Esempio n. 8
0
// Validates a header. Returns an error if the header is invalid.
//
// See YP section 4.3.4. "Block Header Validity"
func ValidateHeader(config *ChainConfig, pow pow.PoW, header *types.Header, parent *types.Header, checkPow, uncle bool) error {
	if big.NewInt(int64(len(header.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
		return fmt.Errorf("Header extra data too long (%d)", len(header.Extra))
	}

	if uncle {
		if header.Time.Cmp(common.MaxBig) == 1 {
			return BlockTSTooBigErr
		}
	} else {
		if header.Time.Cmp(big.NewInt(time.Now().Unix())) == 1 {
			return BlockFutureErr
		}
	}
	if header.Time.Cmp(parent.Time) != 1 {
		return BlockEqualTSErr
	}

	expd := CalcDifficulty(config, header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
	if expd.Cmp(header.Difficulty) != 0 {
		return fmt.Errorf("Difficulty check failed for header %v, %v", header.Difficulty, expd)
	}

	a := new(big.Int).Set(parent.GasLimit)
	a = a.Sub(a, header.GasLimit)
	a.Abs(a)
	b := new(big.Int).Set(parent.GasLimit)
	b = b.Div(b, params.GasLimitBoundDivisor)
	if !(a.Cmp(b) < 0) || (header.GasLimit.Cmp(params.MinGasLimit) == -1) {
		return fmt.Errorf("GasLimit check failed for header %v (%v > %v)", header.GasLimit, a, b)
	}

	num := new(big.Int).Set(parent.Number)
	num.Sub(header.Number, num)
	if num.Cmp(big.NewInt(1)) != 0 {
		return BlockNumberErr
	}

	if checkPow {
		// Verify the nonce of the header. Return an error if it's not valid
		if !pow.Verify(types.NewBlockWithHeader(header)) {
			return &BlockNonceErr{header.Number, header.Hash(), header.Nonce.Uint64()}
		}
	}
	// If all checks passed, validate the extra-data field for hard forks
	return ValidateDAOHeaderExtraData(config, header)
}
Esempio n. 9
0
func PageRequest(w http.ResponseWriter, r *http.Request) {
	// Default page is page 1
	if len(r.URL.Path) <= 1 {
		r.URL.Path = "/1"
	}

	// Convert page number to bignum
	page, success := new(big.Int).SetString(r.URL.Path[1:], 0)
	if !success {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Make sure page number cannot be negative or 0
	page.Abs(page)
	if page.Cmp(one) == -1 {
		page.SetInt64(1)
	}

	// Make sure we're not above page count
	if page.Cmp(pages) > 0 {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Get next and previous page numbers
	previous := new(big.Int).Sub(page, one)
	next := new(big.Int).Add(page, one)

	// Calculate our starting key from page number
	start := new(big.Int).Mul(previous, big.NewInt(ResultsPerPage))

	// Send page header
	fmt.Fprintf(w, PageTemplateHeader, page, pages, previous, next)

	// Send keys
	keys, length := compute(start)
	for i := 0; i < length; i++ {
		key := keys[i]
		fmt.Fprintf(w, KeyTemplate, key.private, key.private, key.number, key.private, key.uncompressed, key.uncompressed, key.compressed, key.compressed)
	}

	// Send page footer
	fmt.Fprintf(w, PageTemplateFooter, previous, next)
}
Esempio n. 10
0
// EncodeDecimal encodes a decimal d into a byte slice which can be sorted lexicographically later.
// EncodeDecimal guarantees that the encoded value is in ascending order for comparison.
// Decimal encoding:
// Byte -> value sign
// EncodeInt -> exp value
// EncodeBytes -> abs value bytes
func EncodeDecimal(b []byte, d mysql.Decimal) []byte {
	if d.Equals(mysql.ZeroDecimal) {
		return append(b, byte(zeroSign))
	}

	v := d.BigIntValue()
	valSign := codecSign(int64(v.Sign()))

	absVal := new(big.Int)
	absVal.Abs(v)

	// Get exp and value, format is "value":"exp".
	// like "12.34" -> "0.1234":"2".
	// like "-0.01234" -> "-0.1234":"-1".
	exp := int64(0)
	div := big.NewInt(10)
	mod := big.NewInt(0)
	value := []byte{}
	for ; ; exp++ {
		if absVal.Sign() == 0 {
			break
		}

		mod.Mod(absVal, div)
		absVal.Div(absVal, div)
		value = append([]byte(strconv.Itoa(int(mod.Int64()))), value...)
	}

	value = bytes.TrimRight(value, "0")

	expVal := exp + int64(d.Exponent())
	if valSign == negativeSign {
		expVal = -expVal
	}

	b = append(b, byte(valSign))
	b = EncodeInt(b, expVal)
	if valSign == negativeSign {
		b = EncodeBytesDesc(b, value)
	} else {
		b = EncodeBytes(b, value)
	}
	return b
}
Esempio n. 11
0
// EncodeDecimal encodes a decimal d into a byte slice which can be sorted lexicographically later.
// EncodeDecimal guarantees that the encoded value is in ascending order for comparison.
// Decimal encoding:
// EncodeInt    -> value sign
// EncodeInt    -> exp sign
// EncodeInt    -> exp value
// EncodeBytes  -> abs value bytes
func EncodeDecimal(b []byte, d mysql.Decimal) []byte {
	if d.Equals(mysql.ZeroDecimal) {
		return EncodeInt(b, zeroSign)
	}

	v := d.BigIntValue()
	valSign := codecSign(int64(v.Sign()))

	absVal := new(big.Int)
	absVal.Abs(v)

	value := []byte(absVal.String())

	// Trim right side "0", like "12.34000" -> "12.34" or "0.1234000" -> "0.1234".
	if d.Exponent() != 0 {
		value = bytes.TrimRight(value, "0")
	}

	// Get exp and value, format is "value":"exp".
	// like "12.34" -> "0.1234":"2".
	// like "-0.01234" -> "-0.1234":"-1".
	exp := int64(0)
	div := big.NewInt(10)
	for ; ; exp++ {
		if absVal.Sign() == 0 {
			break
		}
		absVal = absVal.Div(absVal, div)
	}

	expVal := exp + int64(d.Exponent())
	expSign := codecSign(expVal)

	// For negtive exp, do bit reverse for exp.
	// For negtive decimal, do bit reverse for exp and value.
	expVal = encodeExp(expVal, expSign, valSign)
	codecValue(value, valSign)

	r := EncodeInt(b, valSign)
	r = EncodeInt(r, expSign)
	r = EncodeInt(r, expVal)
	r = EncodeBytes(r, value)
	return r
}
Esempio n. 12
0
func checkGCD(n, g *big.Int) (newN, newG *big.Int, ok bool) {

	var z big.Int

	g.Abs(g)

	z.GCD(nil, nil, n, g)

	if z.Cmp(n) == 0 {
		return nil, nil, false
	}

	if z.Cmp(one) == 0 {
		return nil, nil, false
	}

	n.Div(n, &z)

	return n, &z, true
}
Esempio n. 13
0
func bigIntSqrt(number *big.Int) *big.Int {
	temp := new(big.Int)
	one := new(big.Int)
	one.SetInt64(1)

	n := new(big.Int)
	n.SetInt64(1)

	n1 := new(big.Int)
	n1 = NEXT(n, number)

	for temp.Abs(temp.Sub(n1, n)).Cmp(one) == 1 {
		n.Set(n1)
		n1 = NEXT(n, number)
	}

	for temp.Mul(n1, n1).Cmp(number) == 1 {
		n1.Sub(n1, one)
	}

	return n1
}
Esempio n. 14
0
// Validates the current block. Returns an error if the block was invalid,
// an uncle or anything that isn't on the current block chain.
// Validation validates easy over difficult (dagger takes longer time = difficult)
func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
	if big.NewInt(int64(len(block.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
		return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
	}

	expd := CalcDifficulty(block, parent)
	if expd.Cmp(block.Difficulty) != 0 {
		return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
	}

	// block.gasLimit - parent.gasLimit <= parent.gasLimit / GasLimitBoundDivisor
	a := new(big.Int).Sub(block.GasLimit, parent.GasLimit)
	a.Abs(a)
	b := new(big.Int).Div(parent.GasLimit, params.GasLimitBoundDivisor)
	if !(a.Cmp(b) < 0) || (block.GasLimit.Cmp(params.MinGasLimit) == -1) {
		return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
	}

	// Allow future blocks up to 10 seconds
	if int64(block.Time) > time.Now().Unix()+4 {
		return BlockFutureErr
	}

	if new(big.Int).Sub(block.Number, parent.Number).Cmp(big.NewInt(1)) != 0 {
		return BlockNumberErr
	}

	if block.Time <= parent.Time {
		return BlockEqualTSErr //ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
	}

	// Verify the nonce of the block. Return an error if it's not valid
	if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
		return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
	}

	return nil
}
Esempio n. 15
0
func Comma(n *big.Int) string {
	n = (&big.Int{}).Set(n) // copy

	var negative string
	if n.Cmp(zero) < 0 {
		negative = "-"
	}
	n.Abs(n)

	tmp := &big.Int{}
	var s []string
	for n.Cmp(one_thousand) >= 0 {
		tmp.Mod(n, one_thousand)
		tmp.Add(tmp, one_thousand)
		s = append(s, tmp.String()[1:])
		n.Div(n, one_thousand)
	}
	s = append(s, n.String())
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
	return negative + strings.Join(s, ",")
}
Esempio n. 16
0
// FromBigInt takes math/big Int and return KAPIID instance
func (c APIIDCtrl) FromBigInt(api *big.Int) KAPIID {
	i := new(big.Int)
	i.Abs(api)
	return KAPIID{slc: i.Bytes(), bigInt: i}
}
Esempio n. 17
0
// Returns 'ret' such that
//      ret^2 == a (mod p),
// using the Tonelli/Shanks algorithm (cf. Henri Cohen, "A Course
// in Algebraic Computational Number Theory", algorithm 1.5.1).
// 'p' must be prime!
// If 'a' is not a square, this is not necessarily detected by
// the algorithms; a bogus result must be expected in this case.
func sqrtMod(a, p *big.Int) (*big.Int, error) {
	// Translated manually from OpenSSL's implementation in bn_sqrt.c
	// Simplified to not check for primeness of p

	var r int
	var b, q, t, x, y big.Int
	var e, i, j int

	/* now write  |p| - 1  as  2^e*q  where  q  is odd */
	e = 1
	for p.Bit(e) == 0 {
		e++
	}
	/* we'll set  q  later (if needed) */
	//return nil, fmt.Errorf("a: %x p: %x e:%v", a, p, e)

	if e == 1 {
		/* The easy case:  (|p|-1)/2  is odd, so 2 has an inverse
		 * modulo  (|p|-1)/2,  and square roots can be computed
		 * directly by modular exponentiation.
		 * We have
		 *     2 * (|p|+1)/4 == 1   (mod (|p|-1)/2),
		 * so we can use exponent  (|p|+1)/4,  i.e.  (|p|-3)/4 + 1.
		 */
		q.Abs(p).Rsh(&q, 2).Add(&q, big.NewInt(1))
		q.Exp(a, &q, p)
		return &q, nil
	} else if e == 2 {
		// omitted, not used for secp256k1
		panic("Not general case, e")
	}

	// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	// Rest of this func isn't needed for secp256k1
	// -> probably not working...
	// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

	/* e > 2, so we really have to use the Tonelli/Shanks algorithm.
	 * First, find some  y  that is not a square. */
	q.Abs(p) // use 'q' as temp

	i = 2
	for {
		/* For efficiency, try small numbers first;
		 * if this fails, try random numbers.
		 */
		if i < 22 {
			y.SetInt64(int64(i))
		} else {
			panic("No nonquadratic residual found")
			/*
				if (!BN_pseudo_rand(y, BN_num_bits(p), 0, 0)) goto end;
				if (BN_ucmp(y, p) >= 0)
					{
					if (!(p->neg ? BN_add : BN_sub)(y, y, p)) goto end;
					}
				// now 0 <= y < |p|
				if (BN_is_zero(y))
					if (!BN_set_word(y, i)) goto end;
			*/
		}

		r = legendre(&y, &q) /* here 'q' is |p| */

		i++
		if r != 1 || i >= 82 {
			break
		}
	}

	if r != -1 {
		/* Many rounds and still no non-square -- this is more likely
		 * a bug than just bad luck.
		 * Even if  p  is not prime, we should have found some  y
		 * such that r == -1.
		 */
		return nil, fmt.Errorf("Too many iterations")
	}

	/* Here's our actual 'q': */
	q.Rsh(&q, uint(e))

	/* Now that we have some non-square, we can find an element
	 * of order  2^e  by computing its q'th power. */
	y.Exp(&y, &q, p)

	/* Now we know that (if  p  is indeed prime) there is an integer
	 * k,  0 <= k < 2^e,  such that
	 *
	 *      a^q * y^k == 1   (mod p).
	 *
	 * As  a^q  is a square and  y  is not,  k  must be even.
	 * q+1  is even, too, so there is an element
	 *
	 *     X := a^((q+1)/2) * y^(k/2),
	 *
	 * and it satisfies
	 *
	 *     X^2 = a^q * a     * y^k
	 *         = a,
	 *
	 * so it is the square root that we are looking for.
	 */

	/* t := (q-1)/2  (note that  q  is odd) */
	t.Rsh(&q, 1)

	/* x := a^((q-1)/2) */
	if t.BitLen() == 0 {
		/* special case: p = 2^e + 1 */
		panic("Special case not handled")
	} else {
		x.Exp(a, &t, p)
		if a.BitLen() == 0 {
			/* special case: a == 0  (mod p) */
			return new(big.Int), nil
		}
	}

	/* b := a*x^2  (= a^q) */
	b.Mul(&x, &x).Mod(&b, p).Mul(a, &b).Mod(&b, p)

	/* x := a*x    (= a^((q+1)/2)) */
	x.Mul(a, &x).Mod(&x, p)

	one := big.NewInt(1)
	for {
		/* Now  b  is  a^q * y^k  for some even  k  (0 <= k < 2^E
		 * where  E  refers to the original value of  e,  which we
		 * don't keep in a variable),  and  x  is  a^((q+1)/2) * y^(k/2).
		 *
		 * We have  a*b = x^2,
		 *    y^2^(e-1) = -1,
		 *    b^2^(e-1) = 1.
		 */

		if b.Cmp(one) == 0 {
			return new(big.Int).Set(&x), nil
		}

		/* find smallest  i  such that  b^(2^i) = 1 */
		i = 1
		t.Mul(&b, &b).Mod(&t, p)
		for t.Cmp(one) != 0 {
			i++
			if i == e {
				return nil, fmt.Errorf("Not a square: t=%v i=%v", t, i)
			}
			t.Mul(&t, &t).Mod(&t, p)
		}

		/* t := y^2^(e - i - 1) */
		t.Set(&y)
		for j = e - i - 1; j > 0; j-- {
			t.Mul(&t, &t).Mod(&t, p)
		}
		y.Mul(&t, &t).Mod(&y, p)
		x.Mul(&x, &t).Mod(&x, p)
		b.Mul(&b, &y).Mod(&b, p)
		e = i
	}

	panic("Shouldn't end up here")
}