示例#1
0
func main() {

	var iban string
	var r, s, t, st []string
	u := new(big.Int)
	v := new(big.Int)
	w := new(big.Int)

	iban = "GB82 TEST 1234 5698 7654 32"
	r = strings.Split(iban, " ")
	s = strings.Split(r[0], "")
	t = strings.Split(r[1], "")

	st = []string{strconv.Itoa(sCode[t[0]]),
		strconv.Itoa(sCode[t[1]]),
		strconv.Itoa(sCode[t[2]]),
		strconv.Itoa(sCode[t[3]]),
		strings.Join(r[2:6], ""),
		strconv.Itoa(sCode[s[0]]),
		strconv.Itoa(sCode[s[1]]),
		strings.Join(s[2:4], ""),
	}

	u.SetString(strings.Join(st, ""), 10)
	v.SetInt64(97)
	w.Mod(u, v)

	if w.Uint64() == 1 && lCode[strings.Join(s[0:2], "")] == len(strings.Join(r, "")) {
		fmt.Printf("IBAN %s looks good!\n", iban)
	} else {
		fmt.Printf("IBAN %s looks wrong!\n", iban)
	}
}
示例#2
0
文件: dagger.go 项目: codeaudit/shift
func (dag *Dagger) Node(L uint64, i uint64) *big.Int {
	if L == i {
		return dag.hash
	}

	var m *big.Int
	if L == 9 {
		m = big.NewInt(16)
	} else {
		m = big.NewInt(3)
	}

	sha := sha3.NewKeccak256()
	sha.Reset()
	d := sha3.NewKeccak256()
	b := new(big.Int)
	ret := new(big.Int)

	for k := 0; k < int(m.Uint64()); k++ {
		d.Reset()
		d.Write(dag.hash.Bytes())
		d.Write(dag.xn.Bytes())
		d.Write(big.NewInt(int64(L)).Bytes())
		d.Write(big.NewInt(int64(i)).Bytes())
		d.Write(big.NewInt(int64(k)).Bytes())

		b.SetBytes(Sum(d))
		pk := b.Uint64() & ((1 << ((L - 1) * 3)) - 1)
		sha.Write(dag.Node(L-1, pk).Bytes())
	}

	ret.SetBytes(Sum(sha))

	return ret
}
示例#3
0
func ecrecoverFunc(in []byte) []byte {
	// "in" is (hash, v, r, s), each 32 bytes
	// but for ecrecover we want (r, s, v)
	if len(in) < ecRecoverInputLength {
		return nil
	}

	// Treat V as a 256bit integer
	v := new(big.Int).Sub(common.Bytes2Big(in[32:64]), big.NewInt(27))
	// Ethereum requires V to be either 0 or 1 => (27 || 28)
	if !(v.Cmp(Zero) == 0 || v.Cmp(One) == 0) {
		return nil
	}

	// v needs to be moved to the end
	rsv := append(in[64:128], byte(v.Uint64()))
	pubKey, err := crypto.Ecrecover(in[:32], rsv)
	// make sure the public key is a valid one
	if err != nil {
		glog.V(logger.Error).Infof("EC RECOVER FAIL: ", err)
		return nil
	}

	// the first byte of pubkey is bitcoin heritage
	return common.LeftPadBytes(crypto.Sha3(pubKey[1:])[12:], 32)
}
示例#4
0
func TestJWKThumbprint(t *testing.T) {
	// Key example from RFC 7638
	const base64N = "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAt" +
		"VT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn6" +
		"4tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FD" +
		"W2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n9" +
		"1CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINH" +
		"aQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"
	const base64E = "AQAB"
	const expected = "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs"

	bytes, err := base64.RawURLEncoding.DecodeString(base64N)
	if err != nil {
		t.Fatalf("Error parsing example key N: %v", err)
	}
	n := new(big.Int).SetBytes(bytes)

	bytes, err = base64.RawURLEncoding.DecodeString(base64E)
	if err != nil {
		t.Fatalf("Error parsing example key E: %v", err)
	}
	e := new(big.Int).SetBytes(bytes)

	pub := &rsa.PublicKey{N: n, E: int(e.Uint64())}
	th := JWKThumbprint(pub)
	if th != expected {
		t.Errorf("th = %q; want %q", th, expected)
	}
}
示例#5
0
// Create a new UniformDH instance
func New() *UniformDH {
	udh := &UniformDH{}

	privStr := make([]byte, groupLen)
	// To pick a private UniformDH key, we pick a random 1536-bit number,
	// and make it even by setting its low bit to 0. Let x be that private
	// key, and X = g^x (mod p).
	rand.Read(privStr)
	udh.priv.SetBytes(privStr)

	/// XXX: is setting this bit *and* modulo 2 necessary?
	udh.priv.SetBit(&udh.priv, 0, 0)

	// When someone sends her public key to the other party, she randomly
	// decides whether to send X or p-X. This makes the public key
	// negligibly different from a uniform 1536-bit string
	flip := new(big.Int).Mod(&udh.priv, big.NewInt(2))
	udh.priv.Sub(&udh.priv, flip)

	udh.pub.Exp(big.NewInt(g), &udh.priv, &mod)

	if flip.Uint64() == 1 {
		udh.pub.Sub(&mod, &udh.pub)
	}

	/// XXX: handle erroneous situations better
	if udh.priv.BitLen() > intSize {
		panic("int too large")
	}

	return udh
}
示例#6
0
文件: dagger.go 项目: codeaudit/shift
func (dag *Dagger) Eval(N *big.Int) *big.Int {
	pow := common.BigPow(2, 26)
	dag.xn = pow.Div(N, pow)

	sha := sha3.NewKeccak256()
	sha.Reset()
	ret := new(big.Int)

	for k := 0; k < 4; k++ {
		d := sha3.NewKeccak256()
		b := new(big.Int)

		d.Reset()
		d.Write(dag.hash.Bytes())
		d.Write(dag.xn.Bytes())
		d.Write(N.Bytes())
		d.Write(big.NewInt(int64(k)).Bytes())

		b.SetBytes(Sum(d))
		pk := (b.Uint64() & 0x1ffffff)

		sha.Write(dag.Node(9, pk).Bytes())
	}

	return ret.SetBytes(Sum(sha))
}
示例#7
0
// encodeBlock fills the dst buffer with the encoding of src.
// It is assumed the buffers are appropriately sized, and no
// bounds checks are performed.  In particular, the dst buffer will
// be zero-padded from right to left in all remaining bytes.
func (enc *Encoding) encodeBlock(dst, src []byte) {

	// Interpret the block as a big-endian number (Go's default)
	num := new(big.Int).SetBytes(src)
	rem := new(big.Int)
	quo := new(big.Int)

	encodedLen := enc.EncodedLen(len(src))

	// Shift over the given number of extra Bits, so that all of our
	// wasted bits are on the right.
	num = num.Lsh(num, enc.extraBits(len(src), encodedLen))

	p := encodedLen - 1

	for num.Sign() != 0 {
		num, rem = quo.QuoRem(num, enc.baseBig, rem)
		dst[p] = enc.encode[rem.Uint64()]
		p--
	}

	// Pad the remainder of the buffer with 0s
	for p >= 0 {
		dst[p] = enc.encode[0]
		p--
	}
}
示例#8
0
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)
				}
			}
		}
	}
}
示例#9
0
func ecrecoverFunc(in []byte) []byte {
	in = common.RightPadBytes(in, 128)
	// "in" is (hash, v, r, s), each 32 bytes
	// but for ecrecover we want (r, s, v)

	r := common.BytesToBig(in[64:96])
	s := common.BytesToBig(in[96:128])
	// Treat V as a 256bit integer
	vbig := common.Bytes2Big(in[32:64])
	v := byte(vbig.Uint64())

	if !crypto.ValidateSignatureValues(v, r, s) {
		glog.V(logger.Error).Infof("EC RECOVER FAIL: v, r or s value invalid")
		return nil
	}

	// v needs to be at the end and normalized for libsecp256k1
	vbignormal := new(big.Int).Sub(vbig, big.NewInt(27))
	vnormal := byte(vbignormal.Uint64())
	rsv := append(in[64:128], vnormal)
	pubKey, err := crypto.Ecrecover(in[:32], rsv)
	// make sure the public key is a valid one
	if err != nil {
		glog.V(logger.Error).Infof("EC RECOVER FAIL: ", err)
		return nil
	}

	// the first byte of pubkey is bitcoin heritage
	return common.LeftPadBytes(crypto.Sha3(pubKey[1:])[12:], 32)
}
示例#10
0
文件: common.go 项目: codeaudit/shift
func getData(data []byte, start, size *big.Int) []byte {
	dlen := big.NewInt(int64(len(data)))

	s := common.BigMin(start, dlen)
	e := common.BigMin(new(big.Int).Add(s, size), dlen)
	return common.RightPadBytes(data[s.Uint64():e.Uint64()], int(size.Uint64()))
}
示例#11
0
func (d *DatasourceDerive) CalculatePdpPrep(newValue string, interval float64) (float64, error) {
	if float64(d.Heartbeat) < interval {
		d.LastValue = Undefined
	}

	rate := math.NaN()
	newPdp := math.NaN()
	if newValue != Undefined && float64(d.Heartbeat) >= interval {
		newInt := new(big.Int)
		_, err := fmt.Sscan(newValue, newInt)
		if err != nil {
			return math.NaN(), errors.Errorf("not a simple signed integer: %s", newValue)
		}
		if d.LastValue != "U" {
			prevInt := new(big.Int)
			_, err := fmt.Sscan(d.LastValue, prevInt)
			if err != nil {
				return math.NaN(), errors.Wrap(err, 0)
			}
			diff := new(big.Int)
			diff.Sub(newInt, prevInt)

			newPdp = float64(diff.Uint64())
			rate = newPdp / interval
		}
	}

	if !d.checkRateBounds(rate) {
		newPdp = math.NaN()
	}

	d.LastValue = newValue

	return newPdp, nil
}
示例#12
0
文件: base58.go 项目: qbit/client
// Encode58 base58 encodes the input.
func Encode58(inp []byte) string {
	num := new(big.Int).SetBytes(inp)
	buf := make([]byte, 0, len(inp))
	base := big.NewInt(int64(58))
	rem := new(big.Int)
	quo := new(big.Int)

	for num.Sign() != 0 {
		num, rem = quo.QuoRem(num, base, rem)
		c := alphabet[rem.Uint64()]
		buf = append(buf, c)
	}

	// Pad leading zeros...
	for _, c := range inp {
		if c == 0x0 {
			buf = append(buf, alphabet[0])
		} else {
			// Stop adding padding after the first nonzero byte.
			break
		}
	}
	reverseBuf(buf)

	return string(buf)
}
示例#13
0
文件: tests.go 项目: tscholl2/prime
// SmallPrimeTest determins if N is a small prime
// or divisible by a small prime.
func SmallPrimeTest(N *big.Int) int {
	if N.Sign() <= 0 {
		panic("SmallPrimeTest for positive integers only")
	}
	if N.BitLen() <= 10 {
		n := uint16(N.Uint64())
		i := sort.Search(len(primes10), func(i int) bool {
			return primes10[i] >= n
		})
		if i >= len(primes10) || n != primes10[i] {
			return IsComposite
		}
		return IsPrime
	}
	// quick test for N even
	if N.Bits()[0]&1 == 0 {
		return IsComposite
	}
	// compare several small gcds for efficency
	z := new(big.Int)
	if z.GCD(nil, nil, N, prodPrimes10A).Cmp(one) == 1 {
		return IsComposite
	}
	if z.GCD(nil, nil, N, prodPrimes10B).Cmp(one) == 1 {
		return IsComposite
	}
	if z.GCD(nil, nil, N, prodPrimes10C).Cmp(one) == 1 {
		return IsComposite
	}
	if z.GCD(nil, nil, N, prodPrimes10D).Cmp(one) == 1 {
		return IsComposite
	}
	return Undetermined
}
示例#14
0
func jump(mapping map[uint64]uint64, destinations map[uint64]struct{}, contract *Contract, to *big.Int) (uint64, error) {
	if !validDest(destinations, to) {
		nop := contract.GetOp(to.Uint64())
		return 0, fmt.Errorf("invalid jump destination (%v) %v", nop, to)
	}

	return mapping[to.Uint64()], nil
}
示例#15
0
/*	solution:
	Will rapresent the moves as R=right, D=Down....
	In any grid of size N, we need N moves of each (R,D) (total 2N moves)
		ex for the 2x2 grid we have RRDD,RDRD,RDDR,DRRD,DRDR,DDRR (6 moves)
	If we arbitrary choose N of one direction first and fill the rest
	with other direction,
	the problem becomes a combination problem for N choices out of 2N
	so we could use the C(n,k) = n!/(k!(n-k)!) for the answer
	where n = 2N and k=N
*/
func Euler015(N int) uint64 {
	n, k := (2 * N), N

	num := utils.Fact(n)
	den := new(big.Int).Mul(utils.Fact(k), utils.Fact(n-k))
	res := new(big.Int).Div(num, den)

	return res.Uint64()
}
示例#16
0
// validDest checks if the given destination is a valid one given the
// destination table of the program
func validDest(dests map[uint64]struct{}, dest *big.Int) bool {
	// PC cannot go beyond len(code) and certainly can't be bigger than 64bits.
	// Don't bother checking for JUMPDEST in that case.
	if dest.Cmp(bigMaxUint64) > 0 {
		return false
	}
	_, ok := dests[dest.Uint64()]
	return ok
}
示例#17
0
// trailingZeros counts the number of trailing zeros in the
// big.Int value. It first attempts to use an unsigned integer
// representation of the big.Int to compute this because it is
// roughly 8x faster. If this unsigned integer would overflow,
// it falls back to formatting the big.Int itself.
func trailingZeros(bi *big.Int, tmp []byte) int {
	if bi.BitLen() <= 64 {
		i := bi.Uint64()
		bs := strconv.AppendUint(tmp, i, 10)
		return trailingZerosFromBytes(bs)
	}
	bs := bi.Append(tmp, 10)
	return trailingZerosFromBytes(bs)
}
func SumBig(n *big.Int, base int) (sum int) {
	i := new(big.Int).Set(n)
	b := new(big.Int).SetUint64(uint64(base))
	r := new(big.Int)
	for i.BitLen() > 0 {
		i.DivMod(i, b, r)
		sum += int(r.Uint64())
	}
	return
}
示例#19
0
func myHashFunc(name string) int {
	data := []byte(name)
	tmp := md5.Sum(data)
	var c []byte
	for i := 14; i < 16; i++ {
		c = append(c, tmp[i])
	}
	z := new(big.Int).SetBytes(c)
	return int(z.Uint64())
}
示例#20
0
func (self *Encoder) optimize(obj *jksn_proxy) *jksn_proxy {
	control := obj.Control & 0xf0
	if control == 0x10 {
		if self.lastint != nil {
			origin_int := obj.Origin.(*big.Int)
			delta := new(big.Int).Sub(origin_int, self.lastint)
			if new(big.Int).Abs(delta).Cmp(new(big.Int).Abs(origin_int)) < 0 {
				var new_control uint8
				var new_data []byte
				if delta.Sign() >= 0 && delta.Cmp(big.NewInt(0x5)) <= 0 {
					new_control, new_data = 0xd0|uint8(delta.Uint64()), empty_bytes
				} else if delta.Cmp(big.NewInt(-0x5)) >= 0 && delta.Cmp(big.NewInt(-0x1)) <= 0 {
					new_control, new_data = 0xd0|uint8(new(big.Int).Add(delta, big.NewInt(11)).Uint64()), empty_bytes
				} else if delta.Cmp(big.NewInt(-0x80)) >= 0 && delta.Cmp(big.NewInt(0x7f)) <= 0 {
					new_control, new_data = 0xdd, self.encode_int(delta, 1)
				} else if delta.Cmp(big.NewInt(-0x8000)) >= 0 && delta.Cmp(big.NewInt(0x7fff)) <= 0 {
					new_control, new_data = 0xdc, self.encode_int(delta, 2)
				} else if (delta.Cmp(big.NewInt(-0x80000000)) >= 0 && delta.Cmp(big.NewInt(-0x200000)) <= 0) ||
					(delta.Cmp(big.NewInt(0x200000)) >= 0 && delta.Cmp(big.NewInt(0x7fffffff)) <= 0) {
					new_control, new_data = 0xdb, self.encode_int(delta, 4)
				} else if delta.Sign() >= 0 {
					new_control, new_data = 0xdf, self.encode_int(delta, 0)
				} else {
					new_control, new_data = 0xde, self.encode_int(new(big.Int).Neg(delta), 0)
				}
				if len(new_data) < len(obj.Data) {
					obj.Control, obj.Data = new_control, new_data
				}
			}
		}
		self.lastint = obj.Origin.(*big.Int)
	} else if control == 0x30 || control == 0x40 {
		if len(obj.Buf) > 1 {
			if bytes.Equal(self.texthash[obj.Hash], obj.Buf) {
				obj.Control, obj.Data, obj.Buf = 0x3c, []byte{obj.Hash}, empty_bytes
			} else {
				self.texthash[obj.Hash] = obj.Buf
			}
		}
	} else if control == 0x50 {
		if len(obj.Buf) > 1 {
			if bytes.Equal(self.blobhash[obj.Hash], obj.Buf) {
				obj.Control, obj.Data, obj.Buf = 0x5c, []byte{obj.Hash}, empty_bytes
			} else {
				self.blobhash[obj.Hash] = make([]byte, len(obj.Buf))
				copy(self.blobhash[obj.Hash], obj.Buf)
			}
		}
	} else {
		for _, child := range obj.Children {
			self.optimize(child)
		}
	}
	return obj
}
示例#21
0
// Encodes n using Knuth's Hashing Algorithm.
// Ensure that you store the prime, modInverse and random number
// associated with the Optimus struct so that it can be decoded
// correctly.
func (o Optimus) Encode(n *big.Int) *big.Int {
	b := &big.Int{}
	b.SetUint64(((n.Uint64() * o.prime.Uint64()) & o.maxInt.Uint64()) ^ o.random.Uint64())
	b.Mul(n, o.prime)
	for i := o.bits + 1; i < b.BitLen(); i++ {
		b.SetBit(b, i, 0)
	}
	b.And(b, o.maxInt)
	b.Xor(b, o.random)
	return b
}
示例#22
0
文件: main.go 项目: schulze/trials
func check(table primesTable, p *big.Int) error {
	if q, ok := table[p.Uint64()]; ok {
		if p.Cmp(q) == 0 {
			log.Printf("same primes TODO \n")
			return errors.New("duplicate prime")
		}
		log.Printf("same uint64, but not same prime TODO \n")
	}
	table[p.Uint64()] = p
	return nil
}
示例#23
0
文件: hotp.go 项目: aocsolutions/hotp
// OTP generates a new one-time password.
func (otp HOTP) OTP() string {
	h := hmac.New(sha1.New, otp.Key)
	h.Write(otp.counter[:])
	otp.Increment()
	hash := h.Sum(nil)
	result := truncate(hash)

	mod := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(otp.Digits)), nil)
	mod = mod.Mod(big.NewInt(result), mod)
	fmtStr := fmt.Sprintf("%%0%dd", otp.Digits)
	return fmt.Sprintf(fmtStr, mod.Uint64())
}
示例#24
0
文件: hotp.go 项目: aocsolutions/hotp
// IntegrityCheck returns two values, the base OTP and the current
// counter. This is used, for example, with the Google Authenticator
// app's "Check key value" function and can be used to verify that
// the application and the provider are in sync.
func (otp *HOTP) IntegrityCheck() (string, uint64) {
	h := hmac.New(sha1.New, otp.Key)
	counter := make([]byte, 8)
	h.Write(counter)
	hash := h.Sum(nil)
	result := truncate(hash)

	mod := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(otp.Digits)), nil)
	mod = mod.Mod(big.NewInt(result), mod)
	fmtStr := fmt.Sprintf("%%0%dd", otp.Digits)
	return fmt.Sprintf(fmtStr, mod.Uint64()), otp.Counter()
}
func SumString(n string, base int) (int, error) {
	i, ok := new(big.Int).SetString(n, base)
	if !ok {
		return 0, strconv.ErrSyntax
	}
	if i.Sign() < 0 {
		return 0, strconv.ErrRange
	}
	if i.BitLen() <= 64 {
		return Sum(i.Uint64(), base), nil
	}
	return SumBig(i, base), nil
}
示例#26
0
func TestModSqr(t *testing.T) {
	A := new(big.Int)
	B := new(big.Int)
	for _, a := range numbers {
		A.SetUint64(a)
		b := mod_sqr(a)
		B.Mul(A, A)
		B.Mod(B, P)
		expected := B.Uint64()
		if b != expected {
			t.Fatalf("%d**2: Expecting %d but got %d", a, expected, b)
		}
	}
}
示例#27
0
// has checks whether code has a JUMPDEST at dest.
func (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool {
	// PC cannot go beyond len(code) and certainly can't be bigger than 64bits.
	// Don't bother checking for JUMPDEST in that case.
	if dest.Cmp(bigMaxUint64) > 0 {
		return false
	}
	m, analysed := d[codehash]
	if !analysed {
		m = jumpdests(code)
		d[codehash] = m
	}
	_, ok := m[dest.Uint64()]
	return ok
}
示例#28
0
文件: utils.go 项目: tscholl2/prime
// 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
		}
	}
}
示例#29
0
func (bc *blockchain) mineGenesisBlock() error {
	msg := "Never roll your own crypto"
	b := coin.Block(msg)

	genesisHeader = coin.Header{
		MerkleRoot: sha256.Sum256([]byte(msg)),
		Difficulty: MinimumDifficulty,
	}

	// Calculate modulus
	dInt := new(big.Int).SetUint64(genesisHeader.Difficulty)
	mInt := new(big.Int).SetUint64(2)
	mInt.Exp(mInt, dInt, nil)

	ticker := time.NewTicker(90 * time.Second)

getblocktemplate:
	genesisHeader.Timestamp = time.Now().UnixNano()
	hashMap := make(map[uint64][]uint64)
	i := uint64(0)
	for {
		select {
		case <-ticker.C:
			goto getblocktemplate
		default:
			break
		}

		genesisHeader.Nonces[0] = i
		aHash := genesisHeader.SumNonce(0)
		aInt := new(big.Int).SetBytes(aHash[:])
		aInt.Mod(aInt, mInt)

		a := aInt.Uint64()
		if ns, ok := hashMap[a]; ok {
			if len(ns) == 2 {
				genesisHeader.Nonces[0] = ns[0]
				genesisHeader.Nonces[1] = ns[1]
				genesisHeader.Nonces[2] = i

				return bc.AddBlock(genesisHeader, b)
			}
			hashMap[a] = append(ns, i)
		} else {
			hashMap[a] = []uint64{i}
		}
		i++
	}
}
示例#30
0
// PendingAccountNonce implements ContractTransactor.PendingAccountNonce, delegating
// the current account nonce retrieval to the remote node.
func (b *rpcBackend) PendingAccountNonce(account common.Address) (uint64, error) {
	res, err := b.request("exp_getTransactionCount", []interface{}{account.Hex(), "pending"})
	if err != nil {
		return 0, err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return 0, err
	}
	nonce, ok := new(big.Int).SetString(hex, 0)
	if !ok {
		return 0, fmt.Errorf("invalid nonce hex: %s", hex)
	}
	return nonce.Uint64(), nil
}