Exemplo n.º 1
0
// schnorrCombineSigs combines a list of partial Schnorr signatures s values
// into a complete signature s for some group public key. This is achieved
// by simply adding the s values of the partial signatures as scalars.
func schnorrCombineSigs(curve *secp256k1.KoblitzCurve, sigss [][]byte) (*big.Int,
	error) {
	combinedSigS := new(big.Int).SetInt64(0)
	for i, sigs := range sigss {
		sigsBI := EncodedBytesToBigInt(copyBytes(sigs))
		if sigsBI.Cmp(bigZero) == 0 {
			str := fmt.Sprintf("sig s %v is zero", i)
			return nil, schnorrError(ErrInputValue, str)
		}
		if sigsBI.Cmp(curve.N) >= 0 {
			str := fmt.Sprintf("sig s %v is out of bounds", i)
			return nil, schnorrError(ErrInputValue, str)
		}

		combinedSigS.Add(combinedSigS, sigsBI)
		combinedSigS.Mod(combinedSigS, curve.N)
	}

	if combinedSigS.Cmp(bigZero) == 0 {
		str := fmt.Sprintf("combined sig s %v is zero", combinedSigS)
		return nil, schnorrError(ErrZeroSigS, str)
	}

	return combinedSigS, nil
}
Exemplo n.º 2
0
func bigAdd(IntSlice []big.Int) *big.Int {
	var sum *big.Int = big.NewInt(0)
	for i := 0; i < len(IntSlice); i++ {
		sum.Add(sum, &IntSlice[i])
	}
	return sum
}
Exemplo n.º 3
0
/*
FromFactorBigInt returns n such that d | Mn if n <= max and d is odd. In other
cases zero is returned.

It is conjectured that every odd d ∊ N divides infinitely many Mersenne numbers.
The returned n should be the exponent of smallest such Mn.

NOTE: The computation of n from a given d performs roughly in O(n). It is
thus highly recomended to use the 'max' argument to limit the "searched"
exponent upper bound as appropriate. Otherwise the computation can take a long
time as a large factor can be a divisor of a Mn with exponent above the uint32
limits.

The FromFactorBigInt function is a modification of the original Will
Edgington's "reverse method", discussed here:
http://tech.groups.yahoo.com/group/primenumbers/message/15061
*/
func FromFactorBigInt(d *big.Int, max uint32) (n uint32) {
	if d.Bit(0) == 0 {
		return
	}

	var m big.Int
	for n < max {
		m.Add(&m, d)
		i := 0
		for ; m.Bit(i) == 1; i++ {
			if n == math.MaxUint32 {
				return 0
			}

			n++
		}
		m.Rsh(&m, uint(i))
		if m.Sign() == 0 {
			if n > max {
				n = 0
			}
			return
		}
	}
	return 0
}
Exemplo n.º 4
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
}
Exemplo n.º 5
0
func SumOfBigInts(nums []*big.Int) *big.Int {
	var sum *big.Int = big.NewInt(0)
	for _, i := range nums {
		sum.Add(sum, i)
	}
	return sum
}
Exemplo n.º 6
0
func (self *BlockProcessor) ApplyTransactions(gp GasPool, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, error) {
	var (
		receipts      types.Receipts
		totalUsedGas  = big.NewInt(0)
		err           error
		cumulativeSum = new(big.Int)
		header        = block.Header()
	)

	for i, tx := range txs {
		statedb.StartRecord(tx.Hash(), block.Hash(), i)

		receipt, txGas, err := self.ApplyTransaction(gp, statedb, header, tx, totalUsedGas, transientProcess)
		if err != nil {
			return nil, err
		}

		if err != nil {
			glog.V(logger.Core).Infoln("TX err:", err)
		}
		receipts = append(receipts, receipt)

		cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
	}

	if block.GasUsed().Cmp(totalUsedGas) != 0 {
		return nil, ValidationError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), totalUsedGas))
	}

	if transientProcess {
		go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
	}

	return receipts, err
}
Exemplo n.º 7
0
//Verify verifies the proof file server send.
func (sw *Swizzle) Verify(p Proof) (bool, error) {
	proof, ok := p.(*SwizzleProof)
	if !ok {
		return false, errors.New("use SwizzleProof instance for proof")
	}
	var rhs big.Int
	var dummy big.Int
	ch := sw.lastChallenge
	for i := 0; i < sw.chunks; i++ {
		f, err := keyedPRFBig(sw.fKey, sw.prime, i)
		if err != nil {
			return false, err
		}
		v, err := keyedPRFBig(ch.Key, ch.Vmax, i)
		if err != nil {
			return false, err
		}
		rhs.Add(&rhs, dummy.Mul(v, f))
	}
	for j := 0; j < ch.Sectors; j++ {
		alpha, err := keyedPRFBig(sw.alphaKey, sw.prime, j)
		if err != nil {
			return false, err
		}
		rhs.Add(&rhs, dummy.Mul(alpha, &proof.Mu[j]))
	}
	dummy.DivMod(&rhs, sw.prime, &rhs)
	if proof.Sigma.Cmp(&rhs) == 0 {
		return true, nil
	}
	return false, nil
}
Exemplo n.º 8
0
func main() {
	var s string
	var n, two, tmp big.Int
	two.SetInt64(2)

	in, _ := os.Open("10519.in")
	defer in.Close()
	out, _ := os.Create("10519.out")
	defer out.Close()

	for {
		if _, err := fmt.Fscanf(in, "%s", &s); err != nil {
			break
		}
		if s == "0" {
			fmt.Fprintln(out, 1)
			continue
		}
		n.SetString(s, 10)
		tmp.Mul(&n, &n)
		tmp.Sub(&tmp, &n)
		tmp.Add(&tmp, &two)
		fmt.Fprintln(out, &tmp)
	}
}
Exemplo n.º 9
0
func (block *Block) PayFee(addr []byte, fee *big.Int) bool {
	contract := block.state.GetContract(addr)
	// If we can't pay the fee return
	if contract == nil || contract.Amount.Cmp(fee) < 0 /* amount < fee */ {
		fmt.Println("Contract has insufficient funds", contract.Amount, fee)

		return false
	}

	base := new(big.Int)
	contract.Amount = base.Sub(contract.Amount, fee)
	block.state.trie.Update(string(addr), string(contract.RlpEncode()))

	data := block.state.trie.Get(string(block.Coinbase))

	// Get the ether (Coinbase) and add the fee (gief fee to miner)
	ether := NewAccountFromData([]byte(data))

	base = new(big.Int)
	ether.Amount = base.Add(ether.Amount, fee)

	block.state.trie.Update(string(block.Coinbase), string(ether.RlpEncode()))

	return true
}
Exemplo n.º 10
0
// GenerateKey generates a public and private key pair using random source rand.
func GenerateKey(rand io.Reader) (priv PrivateKey, err error) {
	/* See Certicom's SEC1 3.2.1, pg.23 */
	/* See NSA's Suite B Implementer’s Guide to FIPS 186-3 (ECDSA) A.1.1, pg.18 */

	/* Select private key d randomly from [1, n) */

	/* Read N bit length random bytes + 64 extra bits  */
	b := make([]byte, secp256k1.N.BitLen()/8+8)
	_, err = io.ReadFull(rand, b)
	if err != nil {
		return priv, fmt.Errorf("Reading random reader: %v", err)
	}

	d := new(big.Int).SetBytes(b)

	/* Mod n-1 to shift d into [0, n-1) range */
	d.Mod(d, new(big.Int).Sub(secp256k1.N, big.NewInt(1)))
	/* Add one to shift d to [1, n) range */
	d.Add(d, big.NewInt(1))

	priv.D = d

	/* Derive public key from private key */
	priv.derive()

	return priv, nil
}
Exemplo n.º 11
0
// powerOffset computes the offset by (n + 2^exp) % (2^mod)
func powerOffset(id []byte, exp int, mod int) []byte {
	// Copy the existing slice
	off := make([]byte, len(id))
	copy(off, id)

	// Convert the ID to a bigint
	idInt := big.Int{}
	idInt.SetBytes(id)

	// Get the offset
	two := big.NewInt(2)
	offset := big.Int{}
	offset.Exp(two, big.NewInt(int64(exp)), nil)

	// Sum
	sum := big.Int{}
	sum.Add(&idInt, &offset)

	// Get the ceiling
	ceil := big.Int{}
	ceil.Exp(two, big.NewInt(int64(mod)), nil)

	// Apply the mod
	idInt.Mod(&sum, &ceil)

	// Add together
	return idInt.Bytes()
}
Exemplo n.º 12
0
// (n - 2^(k-1)) mod 2^m
func calcLastFinger(n []byte, k int) (string, []byte) {

	// convert the n to a bigint
	nBigInt := big.Int{}
	nBigInt.SetBytes(n)

	// get the right addend, i.e. 2^(k-1)
	two := big.NewInt(2)
	addend := big.Int{}
	addend.Exp(two, big.NewInt(int64(k-1)), nil)

	addend.Mul(&addend, big.NewInt(-1))
	//Soustraction
	neg := big.Int{}
	neg.Add(&addend, &nBigInt)

	// calculate 2^m
	m := 160
	ceil := big.Int{}
	ceil.Exp(two, big.NewInt(int64(m)), nil)

	// apply the mod
	result := big.Int{}
	result.Mod(&neg, &ceil)

	resultBytes := result.Bytes()
	resultHex := fmt.Sprintf("%x", resultBytes)

	return resultHex, resultBytes
}
Exemplo n.º 13
0
// (n + 2^(k-1)) mod (2^m)
func calcFinger(n []byte, k int, m int) (string, []byte) {

	// convert the n to a bigint
	nBigInt := big.Int{}
	nBigInt.SetBytes(n)

	// get the right addend, i.e. 2^(k-1)
	two := big.NewInt(2)
	addend := big.Int{}
	addend.Exp(two, big.NewInt(int64(k-1)), nil)

	// calculate sum
	sum := big.Int{}
	sum.Add(&nBigInt, &addend)

	// calculate 2^m
	ceil := big.Int{}
	ceil.Exp(two, big.NewInt(int64(m)), nil)

	// apply the mod
	result := big.Int{}
	result.Mod(&sum, &ceil)

	resultBytes := result.Bytes()
	resultHex := fmt.Sprintf("%x", resultBytes)

	return resultHex, resultBytes
}
Exemplo n.º 14
0
func CalculateBlockReward(block *Block, uncleLength int) *big.Int {
	base := new(big.Int)
	for i := 0; i < uncleLength; i++ {
		base.Add(base, UncleInclusionReward)
	}
	return base.Add(base, BlockReward)
}
Exemplo n.º 15
0
// signRFC6979 generates a deterministic ECDSA signature according to RFC 6979
// and BIP 62.
func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) {

	privkey := privateKey.ToECDSA()
	N := order
	k := NonceRFC6979(privkey.D, hash, nil, nil)
	inv := new(big.Int).ModInverse(k, N)
	r, _ := privkey.Curve.ScalarBaseMult(k.Bytes())
	if r.Cmp(N) == 1 {
		r.Sub(r, N)
	}

	if r.Sign() == 0 {
		return nil, errors.New("calculated R is zero")
	}

	e := hashToInt(hash, privkey.Curve)
	s := new(big.Int).Mul(privkey.D, r)
	s.Add(s, e)
	s.Mul(s, inv)
	s.Mod(s, N)

	if s.Cmp(halforder) == 1 {
		s.Sub(N, s)
	}
	if s.Sign() == 0 {
		return nil, errors.New("calculated S is zero")
	}
	return &Signature{R: r, S: s}, nil
}
Exemplo n.º 16
0
func main() {
	s := bufio.NewScanner(bufio.NewReader(os.Stdin))
	s.Split(bufio.ScanWords)

	s.Scan()
	a, _ := strconv.Atoi(s.Text())

	s.Scan()
	b, _ := strconv.Atoi(s.Text())

	s.Scan()
	n, _ := strconv.Atoi(s.Text())

	switch n {
	case 0:
		fmt.Printf("0\n")
	case 1:
		fmt.Printf("%v\n", a)
	case 2:
		fmt.Printf("%v\n", b)
	default:
		fp := big.NewInt(int64(a))
		fc := big.NewInt(int64(b))
		for i := 2; i < n; i++ {
			f := new(big.Int)
			f.Mul(fc, fc)
			f.Add(f, fp)
			fp = fc
			fc = f
		}
		fmt.Printf("%v\n", fc)
	}
}
Exemplo n.º 17
0
// Unblind a signature
func (client BlindingClient) Unblind(blindSignature *BlindSignatureInt, BlindingParams *BlindingParamsPrivateInt) (signature *SignatureInt, err error) {
	// ToDo: Test Params
	ScalarRs1Inv, err := client.curve.ModInverse(BlindingParams.ScalarRs1) // inv(rs1)
	if err != nil {
		return nil, err // should never happen
	}
	ScalarRs2Inv, err := client.curve.ModInverse(BlindingParams.ScalarRs2) // inv(rs2)
	if err != nil {
		return nil, err // should never happen
	}
	ScalarR1R2 := eccutil.ManyMult(BlindingParams.ScalarR1, BlindingParams.ScalarR2) // r1 * r2

	ScalarS1 := eccutil.ManyMult(blindSignature.ScalarS1, ScalarRs1Inv, ScalarR1R2, BlindingParams.ScalarW, BlindingParams.ScalarA) // ss1 * (inv(rs1)) * (r1 * r2) * w * a
	ScalarS2 := eccutil.ManyMult(blindSignature.ScalarS2, ScalarRs2Inv, ScalarR1R2, BlindingParams.ScalarZ, BlindingParams.ScalarB) // ss2 * (inv(rs2)) * (r1 * r2) * z * b
	//cparams := curve.curve.Params()
	ScalarS1 = ScalarS1.Mod(ScalarS1, client.curve.Params.N) // s1 = (ss1 * inv(rs1) * r1 * r2 * w * a)  mod N
	ScalarS2 = ScalarS2.Mod(ScalarS2, client.curve.Params.N) // s2 = (ss2 * inv(rs2) * r1 * r2 * z * b)  mod N
	ScalarS := new(big.Int)
	ScalarS = ScalarS.Add(ScalarS1, ScalarS2) // s = s1 + s2

	PointR := client.curve.AddPoints(BlindingParams.PointR1, BlindingParams.PointR2) // R = R1 + R2

	ScalarR := eccutil.ManyMult(BlindingParams.ScalarR1, BlindingParams.ScalarR2) // r1 * r2
	ScalarR = ScalarR.Mod(ScalarR, client.curve.Params.N)                         //r = (r1 * r2) mod N

	signaturet := new(SignatureInt)
	signaturet.PointR = PointR
	signaturet.ScalarS = ScalarS
	signaturet.ScalarR = ScalarR
	return signaturet, nil
}
Exemplo n.º 18
0
// Put implements storage.Contacts.
func (c *contacts) Put(name string, key *sf.PublicKey) error {
	if len(name) == 0 {
		return errgo.New("empty key name")
	}
	return c.db.Update(func(tx *bolt.Tx) error {
		contactsBucket, err := tx.CreateBucketIfNotExists([]byte("contacts"))
		if err != nil {
			return errgo.Mask(err)
		}
		err = contactsBucket.Put(key[:], []byte(name))
		if err != nil {
			return errgo.Mask(err)
		}
		keysBucket, err := contactsBucket.CreateBucketIfNotExists([]byte(name))
		if err != nil {
			return errgo.Mask(err)
		}

		lastSeqBytes, _ := keysBucket.Cursor().Last()
		var seq big.Int
		seq.SetBytes(lastSeqBytes)
		seq.Add(&seq, bigOne)
		err = keysBucket.Put(seq.Bytes(), key[:])
		if err != nil {
			return errgo.Mask(err)
		}
		return nil
	})
}
Exemplo n.º 19
0
func (self *BlockProcessor) ApplyTransaction(gp GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
	_, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, header), tx, gp)
	if err != nil {
		return nil, nil, err
	}

	// Update the state with pending changes
	statedb.SyncIntermediate()

	usedGas.Add(usedGas, gas)
	receipt := types.NewReceipt(statedb.Root().Bytes(), usedGas)
	receipt.TxHash = tx.Hash()
	receipt.GasUsed = new(big.Int).Set(gas)
	if MessageCreatesContract(tx) {
		from, _ := tx.From()
		receipt.ContractAddress = crypto.CreateAddress(from, tx.Nonce())
	}

	logs := statedb.GetLogs(tx.Hash())
	receipt.SetLogs(logs)
	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})

	glog.V(logger.Debug).Infoln(receipt)

	// Notify all subscribers
	if !transientProcess {
		go self.eventMux.Post(TxPostEvent{tx})
		go self.eventMux.Post(logs)
	}

	return receipt, gas, err
}
Exemplo n.º 20
0
func q2() {
	n := new(big.Int)
	a := new(big.Int)
	asquared := new(big.Int)
	one := new(big.Int)
	x := new(big.Int)
	xsquared := new(big.Int)
	p := new(big.Int)
	q := new(big.Int)
	candidate := new(big.Int)

	n.SetString("648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877", 10)
	one.SetString("1", 10)

	a = mathutil.SqrtBig(n)
	for {
		a.Add(a, one)
		asquared.Mul(a, a)
		xsquared.Sub(asquared, n)
		x = mathutil.SqrtBig(xsquared)
		p.Sub(a, x)
		q.Add(a, x)
		if candidate.Mul(p, q).Cmp(n) == 0 {
			fmt.Println(p.String())
			break
		}
	}
}
Exemplo n.º 21
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
}
Exemplo n.º 22
0
// HashPasswordWithSalt scrambles the password with the provided parameters.
func HashPasswordWithSalt(password, tweak, salt []byte, g, g0 int64, H hash.Hash) ([]byte, error) {
	if g < g0 {
		return nil, ErrInvalidGarlic
	}

	x := make([]byte, len(tweak)+len(password)|len(salt))
	copy(x, tweak)
	copy(x[len(tweak):], password)
	copy(x[len(tweak)+len(password):], salt)

	var err error
	for i := g0; i <= g; i++ {
		c := bigPadded(big.NewInt(i), cPad)
		twoCp1 := new(big.Int).Exp(big.NewInt(2), big.NewInt(i), nil)
		twoCp1 = twoCp1.Add(twoCp1, big.NewInt(1))
		x, err = sbrh(c, x, H)
		if err != nil {
			H.Reset()
			return nil, err
		}
		H.Write(c)
		H.Write(bigPadded(twoCp1, cPad))
		H.Write(x)
		x = H.Sum(nil)
		H.Reset()
	}
	return x, nil
}
Exemplo n.º 23
0
func (t *lft) extr(x *big.Int) *big.Rat {
	var n, d big.Int
	var r big.Rat
	return r.SetFrac(
		n.Add(n.Mul(&t.q, x), &t.r),
		d.Add(d.Mul(&t.s, x), &t.t))
}
Exemplo n.º 24
0
//newPrivateKey makes private key from seeds.
func newPrivateKey(pSeed, qSeed big.Int) (*PrivateKey, error) {
	q := &qSeed
	p := &pSeed
	var tmp big.Int
	test := big.NewInt(0x7743)
	var q1, phi, keyD, keyN big.Int
	for count := 0; count < rsaCreateGiveup; count++ {
		q = primize(q)
		q1.Add(q, tmp.SetInt64(-1))
		p = primize(p)
		phi.Add(p, tmp.SetInt64(-1))
		phi.Mul(&phi, &q1)
		keyD.ModInverse(rsaPublicE, &phi)
		if keyD.Cmp(tmp.SetInt64(0)) == 0 {
			continue
		}
		keyN.Mul(p, q)
		tmp.Exp(test, rsaPublicE, &keyN)
		tmp.Exp(&tmp, &keyD, &keyN)
		if tmp.Cmp(test) == 0 {
			return &PrivateKey{&keyN, &keyD}, nil
		}
		p.Add(p, tmp.SetInt64(2))
		q.Add(q, tmp.SetInt64(2))
	}
	err := errors.New("cannot generate private key")
	log.Fatal(err)
	return nil, err
}
Exemplo n.º 25
0
func plus(z *big.Int, x *big.Int, y *big.Int) *big.Int {
	var lim big.Int
	lim.Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
	z.Add(x, y)
	return z.Mod(z, &lim)

}
Exemplo n.º 26
0
func main() {

	// Open file for read
	fd, err := os.Open("numbers.txt")
	chk(err)
	defer fd.Close()

	// Line by line reader
	scanner := bufio.NewScanner(fd)
	scanner.Split(bufio.ScanLines)

	// Use standart library - big Integers
	bigSum := new(big.Int)

	for scanner.Scan() {
		ns := scanner.Text()
		bigInt := new(big.Int)
		bigInt.SetString(ns, 10) // Convert readed decimal string to big.Int
		bigSum.Add(bigSum, bigInt)
	}

	answerString := bigSum.String()
	fmt.Println("Result:", answerString, len(answerString))
	fmt.Println("Answer:", answerString[0:10])
}
Exemplo n.º 27
0
// baseCheck checks for any stack error underflows
func baseCheck(op OpCode, stack *stack, gas *big.Int) error {
	// PUSH and DUP are a bit special. They all cost the same but we do want to have checking on stack push limit
	// PUSH is also allowed to calculate the same price for all PUSHes
	// DUP requirements are handled elsewhere (except for the stack limit check)
	if op >= PUSH1 && op <= PUSH32 {
		op = PUSH1
	}
	if op >= DUP1 && op <= DUP16 {
		op = DUP1
	}

	if r, ok := _baseCheck[op]; ok {
		err := stack.require(r.stackPop)
		if err != nil {
			return err
		}

		if r.stackPush > 0 && stack.len()-r.stackPop+r.stackPush > int(params.StackLimit.Int64()) {
			return fmt.Errorf("stack limit reached %d (%d)", stack.len(), params.StackLimit.Int64())
		}

		gas.Add(gas, r.gas)
	}
	return nil
}
Exemplo n.º 28
0
func DecodeBase58(ba []byte) []byte {
	if len(ba) == 0 {
		return nil
	}

	x := new(big.Int)
	y := big.NewInt(58)
	z := new(big.Int)
	for _, b := range ba {
		v := strings.IndexRune(base58, rune(b))
		z.SetInt64(int64(v))
		x.Mul(x, y)
		x.Add(x, z)
	}
	xa := x.Bytes()

	// Restore leading zeros
	i := 0
	for i < len(ba) && ba[i] == '1' {
		i++
	}
	ra := make([]byte, i+len(xa))
	copy(ra[i:], xa)
	return ra
}
Exemplo n.º 29
0
// Try to generate a point on this curve from a chosen x-coordinate,
// with a random sign.
func (p *curvePoint) genPoint(x *big.Int, rand cipher.Stream) bool {

	// Compute the corresponding Y coordinate, if any
	y2 := new(big.Int).Mul(x, x)
	y2.Mul(y2, x)
	threeX := new(big.Int).Lsh(x, 1)
	threeX.Add(threeX, x)
	y2.Sub(y2, threeX)
	y2.Add(y2, p.c.p.B)
	y2.Mod(y2, p.c.p.P)
	y := p.c.sqrt(y2)

	// Pick a random sign for the y coordinate
	b := make([]byte, 1)
	rand.XORKeyStream(b, b)
	if (b[0] & 0x80) != 0 {
		y.Sub(p.c.p.P, y)
	}

	// Check that it's a valid point
	y2t := new(big.Int).Mul(y, y)
	y2t.Mod(y2t, p.c.p.P)
	if y2t.Cmp(y2) != 0 {
		return false // Doesn't yield a valid point!
	}

	p.x = x
	p.y = y
	return true
}
Exemplo n.º 30
0
func nextFib() *big.Int {
	num := new(big.Int)
	num.Add(currentNumber, lastNumber)
	lastNumber = currentNumber
	currentNumber = num
	return num
}