Exemple #1
0
func (n *Number) UnmarshalJSON(data []byte) error {
	input := strings.TrimSpace(string(data))

	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
		input = input[1 : len(input)-1]
	}

	if len(input) == 0 {
		*n = Number(latestBlockNumber.Int64())
		return nil
	}

	in := new(big.Int)
	_, ok := in.SetString(input, 0)

	if !ok { // test if user supplied string tag
		return fmt.Errorf(`invalid number %s`, data)
	}

	if in.Cmp(earliestBlockNumber) >= 0 && in.Cmp(maxBlockNumber) <= 0 {
		*n = Number(in.Int64())
		return nil
	}

	return fmt.Errorf("blocknumber not in range [%d, %d]", earliestBlockNumber, maxBlockNumber)
}
Exemple #2
0
// Base58Encode encodes a byte slice to a modified base58 string.
func Base58Encode(b []byte, alphabet string) string {
	x := new(big.Int)
	x.SetBytes(b)

	answer := make([]byte, 0)
	for x.Cmp(bigZero) > 0 {
		mod := new(big.Int)
		x.DivMod(x, bigRadix, mod)
		answer = append(answer, alphabet[mod.Int64()])
	}

	// leading zero bytes
	for _, i := range b {
		if i != 0 {
			break
		}
		answer = append(answer, alphabet[0])
	}

	// reverse
	alen := len(answer)
	for i := 0; i < alen/2; i++ {
		answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i]
	}

	return string(answer)
}
Exemple #3
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
}
Exemple #4
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)], ",")
}
Exemple #5
0
func rand(max *big.Int) int64 {
	i, err := urandom.Int(urandom.Reader, max)
	if err != nil {
		return prandom.Int63n(max.Int64())
	}
	return i.Int64()
}
Exemple #6
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:]
}
Exemple #7
0
func Validate(user string, pass string) bool {
	sess := GetSession()
	defer sess.Close()
	authdb := sess.DB("prod").C("auth")

	var r *big.Int
	r, _ = rand.Int(rand.Reader, big.NewInt(5))
	time.Sleep(time.Duration(r.Int64()) * time.Nanosecond)

	var person S.User
	err := authdb.Find(bson.M{"user": user}).One(&person)
	if err != nil {
		fmt.Println(err)
	} else {
		hasher := sha256.New()
		hasher.Write([]byte(pass + string(person.Salt)))
		hashed := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

		if hashed == person.Pass {
			return true
		}
	}

	return false
}
Exemple #8
0
func (self *EthReg) Resolver(n *big.Int) *registrar.Registrar {
	xe := self.backend
	if n != nil {
		xe = self.backend.AtStateNum(n.Int64())
	}
	return registrar.New(xe)
}
Exemple #9
0
func setBignum(rv reflect.Value, x *big.Int) error {
	switch rv.Kind() {
	case reflect.Ptr:
		return setBignum(reflect.Indirect(rv), x)
	case reflect.Interface:
		rv.Set(reflect.ValueOf(*x))
		return nil
	case reflect.Int32:
		if x.BitLen() < 32 {
			rv.SetInt(x.Int64())
			return nil
		} else {
			return fmt.Errorf("int too big for int32 target")
		}
	case reflect.Int, reflect.Int64:
		if x.BitLen() < 64 {
			rv.SetInt(x.Int64())
			return nil
		} else {
			return fmt.Errorf("int too big for int64 target")
		}
	default:
		return fmt.Errorf("cannot assign bignum into Kind=%s Type=%s %#v", rv.Kind().String(), rv.Type().String(), rv)
	}
}
Exemple #10
0
// EncodeBigInt returns the base62 encoding of an arbitrary precision integer
func (e *Encoding) EncodeBigInt(n *big.Int) string {
	var (
		b    = make([]byte, 0)
		rem  = new(big.Int)
		bse  = new(big.Int)
		zero = new(big.Int)
	)
	bse.SetInt64(base)
	zero.SetInt64(0)

	// Progressively divide by base, until we hit zero
	// store remainder each time
	// Prepend as an additional character is the higher power
	for n.Cmp(zero) == 1 {
		n, rem = n.DivMod(n, bse, rem)
		b = append([]byte{e.encode[rem.Int64()]}, b...)
	}

	s := string(b)
	if e.padding > 0 {
		s = e.pad(s, e.padding)
	}

	return s
}
func (c *StateObject) GetInstr(pc *big.Int) *common.Value {
	if int64(len(c.code)-1) < pc.Int64() {
		return common.NewValue(0)
	}

	return common.NewValueFromBytes([]byte{c.code[pc.Int64()]})
}
Exemple #12
0
func main() {
	lim := 1000
	primes := allPrimes(lim)
	mx_cyc := 0
	mx_len := 0

	for _, i := range primes {
		j := 1
		for j < i {
			p := new(big.Int)
			*p = bigPow(10, j)
			res := new(big.Int)
			res.Mod(p, big.NewInt(int64(i)))
			if res.Int64() == 1 {
				if mx_len < j {
					mx_len = i
					mx_cyc = j
				}
				break
			}
			j++
		}
	}
	fmt.Printf("Found: 1/%d yields %d cycles\n", mx_len, mx_cyc)
}
Exemple #13
0
func (args *WhisperMessageArgs) UnmarshalJSON(b []byte) (err error) {
	var obj []struct {
		Payload  string
		To       string
		From     string
		Topics   []string
		Priority interface{}
		Ttl      interface{}
	}

	if err = json.Unmarshal(b, &obj); err != nil {
		return shared.NewDecodeParamError(err.Error())
	}

	if len(obj) < 1 {
		return shared.NewInsufficientParamsError(len(obj), 1)
	}
	args.Payload = obj[0].Payload
	args.To = obj[0].To
	args.From = obj[0].From
	args.Topics = obj[0].Topics

	var num *big.Int
	if num, err = numString(obj[0].Priority); err != nil {
		return err
	}
	args.Priority = uint32(num.Int64())

	if num, err = numString(obj[0].Ttl); err != nil {
		return err
	}
	args.Ttl = uint32(num.Int64())

	return nil
}
Exemple #14
0
func bigRsh(z, x, y *big.Int) *big.Int {
	i := y.Int64()
	if i < 0 {
		panic("negative shift")
	}
	return z.Rsh(x, uint(i))
}
Exemple #15
0
func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value {
	if int64(len(c.Code)-1) < pc.Int64() {
		return ethutil.NewValue(0)
	}

	return ethutil.NewValueFromBytes([]byte{c.Code[pc.Int64()]})
}
Exemple #16
0
func (c *Context) GetByte(n *big.Int) byte {
	if n.Cmp(big.NewInt(int64(len(c.Code)))) < 0 {
		return c.Code[n.Int64()]
	}

	return 0
}
Exemple #17
0
func (args *WaitForBlockArgs) UnmarshalJSON(b []byte) (err error) {
	var obj []interface{}
	if err := json.Unmarshal(b, &obj); err != nil {
		return shared.NewDecodeParamError(err.Error())
	}

	if len(obj) > 2 {
		return fmt.Errorf("waitForArgs needs 0, 1, 2 arguments")
	}

	// default values when not provided
	args.MinHeight = -1
	args.Timeout = -1

	if len(obj) >= 1 {
		var minHeight *big.Int
		if minHeight, err = numString(obj[0]); err != nil {
			return err
		}
		args.MinHeight = int(minHeight.Int64())
	}

	if len(obj) >= 2 {
		timeout, err := numString(obj[1])
		if err != nil {
			return err
		}
		args.Timeout = int(timeout.Int64())
	}

	return nil
}
Exemple #18
0
func readBigInt(r io.Reader, b []byte, sign byte) (interface{}, error) {
	if _, err := io.ReadFull(r, b); err != nil {
		return nil, err
	}

	size := len(b)
	hsize := size >> 1
	for i := 0; i < hsize; i++ {
		b[i], b[size-i-1] = b[size-i-1], b[i]
	}

	v := new(big.Int).SetBytes(b)
	if sign != 0 {
		v = v.Neg(v)
	}

	// try int and int64
	v64 := v.Int64()
	if x := int(v64); v.Cmp(big.NewInt(int64(x))) == 0 {
		return x, nil
	} else if v.Cmp(big.NewInt(v64)) == 0 {
		return v64, nil
	}

	return v, nil
}
Exemple #19
0
func (h *hasher) GetLoggregatorServerForAppId(appId string) string {
	var id, numberOfItems big.Int
	id.SetBytes([]byte(appId))
	numberOfItems.SetInt64(int64(len(h.items)))

	id.Mod(&id, &numberOfItems)
	return h.items[id.Int64()]
}
func newRandomInt(max *big.Int) int {
	rand, err := rand.Int(rand.Reader, max)
	if err != nil {
		// Fallback to pseudo-random
		return pseudoRand.Intn(int(max.Int64()))
	}
	return int(rand.Int64())
}
Exemple #21
0
func contains(slice []*big.Int, x *big.Int) bool {
	for _, v := range slice {
		if v.Int64() == x.Int64() {
			return true
		}
	}
	return false
}
Exemple #22
0
func (c *Closure) Gets(x, y *big.Int) *ethutil.Value {
	if x.Int64() >= int64(len(c.Code)) || y.Int64() >= int64(len(c.Code)) {
		return ethutil.NewValue(0)
	}

	partial := c.Code[x.Int64() : x.Int64()+y.Int64()]

	return ethutil.NewValue(partial)
}
Exemple #23
0
func EncodeBigInt(chars string, bigInt *big.Int) string {
	if bigInt.Cmp(big.NewInt(int64(len(chars)))) < 0 {
		return string(chars[bigInt.Int64()])
	}
	mod := big.NewInt(0)
	rest := big.NewInt(0)
	rest.DivMod(bigInt, big.NewInt(int64(len(chars))), mod)
	return EncodeBigInt(chars, rest) + string(chars[mod.Int64()])
}
Exemple #24
0
// total order of magnitude
// (same as above, but with no upper limit)
func oom(n, b *big.Int) (float64, int) {
	mag := 0
	m := &big.Int{}
	for n.Cmp(b) >= 0 {
		n.DivMod(n, b, m)
		mag++
	}
	return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
}
Exemple #25
0
func factorial(x float64) float64 {
	if x != float64(uint64(x)) {
		panic("Factorial input must be a positive integer.")
	}
	var res *big.Int = new(big.Int)
	res.MulRange(1, int64(x))

	return float64(res.Int64())
}
Exemple #26
0
func TestMarshalBigInt(t *testing.T) {
	var expected *big.Int = big.NewInt(1000)
	i64 := expected.Int64()

	actual := big.NewInt(i64)

	if expected.Cmp(actual) != 0 {
		t.Fatalf("big.Int numbers are not equal. expected: %v, actual %v", expected.String(), actual.String())
	}
}
Exemple #27
0
func (st *Stack) Get(amount *big.Int) []*big.Int {
	// offset + size <= len(data)
	length := big.NewInt(int64(len(st.data)))
	if amount.Cmp(length) <= 0 {
		start := new(big.Int).Sub(length, amount)
		return st.data[start.Int64():length.Int64()]
	}

	return nil
}
Exemple #28
0
func BenchmarkPrivateKey_MarshalBigIntInt64(b *testing.B) {
	var n *big.Int = big.NewInt(1000)
	var i64 int64 = 0

	for i := 0; i < b.N; i++ {
		i64 = n.Int64()
	}

	log.Println(i64)
}
Exemple #29
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
}
Exemple #30
0
// mul multiplies the input amount by the input price
func mul(amount int64, pricen int64, priced int64) int64 {
	var r, n, d big.Int

	r.SetInt64(amount)
	n.SetInt64(pricen)
	d.SetInt64(priced)

	r.Mul(&r, &n)
	r.Quo(&r, &d)
	return r.Int64()
}