Exemplo n.º 1
0
func (z *Polynomial) Mul(x, y *Polynomial) *Polynomial {
	var zCoeffs *big.Int
	if z == x || z == y {
		// Ensure that we do not modify z if it's a parameter.
		zCoeffs = new(big.Int)
	} else {
		zCoeffs = &z.coeffs
		zCoeffs.SetInt64(0)
	}

	small, large := x, y
	if y.degree < x.degree {
		small, large = y, x
	}

	// Walk through small coeffs, shift large by the corresponding amount,
	// and accumulate in z.
	coeffs := new(big.Int).Set(&small.coeffs)
	zero := new(big.Int)
	for coeffs.Cmp(zero) > 0 {
		deg := calcDegree(coeffs)
		factor := new(big.Int).Lsh(&large.coeffs, deg)
		zCoeffs.Xor(zCoeffs, factor)

		// Prepare for next iteration.
		coeffs.SetBit(coeffs, int(deg), 0)
	}

	z.degree = calcDegree(zCoeffs)
	z.coeffs = *zCoeffs
	return z
}
Exemplo n.º 2
0
func (d PublicKeyDigest) Xor(n PublicKeyDigest) PublicKeyDigest {
	var b, c big.Int
	b.SetBytes(d[:])
	c.SetBytes(n[:])
	b.Xor(&b, &c)
	var e PublicKeyDigest
	copy(e[:], b.Bytes())
	return e
}
Exemplo n.º 3
0
Arquivo: deploy.go Projeto: gdb/Stout
func hashFiles(files []string) string {
	hash := new(big.Int)
	for _, file := range files {
		val := new(big.Int)
		val.SetBytes(hashFile(file))

		hash = hash.Xor(hash, val)
	}

	return fmt.Sprintf("%x", hash)
}
Exemplo n.º 4
0
Arquivo: const.go Projeto: spate/llgo
func binaryIntOp(x *big.Int, op token.Token, y *big.Int) interface{} {
	var z big.Int
	switch op {
	case token.ADD:
		return z.Add(x, y)
	case token.SUB:
		return z.Sub(x, y)
	case token.MUL:
		return z.Mul(x, y)
	case token.QUO:
		return z.Quo(x, y)
	case token.REM:
		return z.Rem(x, y)
	case token.AND:
		return z.And(x, y)
	case token.OR:
		return z.Or(x, y)
	case token.XOR:
		return z.Xor(x, y)
	case token.AND_NOT:
		return z.AndNot(x, y)
	case token.SHL:
		// The shift length must be uint, or untyped int and
		// convertible to uint.
		// TODO 32/64bit
		if y.BitLen() > 32 {
			panic("Excessive shift length")
		}
		return z.Lsh(x, uint(y.Int64()))
	case token.SHR:
		if y.BitLen() > 32 {
			panic("Excessive shift length")
		}
		return z.Rsh(x, uint(y.Int64()))
	case token.EQL:
		return x.Cmp(y) == 0
	case token.NEQ:
		return x.Cmp(y) != 0
	case token.LSS:
		return x.Cmp(y) < 0
	case token.LEQ:
		return x.Cmp(y) <= 0
	case token.GTR:
		return x.Cmp(y) > 0
	case token.GEQ:
		return x.Cmp(y) >= 0
	}
	panic("unreachable")
}
Exemplo n.º 5
0
Arquivo: merges.go Projeto: baeeq/god
func bigIntXor(oldValues [][]byte, newValues [][]byte, w float64) (result [][]byte) {
	var sum *big.Int
	if oldValues != nil {
		sum = new(big.Int).SetBytes(oldValues[0])
		for _, b := range newValues {
			sum.Xor(sum, new(big.Int).Mul(common.DecodeBigInt(b), big.NewInt(int64(w))))
		}
	} else {
		sum = new(big.Int).Mul(new(big.Int).SetBytes(newValues[0]), big.NewInt(int64(w)))
		for _, b := range newValues[1:] {
			sum.Xor(sum, new(big.Int).Mul(common.DecodeBigInt(b), big.NewInt(int64(w))))
		}
	}
	return [][]byte{sum.Bytes()}
}
Exemplo n.º 6
0
// LastUsable returns the last address in a given network.
func (ipv6 IPv6Addr) LastUsable() IPAddr {
	addr := new(big.Int)
	addr.Set(ipv6.Address)

	mask := new(big.Int)
	mask.Set(ipv6.Mask)

	negMask := new(big.Int)
	negMask.Xor(ipv6HostMask, mask)

	lastAddr := new(big.Int)
	lastAddr.And(addr, mask)
	lastAddr.Or(lastAddr, negMask)

	return IPv6Addr{
		Address: IPv6Address(lastAddr),
		Mask:    ipv6HostMask,
	}
}
Exemplo n.º 7
0
func computeClientAuthenticator(hf HashFunc, grp *SRPGroup, username, salt, A, B, K []byte) []byte {
	//M = H(H(N) xor H(g), H(I), s, A, B, K)

	// H(N) xor H(g)
	hn := new(big.Int).SetBytes(quickHash(hf, grp.Prime.Bytes()))
	hg := new(big.Int).SetBytes(quickHash(hf, grp.Generator.Bytes()))
	hng := hn.Xor(hn, hg)

	hi := quickHash(hf, []byte(username))

	h := hf()
	h.Write(hng.Bytes())
	h.Write(hi)
	h.Write(salt)
	h.Write(A)
	h.Write(B)
	h.Write(K)
	return h.Sum(nil)
}
Exemplo n.º 8
0
func binaryIntOp(x *big.Int, op token.Token, y *big.Int) interface{} {
	var z big.Int
	switch op {
	case token.ADD:
		return z.Add(x, y)
	case token.SUB:
		return z.Sub(x, y)
	case token.MUL:
		return z.Mul(x, y)
	case token.QUO:
		return z.Quo(x, y)
	case token.REM:
		return z.Rem(x, y)
	case token.AND:
		return z.And(x, y)
	case token.OR:
		return z.Or(x, y)
	case token.XOR:
		return z.Xor(x, y)
	case token.AND_NOT:
		return z.AndNot(x, y)
	case token.SHL:
		panic("unimplemented")
	case token.SHR:
		panic("unimplemented")
	case token.EQL:
		return x.Cmp(y) == 0
	case token.NEQ:
		return x.Cmp(y) != 0
	case token.LSS:
		return x.Cmp(y) < 0
	case token.LEQ:
		return x.Cmp(y) <= 0
	case token.GTR:
		return x.Cmp(y) > 0
	case token.GEQ:
		return x.Cmp(y) >= 0
	}
	panic("unreachable")
}
Exemplo n.º 9
0
// binaryOpConst returns the result of the constant evaluation x op y;
// both operands must be of the same "kind" (boolean, numeric, or string).
// If intDiv is true, division (op == token.QUO) is using integer division
// (and the result is guaranteed to be integer) rather than floating-point
// division. Division by zero leads to a run-time panic.
//
func binaryOpConst(x, y interface{}, op token.Token, intDiv bool) interface{} {
	x, y = matchConst(x, y)

	switch x := x.(type) {
	case bool:
		y := y.(bool)
		switch op {
		case token.LAND:
			return x && y
		case token.LOR:
			return x || y
		default:
			unreachable()
		}

	case int64:
		y := y.(int64)
		switch op {
		case token.ADD:
			// TODO(gri) can do better than this
			if is63bit(x) && is63bit(y) {
				return x + y
			}
			return normalizeIntConst(new(big.Int).Add(big.NewInt(x), big.NewInt(y)))
		case token.SUB:
			// TODO(gri) can do better than this
			if is63bit(x) && is63bit(y) {
				return x - y
			}
			return normalizeIntConst(new(big.Int).Sub(big.NewInt(x), big.NewInt(y)))
		case token.MUL:
			// TODO(gri) can do better than this
			if is32bit(x) && is32bit(y) {
				return x * y
			}
			return normalizeIntConst(new(big.Int).Mul(big.NewInt(x), big.NewInt(y)))
		case token.REM:
			return x % y
		case token.QUO:
			if intDiv {
				return x / y
			}
			return normalizeRatConst(new(big.Rat).SetFrac(big.NewInt(x), big.NewInt(y)))
		case token.AND:
			return x & y
		case token.OR:
			return x | y
		case token.XOR:
			return x ^ y
		case token.AND_NOT:
			return x &^ y
		default:
			unreachable()
		}

	case *big.Int:
		y := y.(*big.Int)
		var z big.Int
		switch op {
		case token.ADD:
			z.Add(x, y)
		case token.SUB:
			z.Sub(x, y)
		case token.MUL:
			z.Mul(x, y)
		case token.REM:
			z.Rem(x, y)
		case token.QUO:
			if intDiv {
				z.Quo(x, y)
			} else {
				return normalizeRatConst(new(big.Rat).SetFrac(x, y))
			}
		case token.AND:
			z.And(x, y)
		case token.OR:
			z.Or(x, y)
		case token.XOR:
			z.Xor(x, y)
		case token.AND_NOT:
			z.AndNot(x, y)
		default:
			unreachable()
		}
		return normalizeIntConst(&z)

	case *big.Rat:
		y := y.(*big.Rat)
		var z big.Rat
		switch op {
		case token.ADD:
			z.Add(x, y)
		case token.SUB:
			z.Sub(x, y)
		case token.MUL:
			z.Mul(x, y)
		case token.QUO:
			z.Quo(x, y)
		default:
			unreachable()
		}
		return normalizeRatConst(&z)

	case complex:
		y := y.(complex)
		a, b := x.re, x.im
		c, d := y.re, y.im
		var re, im big.Rat
		switch op {
		case token.ADD:
			// (a+c) + i(b+d)
			re.Add(a, c)
			im.Add(b, d)
		case token.SUB:
			// (a-c) + i(b-d)
			re.Sub(a, c)
			im.Sub(b, d)
		case token.MUL:
			// (ac-bd) + i(bc+ad)
			var ac, bd, bc, ad big.Rat
			ac.Mul(a, c)
			bd.Mul(b, d)
			bc.Mul(b, c)
			ad.Mul(a, d)
			re.Sub(&ac, &bd)
			im.Add(&bc, &ad)
		case token.QUO:
			// (ac+bd)/s + i(bc-ad)/s, with s = cc + dd
			var ac, bd, bc, ad, s big.Rat
			ac.Mul(a, c)
			bd.Mul(b, d)
			bc.Mul(b, c)
			ad.Mul(a, d)
			s.Add(c.Mul(c, c), d.Mul(d, d))
			re.Add(&ac, &bd)
			re.Quo(&re, &s)
			im.Sub(&bc, &ad)
			im.Quo(&im, &s)
		default:
			unreachable()
		}
		return normalizeComplexConst(complex{&re, &im})

	case string:
		if op == token.ADD {
			return x + y.(string)
		}
	}

	unreachable()
	return nil
}
Exemplo n.º 10
0
func nxor(z *big.Int, x *big.Int, y *big.Int) *big.Int {
	z.Xor(x, y)
	return z.Not(z)
}
Exemplo n.º 11
0
func xor(z *big.Int, x *big.Int, y *big.Int) *big.Int { return z.Xor(x, y) }
Exemplo n.º 12
0
// Run loops and evaluates the contract's code with the given input data
func (self *Vm) Run(context *Context, input []byte) (ret []byte, err error) {
	self.env.SetDepth(self.env.Depth() + 1)
	defer self.env.SetDepth(self.env.Depth() - 1)

	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
	defer func() {
		if err != nil {
			// In case of a VM exception (known exceptions) all gas consumed (panics NOT included).
			context.UseGas(context.Gas)

			ret = context.Return(nil)
		}
	}()

	if context.CodeAddr != nil {
		if p := Precompiled[context.CodeAddr.Str()]; p != nil {
			return self.RunPrecompiled(p, input, context)
		}
	}

	var (
		codehash = crypto.Sha3Hash(context.Code) // codehash is used when doing jump dest caching
		program  *Program
	)
	if EnableJit {
		// Fetch program status.
		// * If ready run using JIT
		// * If unknown, compile in a seperate goroutine
		// * If forced wait for compilation and run once done
		if status := GetProgramStatus(codehash); status == progReady {
			return RunProgram(GetProgram(codehash), self.env, context, input)
		} else if status == progUnknown {
			if ForceJit {
				// Create and compile program
				program = NewProgram(context.Code)
				perr := CompileProgram(program)
				if perr == nil {
					return RunProgram(program, self.env, context, input)
				}
				glog.V(logger.Info).Infoln("error compiling program", err)
			} else {
				// create and compile the program. Compilation
				// is done in a seperate goroutine
				program = NewProgram(context.Code)
				go func() {
					err := CompileProgram(program)
					if err != nil {
						glog.V(logger.Info).Infoln("error compiling program", err)
						return
					}
				}()
			}
		}
	}

	var (
		caller = context.caller
		code   = context.Code
		value  = context.value
		price  = context.Price

		op      OpCode             // current opcode
		mem     = NewMemory()      // bound memory
		stack   = newstack()       // local stack
		statedb = self.env.State() // current state
		// For optimisation reason we're using uint64 as the program counter.
		// It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Pratically much less so feasible.
		pc = uint64(0) // program counter

		// jump evaluates and checks whether the given jump destination is a valid one
		// if valid move the `pc` otherwise return an error.
		jump = func(from uint64, to *big.Int) error {
			if !context.jumpdests.has(codehash, code, to) {
				nop := context.GetOp(to.Uint64())
				return fmt.Errorf("invalid jump destination (%v) %v", nop, to)
			}

			pc = to.Uint64()

			return nil
		}

		newMemSize *big.Int
		cost       *big.Int
	)

	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
	defer func() {
		if err != nil {
			self.log(pc, op, context.Gas, cost, mem, stack, context, err)
		}
	}()

	// Don't bother with the execution if there's no code.
	if len(code) == 0 {
		return context.Return(nil), nil
	}

	for {
		// Overhead of the atomic read might not be worth it
		/* TODO this still causes a few issues in the tests
		if program != nil && progStatus(atomic.LoadInt32(&program.status)) == progReady {
			// move execution
			glog.V(logger.Info).Infoln("Moved execution to JIT")
			return runProgram(program, pc, mem, stack, self.env, context, input)
		}
		*/
		// The base for all big integer arithmetic
		base := new(big.Int)

		// Get the memory location of pc
		op = context.GetOp(pc)

		// calculate the new memory size and gas price for the current executing opcode
		newMemSize, cost, err = calculateGasAndSize(self.env, context, caller, op, statedb, mem, stack)
		if err != nil {
			return nil, err
		}

		// Use the calculated gas. When insufficient gas is present, use all gas and return an
		// Out Of Gas error
		if !context.UseGas(cost) {
			return nil, OutOfGasError
		}

		// Resize the memory calculated previously
		mem.Resize(newMemSize.Uint64())
		// Add a log message
		self.log(pc, op, context.Gas, cost, mem, stack, context, nil)

		switch op {
		case ADD:
			x, y := stack.pop(), stack.pop()

			base.Add(x, y)

			U256(base)

			// pop result back on the stack
			stack.push(base)
		case SUB:
			x, y := stack.pop(), stack.pop()

			base.Sub(x, y)

			U256(base)

			// pop result back on the stack
			stack.push(base)
		case MUL:
			x, y := stack.pop(), stack.pop()

			base.Mul(x, y)

			U256(base)

			// pop result back on the stack
			stack.push(base)
		case DIV:
			x, y := stack.pop(), stack.pop()

			if y.Cmp(common.Big0) != 0 {
				base.Div(x, y)
			}

			U256(base)

			// pop result back on the stack
			stack.push(base)
		case SDIV:
			x, y := S256(stack.pop()), S256(stack.pop())

			if y.Cmp(common.Big0) == 0 {
				base.Set(common.Big0)
			} else {
				n := new(big.Int)
				if new(big.Int).Mul(x, y).Cmp(common.Big0) < 0 {
					n.SetInt64(-1)
				} else {
					n.SetInt64(1)
				}

				base.Div(x.Abs(x), y.Abs(y)).Mul(base, n)

				U256(base)
			}

			stack.push(base)
		case MOD:
			x, y := stack.pop(), stack.pop()

			if y.Cmp(common.Big0) == 0 {
				base.Set(common.Big0)
			} else {
				base.Mod(x, y)
			}

			U256(base)

			stack.push(base)
		case SMOD:
			x, y := S256(stack.pop()), S256(stack.pop())

			if y.Cmp(common.Big0) == 0 {
				base.Set(common.Big0)
			} else {
				n := new(big.Int)
				if x.Cmp(common.Big0) < 0 {
					n.SetInt64(-1)
				} else {
					n.SetInt64(1)
				}

				base.Mod(x.Abs(x), y.Abs(y)).Mul(base, n)

				U256(base)
			}

			stack.push(base)

		case EXP:
			x, y := stack.pop(), stack.pop()

			base.Exp(x, y, Pow256)

			U256(base)

			stack.push(base)
		case SIGNEXTEND:
			back := stack.pop()
			if back.Cmp(big.NewInt(31)) < 0 {
				bit := uint(back.Uint64()*8 + 7)
				num := stack.pop()
				mask := new(big.Int).Lsh(common.Big1, bit)
				mask.Sub(mask, common.Big1)
				if common.BitTest(num, int(bit)) {
					num.Or(num, mask.Not(mask))
				} else {
					num.And(num, mask)
				}

				num = U256(num)

				stack.push(num)
			}
		case NOT:
			stack.push(U256(new(big.Int).Not(stack.pop())))
		case LT:
			x, y := stack.pop(), stack.pop()

			// x < y
			if x.Cmp(y) < 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}
		case GT:
			x, y := stack.pop(), stack.pop()

			// x > y
			if x.Cmp(y) > 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}

		case SLT:
			x, y := S256(stack.pop()), S256(stack.pop())

			// x < y
			if x.Cmp(S256(y)) < 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}
		case SGT:
			x, y := S256(stack.pop()), S256(stack.pop())

			// x > y
			if x.Cmp(y) > 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}

		case EQ:
			x, y := stack.pop(), stack.pop()

			// x == y
			if x.Cmp(y) == 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}
		case ISZERO:
			x := stack.pop()
			if x.Cmp(common.BigFalse) > 0 {
				stack.push(common.BigFalse)
			} else {
				stack.push(common.BigTrue)
			}

		case AND:
			x, y := stack.pop(), stack.pop()

			stack.push(base.And(x, y))
		case OR:
			x, y := stack.pop(), stack.pop()

			stack.push(base.Or(x, y))
		case XOR:
			x, y := stack.pop(), stack.pop()

			stack.push(base.Xor(x, y))
		case BYTE:
			th, val := stack.pop(), stack.pop()

			if th.Cmp(big.NewInt(32)) < 0 {
				byt := big.NewInt(int64(common.LeftPadBytes(val.Bytes(), 32)[th.Int64()]))

				base.Set(byt)
			} else {
				base.Set(common.BigFalse)
			}

			stack.push(base)
		case ADDMOD:
			x := stack.pop()
			y := stack.pop()
			z := stack.pop()

			if z.Cmp(Zero) > 0 {
				add := new(big.Int).Add(x, y)
				base.Mod(add, z)

				base = U256(base)
			}

			stack.push(base)
		case MULMOD:
			x := stack.pop()
			y := stack.pop()
			z := stack.pop()

			if z.Cmp(Zero) > 0 {
				mul := new(big.Int).Mul(x, y)
				base.Mod(mul, z)

				U256(base)
			}

			stack.push(base)

		case SHA3:
			offset, size := stack.pop(), stack.pop()
			data := crypto.Sha3(mem.Get(offset.Int64(), size.Int64()))

			stack.push(common.BigD(data))

		case ADDRESS:
			stack.push(common.Bytes2Big(context.Address().Bytes()))

		case BALANCE:
			addr := common.BigToAddress(stack.pop())
			balance := statedb.GetBalance(addr)

			stack.push(new(big.Int).Set(balance))

		case ORIGIN:
			origin := self.env.Origin()

			stack.push(origin.Big())

		case CALLER:
			caller := context.caller.Address()
			stack.push(common.Bytes2Big(caller.Bytes()))

		case CALLVALUE:
			stack.push(new(big.Int).Set(value))

		case CALLDATALOAD:
			data := getData(input, stack.pop(), common.Big32)

			stack.push(common.Bytes2Big(data))
		case CALLDATASIZE:
			l := int64(len(input))
			stack.push(big.NewInt(l))

		case CALLDATACOPY:
			var (
				mOff = stack.pop()
				cOff = stack.pop()
				l    = stack.pop()
			)
			data := getData(input, cOff, l)

			mem.Set(mOff.Uint64(), l.Uint64(), data)

		case CODESIZE, EXTCODESIZE:
			var code []byte
			if op == EXTCODESIZE {
				addr := common.BigToAddress(stack.pop())

				code = statedb.GetCode(addr)
			} else {
				code = context.Code
			}

			l := big.NewInt(int64(len(code)))
			stack.push(l)

		case CODECOPY, EXTCODECOPY:
			var code []byte
			if op == EXTCODECOPY {
				addr := common.BigToAddress(stack.pop())
				code = statedb.GetCode(addr)
			} else {
				code = context.Code
			}

			var (
				mOff = stack.pop()
				cOff = stack.pop()
				l    = stack.pop()
			)

			codeCopy := getData(code, cOff, l)

			mem.Set(mOff.Uint64(), l.Uint64(), codeCopy)

		case GASPRICE:
			stack.push(new(big.Int).Set(context.Price))

		case BLOCKHASH:
			num := stack.pop()

			n := new(big.Int).Sub(self.env.BlockNumber(), common.Big257)
			if num.Cmp(n) > 0 && num.Cmp(self.env.BlockNumber()) < 0 {
				stack.push(self.env.GetHash(num.Uint64()).Big())
			} else {
				stack.push(common.Big0)
			}

		case COINBASE:
			coinbase := self.env.Coinbase()

			stack.push(coinbase.Big())

		case TIMESTAMP:
			time := self.env.Time()

			stack.push(new(big.Int).Set(time))

		case NUMBER:
			number := self.env.BlockNumber()

			stack.push(U256(number))

		case DIFFICULTY:
			difficulty := self.env.Difficulty()

			stack.push(new(big.Int).Set(difficulty))

		case GASLIMIT:

			stack.push(new(big.Int).Set(self.env.GasLimit()))

		case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32:
			size := uint64(op - PUSH1 + 1)
			byts := getData(code, new(big.Int).SetUint64(pc+1), new(big.Int).SetUint64(size))
			// push value to stack
			stack.push(common.Bytes2Big(byts))
			pc += size

		case POP:
			stack.pop()
		case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
			n := int(op - DUP1 + 1)
			stack.dup(n)

		case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
			n := int(op - SWAP1 + 2)
			stack.swap(n)

		case LOG0, LOG1, LOG2, LOG3, LOG4:
			n := int(op - LOG0)
			topics := make([]common.Hash, n)
			mStart, mSize := stack.pop(), stack.pop()
			for i := 0; i < n; i++ {
				topics[i] = common.BigToHash(stack.pop())
			}

			data := mem.Get(mStart.Int64(), mSize.Int64())
			log := state.NewLog(context.Address(), topics, data, self.env.BlockNumber().Uint64())
			self.env.AddLog(log)

		case MLOAD:
			offset := stack.pop()
			val := common.BigD(mem.Get(offset.Int64(), 32))
			stack.push(val)

		case MSTORE:
			// pop value of the stack
			mStart, val := stack.pop(), stack.pop()
			mem.Set(mStart.Uint64(), 32, common.BigToBytes(val, 256))

		case MSTORE8:
			off, val := stack.pop().Int64(), stack.pop().Int64()

			mem.store[off] = byte(val & 0xff)

		case SLOAD:
			loc := common.BigToHash(stack.pop())
			val := statedb.GetState(context.Address(), loc).Big()
			stack.push(val)

		case SSTORE:
			loc := common.BigToHash(stack.pop())
			val := stack.pop()

			statedb.SetState(context.Address(), loc, common.BigToHash(val))

		case JUMP:
			if err := jump(pc, stack.pop()); err != nil {
				return nil, err
			}

			continue
		case JUMPI:
			pos, cond := stack.pop(), stack.pop()

			if cond.Cmp(common.BigTrue) >= 0 {
				if err := jump(pc, pos); err != nil {
					return nil, err
				}

				continue
			}

		case JUMPDEST:
		case PC:
			stack.push(new(big.Int).SetUint64(pc))
		case MSIZE:
			stack.push(big.NewInt(int64(mem.Len())))
		case GAS:
			stack.push(new(big.Int).Set(context.Gas))
		case CREATE:

			var (
				value        = stack.pop()
				offset, size = stack.pop(), stack.pop()
				input        = mem.Get(offset.Int64(), size.Int64())
				gas          = new(big.Int).Set(context.Gas)
				addr         common.Address
			)

			context.UseGas(context.Gas)
			ret, suberr, ref := self.env.Create(context, input, gas, price, value)
			if suberr != nil {
				stack.push(common.BigFalse)

			} else {
				// gas < len(ret) * CreateDataGas == NO_CODE
				dataGas := big.NewInt(int64(len(ret)))
				dataGas.Mul(dataGas, params.CreateDataGas)
				if context.UseGas(dataGas) {
					ref.SetCode(ret)
				}
				addr = ref.Address()

				stack.push(addr.Big())

			}

		case CALL, CALLCODE:
			gas := stack.pop()
			// pop gas and value of the stack.
			addr, value := stack.pop(), stack.pop()
			value = U256(value)
			// pop input size and offset
			inOffset, inSize := stack.pop(), stack.pop()
			// pop return size and offset
			retOffset, retSize := stack.pop(), stack.pop()

			address := common.BigToAddress(addr)

			// Get the arguments from the memory
			args := mem.Get(inOffset.Int64(), inSize.Int64())

			if len(value.Bytes()) > 0 {
				gas.Add(gas, params.CallStipend)
			}

			var (
				ret []byte
				err error
			)
			if op == CALLCODE {
				ret, err = self.env.CallCode(context, address, args, gas, price, value)
			} else {
				ret, err = self.env.Call(context, address, args, gas, price, value)
			}

			if err != nil {
				stack.push(common.BigFalse)

			} else {
				stack.push(common.BigTrue)

				mem.Set(retOffset.Uint64(), retSize.Uint64(), ret)
			}

		case RETURN:
			offset, size := stack.pop(), stack.pop()
			ret := mem.GetPtr(offset.Int64(), size.Int64())

			return context.Return(ret), nil
		case SUICIDE:
			receiver := statedb.GetOrNewStateObject(common.BigToAddress(stack.pop()))
			balance := statedb.GetBalance(context.Address())

			receiver.AddBalance(balance)

			statedb.Delete(context.Address())

			fallthrough
		case STOP: // Stop the context

			return context.Return(nil), nil
		default:

			return nil, fmt.Errorf("Invalid opcode %x", op)
		}

		pc++

	}
}
Exemplo n.º 13
0
func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) {
	self.env.SetDepth(self.env.Depth() + 1)
	defer self.env.SetDepth(self.env.Depth() - 1)

	var (
		caller = context.caller
		code   = context.Code
		value  = context.value
		price  = context.Price
	)

	self.Printf("(%d) (%x) %x (code=%d) gas: %v (d) %x", self.env.Depth(), caller.Address().Bytes()[:4], context.Address(), len(code), context.Gas, callData).Endl()

	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
	defer func() {
		if self.After != nil {
			self.After(context, err)
		}

		if err != nil {
			self.Printf(" %v", err).Endl()
			// In case of a VM exception (known exceptions) all gas consumed (panics NOT included).
			context.UseGas(context.Gas)

			ret = context.Return(nil)
		}
	}()

	if context.CodeAddr != nil {
		if p := Precompiled[context.CodeAddr.Str()]; p != nil {
			return self.RunPrecompiled(p, callData, context)
		}
	}

	var (
		op OpCode

		destinations = analyseJumpDests(context.Code)
		mem          = NewMemory()
		stack        = newStack()
		pc           = new(big.Int)
		statedb      = self.env.State()

		jump = func(from *big.Int, to *big.Int) error {
			nop := context.GetOp(to)
			if !destinations.Has(to) {
				return fmt.Errorf("invalid jump destination (%v) %v", nop, to)
			}

			self.Printf(" ~> %v", to)
			pc = to

			self.Endl()

			return nil
		}
	)

	// Don't bother with the execution if there's no code.
	if len(code) == 0 {
		return context.Return(nil), nil
	}

	for {
		// The base for all big integer arithmetic
		base := new(big.Int)

		// Get the memory location of pc
		op = context.GetOp(pc)

		self.Printf("(pc) %-3d -o- %-14s (m) %-4d (s) %-4d ", pc, op.String(), mem.Len(), stack.len())
		newMemSize, gas, err := self.calculateGasAndSize(context, caller, op, statedb, mem, stack)
		if err != nil {
			return nil, err
		}

		self.Printf("(g) %-3v (%v)", gas, context.Gas)

		if !context.UseGas(gas) {
			self.Endl()

			tmp := new(big.Int).Set(context.Gas)

			context.UseGas(context.Gas)

			return context.Return(nil), OOG(gas, tmp)
		}

		mem.Resize(newMemSize.Uint64())

		switch op {
		// 0x20 range
		case ADD:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v + %v", y, x)

			base.Add(x, y)

			U256(base)

			self.Printf(" = %v", base)
			// pop result back on the stack
			stack.push(base)
		case SUB:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v - %v", y, x)

			base.Sub(x, y)

			U256(base)

			self.Printf(" = %v", base)
			// pop result back on the stack
			stack.push(base)
		case MUL:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v * %v", y, x)

			base.Mul(x, y)

			U256(base)

			self.Printf(" = %v", base)
			// pop result back on the stack
			stack.push(base)
		case DIV:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v / %v", x, y)

			if y.Cmp(common.Big0) != 0 {
				base.Div(x, y)
			}

			U256(base)

			self.Printf(" = %v", base)
			// pop result back on the stack
			stack.push(base)
		case SDIV:
			x, y := S256(stack.pop()), S256(stack.pop())

			self.Printf(" %v / %v", x, y)

			if y.Cmp(common.Big0) == 0 {
				base.Set(common.Big0)
			} else {
				n := new(big.Int)
				if new(big.Int).Mul(x, y).Cmp(common.Big0) < 0 {
					n.SetInt64(-1)
				} else {
					n.SetInt64(1)
				}

				base.Div(x.Abs(x), y.Abs(y)).Mul(base, n)

				U256(base)
			}

			self.Printf(" = %v", base)
			stack.push(base)
		case MOD:
			x, y := stack.pop(), stack.pop()

			self.Printf(" %v %% %v", x, y)

			if y.Cmp(common.Big0) == 0 {
				base.Set(common.Big0)
			} else {
				base.Mod(x, y)
			}

			U256(base)

			self.Printf(" = %v", base)
			stack.push(base)
		case SMOD:
			x, y := S256(stack.pop()), S256(stack.pop())

			self.Printf(" %v %% %v", x, y)

			if y.Cmp(common.Big0) == 0 {
				base.Set(common.Big0)
			} else {
				n := new(big.Int)
				if x.Cmp(common.Big0) < 0 {
					n.SetInt64(-1)
				} else {
					n.SetInt64(1)
				}

				base.Mod(x.Abs(x), y.Abs(y)).Mul(base, n)

				U256(base)
			}

			self.Printf(" = %v", base)
			stack.push(base)

		case EXP:
			x, y := stack.pop(), stack.pop()

			self.Printf(" %v ** %v", x, y)

			base.Exp(x, y, Pow256)

			U256(base)

			self.Printf(" = %v", base)

			stack.push(base)
		case SIGNEXTEND:
			back := stack.pop()
			if back.Cmp(big.NewInt(31)) < 0 {
				bit := uint(back.Uint64()*8 + 7)
				num := stack.pop()
				mask := new(big.Int).Lsh(common.Big1, bit)
				mask.Sub(mask, common.Big1)
				if common.BitTest(num, int(bit)) {
					num.Or(num, mask.Not(mask))
				} else {
					num.And(num, mask)
				}

				num = U256(num)

				self.Printf(" = %v", num)

				stack.push(num)
			}
		case NOT:
			stack.push(U256(new(big.Int).Not(stack.pop())))
			//base.Sub(Pow256, stack.pop()).Sub(base, common.Big1)
			//base = U256(base)
			//stack.push(base)
		case LT:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v < %v", x, y)
			// x < y
			if x.Cmp(y) < 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}
		case GT:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v > %v", x, y)

			// x > y
			if x.Cmp(y) > 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}

		case SLT:
			x, y := S256(stack.pop()), S256(stack.pop())
			self.Printf(" %v < %v", x, y)
			// x < y
			if x.Cmp(S256(y)) < 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}
		case SGT:
			x, y := S256(stack.pop()), S256(stack.pop())
			self.Printf(" %v > %v", x, y)

			// x > y
			if x.Cmp(y) > 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}

		case EQ:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v == %v", y, x)

			// x == y
			if x.Cmp(y) == 0 {
				stack.push(common.BigTrue)
			} else {
				stack.push(common.BigFalse)
			}
		case ISZERO:
			x := stack.pop()
			if x.Cmp(common.BigFalse) > 0 {
				stack.push(common.BigFalse)
			} else {
				stack.push(common.BigTrue)
			}

			// 0x10 range
		case AND:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v & %v", y, x)

			stack.push(base.And(x, y))
		case OR:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v | %v", x, y)

			stack.push(base.Or(x, y))
		case XOR:
			x, y := stack.pop(), stack.pop()
			self.Printf(" %v ^ %v", x, y)

			stack.push(base.Xor(x, y))
		case BYTE:
			th, val := stack.pop(), stack.pop()

			if th.Cmp(big.NewInt(32)) < 0 {
				byt := big.NewInt(int64(common.LeftPadBytes(val.Bytes(), 32)[th.Int64()]))

				base.Set(byt)
			} else {
				base.Set(common.BigFalse)
			}

			self.Printf(" => 0x%x", base.Bytes())

			stack.push(base)
		case ADDMOD:
			x := stack.pop()
			y := stack.pop()
			z := stack.pop()

			if z.Cmp(Zero) > 0 {
				add := new(big.Int).Add(x, y)
				base.Mod(add, z)

				base = U256(base)
			}

			self.Printf(" %v + %v %% %v = %v", x, y, z, base)

			stack.push(base)
		case MULMOD:
			x := stack.pop()
			y := stack.pop()
			z := stack.pop()

			if z.Cmp(Zero) > 0 {
				mul := new(big.Int).Mul(x, y)
				base.Mod(mul, z)

				U256(base)
			}

			self.Printf(" %v + %v %% %v = %v", x, y, z, base)

			stack.push(base)

			// 0x20 range
		case SHA3:
			offset, size := stack.pop(), stack.pop()
			data := crypto.Sha3(mem.Get(offset.Int64(), size.Int64()))

			stack.push(common.BigD(data))

			self.Printf(" => (%v) %x", size, data)
			// 0x30 range
		case ADDRESS:
			stack.push(common.Bytes2Big(context.Address().Bytes()))

			self.Printf(" => %x", context.Address())
		case BALANCE:
			addr := common.BigToAddress(stack.pop())
			balance := statedb.GetBalance(addr)

			stack.push(balance)

			self.Printf(" => %v (%x)", balance, addr)
		case ORIGIN:
			origin := self.env.Origin()

			stack.push(origin.Big())

			self.Printf(" => %x", origin)
		case CALLER:
			caller := context.caller.Address()
			stack.push(common.Bytes2Big(caller.Bytes()))

			self.Printf(" => %x", caller)
		case CALLVALUE:
			stack.push(value)

			self.Printf(" => %v", value)
		case CALLDATALOAD:
			data := getData(callData, stack.pop(), common.Big32)

			self.Printf(" => 0x%x", data)

			stack.push(common.Bytes2Big(data))
		case CALLDATASIZE:
			l := int64(len(callData))
			stack.push(big.NewInt(l))

			self.Printf(" => %d", l)
		case CALLDATACOPY:
			var (
				mOff = stack.pop()
				cOff = stack.pop()
				l    = stack.pop()
			)
			data := getData(callData, cOff, l)

			mem.Set(mOff.Uint64(), l.Uint64(), data)

			self.Printf(" => [%v, %v, %v]", mOff, cOff, l)
		case CODESIZE, EXTCODESIZE:
			var code []byte
			if op == EXTCODESIZE {
				addr := common.BigToAddress(stack.pop())

				code = statedb.GetCode(addr)
			} else {
				code = context.Code
			}

			l := big.NewInt(int64(len(code)))
			stack.push(l)

			self.Printf(" => %d", l)
		case CODECOPY, EXTCODECOPY:
			var code []byte
			if op == EXTCODECOPY {
				addr := common.BigToAddress(stack.pop())
				code = statedb.GetCode(addr)
			} else {
				code = context.Code
			}

			var (
				mOff = stack.pop()
				cOff = stack.pop()
				l    = stack.pop()
			)

			codeCopy := getData(code, cOff, l)

			mem.Set(mOff.Uint64(), l.Uint64(), codeCopy)

			self.Printf(" => [%v, %v, %v] %x", mOff, cOff, l, codeCopy)
		case GASPRICE:
			stack.push(context.Price)

			self.Printf(" => %x", context.Price)

			// 0x40 range
		case BLOCKHASH:
			num := stack.pop()

			n := new(big.Int).Sub(self.env.BlockNumber(), common.Big257)
			if num.Cmp(n) > 0 && num.Cmp(self.env.BlockNumber()) < 0 {
				stack.push(self.env.GetHash(num.Uint64()).Big())
			} else {
				stack.push(common.Big0)
			}

			self.Printf(" => 0x%x", stack.peek().Bytes())
		case COINBASE:
			coinbase := self.env.Coinbase()

			stack.push(coinbase.Big())

			self.Printf(" => 0x%x", coinbase)
		case TIMESTAMP:
			time := self.env.Time()

			stack.push(big.NewInt(time))

			self.Printf(" => 0x%x", time)
		case NUMBER:
			number := self.env.BlockNumber()

			stack.push(U256(number))

			self.Printf(" => 0x%x", number.Bytes())
		case DIFFICULTY:
			difficulty := self.env.Difficulty()

			stack.push(difficulty)

			self.Printf(" => 0x%x", difficulty.Bytes())
		case GASLIMIT:
			self.Printf(" => %v", self.env.GasLimit())

			stack.push(self.env.GasLimit())

			// 0x50 range
		case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32:
			a := big.NewInt(int64(op - PUSH1 + 1))
			byts := getData(code, new(big.Int).Add(pc, big.NewInt(1)), a)
			// push value to stack
			stack.push(common.Bytes2Big(byts))
			pc.Add(pc, a)

			self.Printf(" => 0x%x", byts)
		case POP:
			stack.pop()
		case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
			n := int(op - DUP1 + 1)
			stack.dup(n)

			self.Printf(" => [%d] 0x%x", n, stack.peek().Bytes())
		case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
			n := int(op - SWAP1 + 2)
			stack.swap(n)

			self.Printf(" => [%d]", n)
		case LOG0, LOG1, LOG2, LOG3, LOG4:
			n := int(op - LOG0)
			topics := make([]common.Hash, n)
			mStart, mSize := stack.pop(), stack.pop()
			for i := 0; i < n; i++ {
				topics[i] = common.BigToHash(stack.pop()) //common.LeftPadBytes(stack.pop().Bytes(), 32)
			}

			data := mem.Get(mStart.Int64(), mSize.Int64())
			log := state.NewLog(context.Address(), topics, data, self.env.BlockNumber().Uint64())
			//log := &Log{context.Address(), topics, data, self.env.BlockNumber().Uint64()}
			self.env.AddLog(log)

			self.Printf(" => %v", log)
		case MLOAD:
			offset := stack.pop()
			val := common.BigD(mem.Get(offset.Int64(), 32))
			stack.push(val)

			self.Printf(" => 0x%x", val.Bytes())
		case MSTORE: // Store the value at stack top-1 in to memory at location stack top
			// pop value of the stack
			mStart, val := stack.pop(), stack.pop()
			mem.Set(mStart.Uint64(), 32, common.BigToBytes(val, 256))

			self.Printf(" => 0x%x", val)
		case MSTORE8:
			off, val := stack.pop().Int64(), stack.pop().Int64()

			mem.store[off] = byte(val & 0xff)

			self.Printf(" => [%v] 0x%x", off, mem.store[off])
		case SLOAD:
			loc := common.BigToHash(stack.pop())
			val := common.Bytes2Big(statedb.GetState(context.Address(), loc))
			stack.push(val)

			self.Printf(" {0x%x : 0x%x}", loc, val.Bytes())
		case SSTORE:
			loc := common.BigToHash(stack.pop())
			val := stack.pop()

			statedb.SetState(context.Address(), loc, val)

			self.Printf(" {0x%x : 0x%x}", loc, val.Bytes())
		case JUMP:
			if err := jump(pc, stack.pop()); err != nil {
				return nil, err
			}

			continue
		case JUMPI:
			pos, cond := stack.pop(), stack.pop()

			if cond.Cmp(common.BigTrue) >= 0 {
				if err := jump(pc, pos); err != nil {
					return nil, err
				}

				continue
			}

			self.Printf(" ~> false")

		case JUMPDEST:
		case PC:
			//stack.push(big.NewInt(int64(pc)))
			stack.push(pc)
		case MSIZE:
			stack.push(big.NewInt(int64(mem.Len())))
		case GAS:
			stack.push(context.Gas)

			self.Printf(" => %x", context.Gas)
			// 0x60 range
		case CREATE:

			var (
				value        = stack.pop()
				offset, size = stack.pop(), stack.pop()
				input        = mem.Get(offset.Int64(), size.Int64())
				gas          = new(big.Int).Set(context.Gas)
				addr         common.Address
			)
			self.Endl()

			context.UseGas(context.Gas)
			ret, suberr, ref := self.env.Create(context, input, gas, price, value)
			if suberr != nil {
				stack.push(common.BigFalse)

				self.Printf(" (*) 0x0 %v", suberr)
			} else {
				// gas < len(ret) * CreateDataGas == NO_CODE
				dataGas := big.NewInt(int64(len(ret)))
				dataGas.Mul(dataGas, params.CreateDataGas)
				if context.UseGas(dataGas) {
					ref.SetCode(ret)
				}
				addr = ref.Address()

				stack.push(addr.Big())

			}

		case CALL, CALLCODE:
			gas := stack.pop()
			// pop gas and value of the stack.
			addr, value := stack.pop(), stack.pop()
			value = U256(value)
			// pop input size and offset
			inOffset, inSize := stack.pop(), stack.pop()
			// pop return size and offset
			retOffset, retSize := stack.pop(), stack.pop()

			address := common.BigToAddress(addr)
			self.Printf(" => %x", address).Endl()

			// Get the arguments from the memory
			args := mem.Get(inOffset.Int64(), inSize.Int64())

			if len(value.Bytes()) > 0 {
				gas.Add(gas, params.CallStipend)
			}

			var (
				ret []byte
				err error
			)
			if op == CALLCODE {
				ret, err = self.env.CallCode(context, address, args, gas, price, value)
			} else {
				ret, err = self.env.Call(context, address, args, gas, price, value)
			}

			if err != nil {
				stack.push(common.BigFalse)

				self.Printf("%v").Endl()
			} else {
				stack.push(common.BigTrue)

				mem.Set(retOffset.Uint64(), retSize.Uint64(), ret)
			}
			self.Printf("resume %x (%v)", context.Address(), context.Gas)
		case RETURN:
			offset, size := stack.pop(), stack.pop()
			ret := mem.Get(offset.Int64(), size.Int64())

			self.Printf(" => [%v, %v] (%d) 0x%x", offset, size, len(ret), ret).Endl()

			return context.Return(ret), nil
		case SUICIDE:
			receiver := statedb.GetOrNewStateObject(common.BigToAddress(stack.pop()))
			balance := statedb.GetBalance(context.Address())

			self.Printf(" => (%x) %v", receiver.Address().Bytes()[:4], balance)

			receiver.AddBalance(balance)

			statedb.Delete(context.Address())

			fallthrough
		case STOP: // Stop the context
			self.Endl()

			return context.Return(nil), nil
		default:
			self.Printf("(pc) %-3v Invalid opcode %x\n", pc, op).Endl()

			return nil, fmt.Errorf("Invalid opcode %x", op)
		}

		pc.Add(pc, One)

		self.Endl()
	}
}
Exemplo n.º 14
0
func (self *Vm) RunClosure(closure *Closure) (ret []byte, err error) {
	if self.Recoverable {
		// Recover from any require exception
		defer func() {
			if r := recover(); r != nil {
				ret = closure.Return(nil)
				err = fmt.Errorf("%v", r)
				vmlogger.Errorln("vm err", err)
			}
		}()
	}

	// Debug hook
	if self.Dbg != nil {
		self.Dbg.SetCode(closure.Code)
	}

	// Don't bother with the execution if there's no code.
	if len(closure.Code) == 0 {
		return closure.Return(nil), nil
	}

	vmlogger.Debugf("(%s) %x gas: %v (d) %x\n", self.Fn, closure.Address(), closure.Gas, closure.Args)

	var (
		op OpCode

		mem      = &Memory{}
		stack    = NewStack()
		pc       = big.NewInt(0)
		step     = 0
		prevStep = 0
		require  = func(m int) {
			if stack.Len() < m {
				panic(fmt.Sprintf("%04v (%v) stack err size = %d, required = %d", pc, op, stack.Len(), m))
			}
		}
	)

	for {
		prevStep = step
		// The base for all big integer arithmetic
		base := new(big.Int)

		step++
		// Get the memory location of pc
		val := closure.Get(pc)
		// Get the opcode (it must be an opcode!)
		op = OpCode(val.Uint())

		// XXX Leave this Println intact. Don't change this to the log system.
		// Used for creating diffs between implementations
		if self.logTy == LogTyDiff {
			/*
				switch op {
				case STOP, RETURN, SUICIDE:
					closure.object.EachStorage(func(key string, value *ethutil.Value) {
						value.Decode()
						fmt.Printf("%x %x\n", new(big.Int).SetBytes([]byte(key)).Bytes(), value.Bytes())
					})
				}
			*/

			b := pc.Bytes()
			if len(b) == 0 {
				b = []byte{0}
			}

			fmt.Printf("%x %x %x %x\n", closure.Address(), b, []byte{byte(op)}, closure.Gas.Bytes())
		}

		gas := new(big.Int)
		addStepGasUsage := func(amount *big.Int) {
			if amount.Cmp(ethutil.Big0) >= 0 {
				gas.Add(gas, amount)
			}
		}

		addStepGasUsage(GasStep)

		var newMemSize uint64 = 0
		switch op {
		case STOP:
			gas.Set(ethutil.Big0)
		case SUICIDE:
			gas.Set(ethutil.Big0)
		case SLOAD:
			gas.Set(GasSLoad)
		case SSTORE:
			var mult *big.Int
			y, x := stack.Peekn()
			val := closure.GetStorage(x)
			if val.BigInt().Cmp(ethutil.Big0) == 0 && len(y.Bytes()) > 0 {
				mult = ethutil.Big2
			} else if val.BigInt().Cmp(ethutil.Big0) != 0 && len(y.Bytes()) == 0 {
				mult = ethutil.Big0
			} else {
				mult = ethutil.Big1
			}
			gas = new(big.Int).Mul(mult, GasSStore)
		case BALANCE:
			gas.Set(GasBalance)
		case MSTORE:
			require(2)
			newMemSize = stack.Peek().Uint64() + 32
		case MLOAD:
			require(1)

			newMemSize = stack.Peek().Uint64() + 32
		case MSTORE8:
			require(2)
			newMemSize = stack.Peek().Uint64() + 1
		case RETURN:
			require(2)

			newMemSize = stack.Peek().Uint64() + stack.data[stack.Len()-2].Uint64()
		case SHA3:
			require(2)

			gas.Set(GasSha)

			newMemSize = stack.Peek().Uint64() + stack.data[stack.Len()-2].Uint64()
		case CALLDATACOPY:
			require(3)

			newMemSize = stack.Peek().Uint64() + stack.data[stack.Len()-3].Uint64()
		case CODECOPY:
			require(3)

			newMemSize = stack.Peek().Uint64() + stack.data[stack.Len()-3].Uint64()
		case CALL:
			require(7)
			gas.Set(GasCall)
			addStepGasUsage(stack.data[stack.Len()-1])

			x := stack.data[stack.Len()-6].Uint64() + stack.data[stack.Len()-7].Uint64()
			y := stack.data[stack.Len()-4].Uint64() + stack.data[stack.Len()-5].Uint64()

			newMemSize = uint64(math.Max(float64(x), float64(y)))
		case CREATE:
			require(3)
			gas.Set(GasCreate)

			newMemSize = stack.data[stack.Len()-2].Uint64() + stack.data[stack.Len()-3].Uint64()
		}

		newMemSize = (newMemSize + 31) / 32 * 32
		if newMemSize > uint64(mem.Len()) {
			m := GasMemory.Uint64() * (newMemSize - uint64(mem.Len())) / 32
			addStepGasUsage(big.NewInt(int64(m)))
		}

		if !closure.UseGas(gas) {
			err := fmt.Errorf("Insufficient gas for %v. req %v has %v", op, gas, closure.Gas)

			closure.UseGas(closure.Gas)

			return closure.Return(nil), err
		}

		self.Printf("(pc) %-3d -o- %-14s", pc, op.String())
		self.Printf(" (g) %-3v (%v)", gas, closure.Gas)

		mem.Resize(newMemSize)

		switch op {
		case LOG:
			stack.Print()
			mem.Print()
			// 0x20 range
		case ADD:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v + %v", y, x)

			base.Add(y, x)

			ensure256(base)

			self.Printf(" = %v", base)
			// Pop result back on the stack
			stack.Push(base)
		case SUB:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v - %v", y, x)

			base.Sub(y, x)

			ensure256(base)

			self.Printf(" = %v", base)
			// Pop result back on the stack
			stack.Push(base)
		case MUL:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v * %v", y, x)

			base.Mul(y, x)

			ensure256(base)

			self.Printf(" = %v", base)
			// Pop result back on the stack
			stack.Push(base)
		case DIV:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v / %v", y, x)

			if x.Cmp(ethutil.Big0) != 0 {
				base.Div(y, x)
			}

			ensure256(base)

			self.Printf(" = %v", base)
			// Pop result back on the stack
			stack.Push(base)
		case SDIV:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v / %v", y, x)

			if x.Cmp(ethutil.Big0) != 0 {
				base.Div(y, x)
			}

			ensure256(base)

			self.Printf(" = %v", base)
			// Pop result back on the stack
			stack.Push(base)
		case MOD:
			require(2)
			x, y := stack.Popn()

			self.Printf(" %v %% %v", y, x)

			base.Mod(y, x)

			ensure256(base)

			self.Printf(" = %v", base)
			stack.Push(base)
		case SMOD:
			require(2)
			x, y := stack.Popn()

			self.Printf(" %v %% %v", y, x)

			base.Mod(y, x)

			ensure256(base)

			self.Printf(" = %v", base)
			stack.Push(base)

		case EXP:
			require(2)
			x, y := stack.Popn()

			self.Printf(" %v ** %v", y, x)

			base.Exp(y, x, Pow256)

			ensure256(base)

			self.Printf(" = %v", base)

			stack.Push(base)
		case NEG:
			require(1)
			base.Sub(Pow256, stack.Pop())
			stack.Push(base)
		case LT:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v < %v", y, x)
			// x < y
			if y.Cmp(x) < 0 {
				stack.Push(ethutil.BigTrue)
			} else {
				stack.Push(ethutil.BigFalse)
			}
		case GT:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v > %v", y, x)

			// x > y
			if y.Cmp(x) > 0 {
				stack.Push(ethutil.BigTrue)
			} else {
				stack.Push(ethutil.BigFalse)
			}

		case SLT:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v < %v", y, x)
			// x < y
			if y.Cmp(x) < 0 {
				stack.Push(ethutil.BigTrue)
			} else {
				stack.Push(ethutil.BigFalse)
			}
		case SGT:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v > %v", y, x)

			// x > y
			if y.Cmp(x) > 0 {
				stack.Push(ethutil.BigTrue)
			} else {
				stack.Push(ethutil.BigFalse)
			}

		case EQ:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v == %v", y, x)

			// x == y
			if x.Cmp(y) == 0 {
				stack.Push(ethutil.BigTrue)
			} else {
				stack.Push(ethutil.BigFalse)
			}
		case NOT:
			require(1)
			x := stack.Pop()
			if x.Cmp(ethutil.BigFalse) > 0 {
				stack.Push(ethutil.BigFalse)
			} else {
				stack.Push(ethutil.BigTrue)
			}

			// 0x10 range
		case AND:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v & %v", y, x)

			stack.Push(base.And(y, x))
		case OR:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v | %v", y, x)

			stack.Push(base.Or(y, x))
		case XOR:
			require(2)
			x, y := stack.Popn()
			self.Printf(" %v ^ %v", y, x)

			stack.Push(base.Xor(y, x))
		case BYTE:
			require(2)
			val, th := stack.Popn()
			if th.Cmp(big.NewInt(32)) < 0 && th.Cmp(big.NewInt(int64(len(val.Bytes())))) < 0 {
				byt := big.NewInt(int64(ethutil.LeftPadBytes(val.Bytes(), 32)[th.Int64()]))
				stack.Push(byt)

				self.Printf(" => 0x%x", byt.Bytes())
			} else {
				stack.Push(ethutil.BigFalse)
			}
		case ADDMOD:
			require(3)

			x := stack.Pop()
			y := stack.Pop()
			z := stack.Pop()

			base.Add(x, y)
			base.Mod(base, z)

			ensure256(base)

			self.Printf(" = %v", base)

			stack.Push(base)
		case MULMOD:
			require(3)

			x := stack.Pop()
			y := stack.Pop()
			z := stack.Pop()

			base.Mul(x, y)
			base.Mod(base, z)

			ensure256(base)

			self.Printf(" = %v", base)

			stack.Push(base)

			// 0x20 range
		case SHA3:
			require(2)
			size, offset := stack.Popn()
			data := ethcrypto.Sha3Bin(mem.Get(offset.Int64(), size.Int64()))

			stack.Push(ethutil.BigD(data))

			self.Printf(" => %x", data)
			// 0x30 range
		case ADDRESS:
			stack.Push(ethutil.BigD(closure.Address()))

			self.Printf(" => %x", closure.Address())
		case BALANCE:
			require(1)

			addr := stack.Pop().Bytes()
			balance := self.env.State().GetBalance(addr)

			stack.Push(balance)

			self.Printf(" => %v (%x)", balance, addr)
		case ORIGIN:
			origin := self.env.Origin()

			stack.Push(ethutil.BigD(origin))

			self.Printf(" => %x", origin)
		case CALLER:
			caller := closure.caller.Address()
			stack.Push(ethutil.BigD(caller))

			self.Printf(" => %x", caller)
		case CALLVALUE:
			value := self.env.Value()

			stack.Push(value)

			self.Printf(" => %v", value)
		case CALLDATALOAD:
			require(1)
			var (
				offset  = stack.Pop()
				data    = make([]byte, 32)
				lenData = big.NewInt(int64(len(closure.Args)))
			)

			if lenData.Cmp(offset) >= 0 {
				length := new(big.Int).Add(offset, ethutil.Big32)
				length = ethutil.BigMin(length, lenData)

				copy(data, closure.Args[offset.Int64():length.Int64()])
			}

			self.Printf(" => 0x%x", data)

			stack.Push(ethutil.BigD(data))
		case CALLDATASIZE:
			l := int64(len(closure.Args))
			stack.Push(big.NewInt(l))

			self.Printf(" => %d", l)
		case CALLDATACOPY:
			var (
				size = int64(len(closure.Args))
				mOff = stack.Pop().Int64()
				cOff = stack.Pop().Int64()
				l    = stack.Pop().Int64()
			)

			if cOff > size {
				cOff = 0
				l = 0
			} else if cOff+l > size {
				l = 0
			}

			code := closure.Args[cOff : cOff+l]

			mem.Set(mOff, l, code)
		case CODESIZE:
			l := big.NewInt(int64(len(closure.Code)))
			stack.Push(l)

			self.Printf(" => %d", l)
		case CODECOPY:
			var (
				size = int64(len(closure.Code))
				mOff = stack.Pop().Int64()
				cOff = stack.Pop().Int64()
				l    = stack.Pop().Int64()
			)

			if cOff > size {
				cOff = 0
				l = 0
			} else if cOff+l > size {
				l = 0
			}

			code := closure.Code[cOff : cOff+l]

			mem.Set(mOff, l, code)
		case GASPRICE:
			stack.Push(closure.Price)

			self.Printf(" => %v", closure.Price)

			// 0x40 range
		case PREVHASH:
			prevHash := self.env.PrevHash()

			stack.Push(ethutil.BigD(prevHash))

			self.Printf(" => 0x%x", prevHash)
		case COINBASE:
			coinbase := self.env.Coinbase()

			stack.Push(ethutil.BigD(coinbase))

			self.Printf(" => 0x%x", coinbase)
		case TIMESTAMP:
			time := self.env.Time()

			stack.Push(big.NewInt(time))

			self.Printf(" => 0x%x", time)
		case NUMBER:
			number := self.env.BlockNumber()

			stack.Push(number)

			self.Printf(" => 0x%x", number.Bytes())
		case DIFFICULTY:
			difficulty := self.env.Difficulty()

			stack.Push(difficulty)

			self.Printf(" => 0x%x", difficulty.Bytes())
		case GASLIMIT:
			// TODO
			stack.Push(big.NewInt(0))

			// 0x50 range
		case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32:
			a := big.NewInt(int64(op) - int64(PUSH1) + 1)
			pc.Add(pc, ethutil.Big1)
			data := closure.Gets(pc, a)
			val := ethutil.BigD(data.Bytes())
			// Push value to stack
			stack.Push(val)
			pc.Add(pc, a.Sub(a, big.NewInt(1)))

			step += int(op) - int(PUSH1) + 1

			self.Printf(" => 0x%x", data.Bytes())
		case POP:
			require(1)
			stack.Pop()
		case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
			n := int(op - DUP1 + 1)
			stack.Dupn(n)

			self.Printf(" => [%d] 0x%x", n, stack.Peek().Bytes())
		case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
			n := int(op - SWAP1 + 1)
			x, y := stack.Swapn(n)

			self.Printf(" => [%d] %x [0] %x", n, x.Bytes(), y.Bytes())
		case MLOAD:
			require(1)
			offset := stack.Pop()
			val := ethutil.BigD(mem.Get(offset.Int64(), 32))
			stack.Push(val)

			self.Printf(" => 0x%x", val.Bytes())
		case MSTORE: // Store the value at stack top-1 in to memory at location stack top
			require(2)
			// Pop value of the stack
			val, mStart := stack.Popn()
			mem.Set(mStart.Int64(), 32, ethutil.BigToBytes(val, 256))

			self.Printf(" => 0x%x", val)
		case MSTORE8:
			require(2)
			val, mStart := stack.Popn()
			//base.And(val, new(big.Int).SetInt64(0xff))
			//mem.Set(mStart.Int64(), 32, ethutil.BigToBytes(base, 256))
			mem.store[mStart.Int64()] = byte(val.Int64() & 0xff)

			self.Printf(" => 0x%x", val)
		case SLOAD:
			require(1)
			loc := stack.Pop()
			val := closure.GetStorage(loc)

			stack.Push(val.BigInt())

			self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes())
		case SSTORE:
			require(2)
			val, loc := stack.Popn()
			closure.SetStorage(loc, ethutil.NewValue(val))

			closure.message.AddStorageChange(loc.Bytes())

			self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes())
		case JUMP:
			require(1)
			pc = stack.Pop()
			// Reduce pc by one because of the increment that's at the end of this for loop
			self.Printf(" ~> %v", pc).Endl()

			continue
		case JUMPI:
			require(2)
			cond, pos := stack.Popn()
			if cond.Cmp(ethutil.BigTrue) >= 0 {
				pc = pos

				self.Printf(" ~> %v (t)", pc).Endl()

				continue
			} else {
				self.Printf(" (f)")
			}
		case PC:
			stack.Push(pc)
		case MSIZE:
			stack.Push(big.NewInt(int64(mem.Len())))
		case GAS:
			stack.Push(closure.Gas)
			// 0x60 range
		case CREATE:
			require(3)

			var (
				err          error
				value        = stack.Pop()
				size, offset = stack.Popn()

				// Snapshot the current stack so we are able to
				// revert back to it later.
				snapshot = self.env.State().Copy()
			)

			// Generate a new address
			addr := ethcrypto.CreateAddress(closure.Address(), closure.object.Nonce)
			for i := uint64(0); self.env.State().GetStateObject(addr) != nil; i++ {
				ethcrypto.CreateAddress(closure.Address(), closure.object.Nonce+i)
			}
			closure.object.Nonce++

			self.Printf(" (*) %x", addr).Endl()

			msg := self.env.State().Manifest().AddMessage(&ethstate.Message{
				To: addr, From: closure.Address(),
				Origin: self.env.Origin(),
				Block:  self.env.BlockHash(), Timestamp: self.env.Time(), Coinbase: self.env.Coinbase(), Number: self.env.BlockNumber(),
				Value: value,
			})

			// Create a new contract
			contract := self.env.State().NewStateObject(addr)
			if contract.Balance.Cmp(value) >= 0 {
				closure.object.SubAmount(value)
				contract.AddAmount(value)

				// Set the init script
				initCode := mem.Get(offset.Int64(), size.Int64())
				msg.Input = initCode

				// Transfer all remaining gas to the new
				// contract so it may run the init script
				gas := new(big.Int).Set(closure.Gas)
				closure.UseGas(closure.Gas)

				// Create the closure
				c := NewClosure(msg, closure, contract, initCode, gas, closure.Price)
				// Call the closure and set the return value as
				// main script.
				contract.Code, _, err = c.Call(self, nil)
			} else {
				err = fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", value, closure.object.Balance)
			}

			if err != nil {
				stack.Push(ethutil.BigFalse)

				// Revert the state as it was before.
				self.env.State().Set(snapshot)

				self.Printf("CREATE err %v", err)
			} else {
				stack.Push(ethutil.BigD(addr))

				msg.Output = contract.Code
			}
			self.Endl()

			// Debug hook
			if self.Dbg != nil {
				self.Dbg.SetCode(closure.Code)
			}
		case CALL:
			require(7)

			self.Endl()

			gas := stack.Pop()
			// Pop gas and value of the stack.
			value, addr := stack.Popn()
			// Pop input size and offset
			inSize, inOffset := stack.Popn()
			// Pop return size and offset
			retSize, retOffset := stack.Popn()

			// Get the arguments from the memory
			args := mem.Get(inOffset.Int64(), inSize.Int64())

			msg := self.env.State().Manifest().AddMessage(&ethstate.Message{
				To: addr.Bytes(), From: closure.Address(),
				Input:  args,
				Origin: self.env.Origin(),
				Block:  self.env.BlockHash(), Timestamp: self.env.Time(), Coinbase: self.env.Coinbase(), Number: self.env.BlockNumber(),
				Value: value,
			})

			if closure.object.Balance.Cmp(value) < 0 {
				vmlogger.Debugf("Insufficient funds to transfer value. Req %v, has %v", value, closure.object.Balance)

				closure.ReturnGas(gas, nil)

				stack.Push(ethutil.BigFalse)
			} else {
				snapshot := self.env.State().Copy()

				stateObject := self.env.State().GetOrNewStateObject(addr.Bytes())

				closure.object.SubAmount(value)
				stateObject.AddAmount(value)

				// Create a new callable closure
				c := NewClosure(msg, closure, stateObject, stateObject.Code, gas, closure.Price)
				// Executer the closure and get the return value (if any)
				ret, _, err := c.Call(self, args)
				if err != nil {
					stack.Push(ethutil.BigFalse)

					vmlogger.Debugf("Closure execution failed. %v\n", err)

					self.env.State().Set(snapshot)
				} else {
					stack.Push(ethutil.BigTrue)

					mem.Set(retOffset.Int64(), retSize.Int64(), ret)
				}

				msg.Output = ret

				// Debug hook
				if self.Dbg != nil {
					self.Dbg.SetCode(closure.Code)
				}
			}
		case RETURN:
			require(2)
			size, offset := stack.Popn()
			ret := mem.Get(offset.Int64(), size.Int64())

			self.Printf(" => (%d) 0x%x", len(ret), ret).Endl()

			return closure.Return(ret), nil
		case SUICIDE:
			require(1)

			receiver := self.env.State().GetOrNewStateObject(stack.Pop().Bytes())

			receiver.AddAmount(closure.object.Balance)

			closure.object.MarkForDeletion()

			fallthrough
		case STOP: // Stop the closure
			self.Endl()

			return closure.Return(nil), nil
		default:
			vmlogger.Debugf("(pc) %-3v Invalid opcode %x\n", pc, op)

			return closure.Return(nil), fmt.Errorf("Invalid opcode %x", op)
		}

		pc.Add(pc, ethutil.Big1)

		self.Endl()

		if self.Dbg != nil {
			for _, instrNo := range self.Dbg.BreakPoints() {
				if pc.Cmp(big.NewInt(instrNo)) == 0 {
					self.Stepping = true

					if !self.Dbg.BreakHook(prevStep, op, mem, stack, closure.Object()) {
						return nil, nil
					}
				} else if self.Stepping {
					if !self.Dbg.StepHook(prevStep, op, mem, stack, closure.Object()) {
						return nil, nil
					}
				}
			}
		}

	}
}
Exemplo n.º 15
0
// Post-order traversal, equivalent to postfix notation.
func Eval(node interface{}) (*big.Int, error) {
	switch nn := node.(type) {
	case *ast.BinaryExpr:
		z := new(big.Int)
		x, xerr := Eval(nn.X)
		if xerr != nil {
			return nil, xerr
		}
		y, yerr := Eval(nn.Y)
		if yerr != nil {
			return nil, yerr
		}
		switch nn.Op {
		case token.ADD:
			return z.Add(x, y), nil
		case token.SUB:
			return z.Sub(x, y), nil
		case token.MUL:
			return z.Mul(x, y), nil
		case token.QUO:
			if y.Sign() == 0 { // 0 denominator
				return nil, DivideByZero
			}
			return z.Quo(x, y), nil
		case token.REM:
			if y.Sign() == 0 {
				return nil, DivideByZero
			}
			return z.Rem(x, y), nil
		case token.AND:
			return z.And(x, y), nil
		case token.OR:
			return z.Or(x, y), nil
		case token.XOR:
			return z.Xor(x, y), nil
		case token.SHL:
			if y.Sign() < 0 { // negative shift
				return nil, NegativeShift
			}
			return z.Lsh(x, uint(y.Int64())), nil
		case token.SHR:
			if y.Sign() < 0 {
				return nil, NegativeShift
			}
			return z.Rsh(x, uint(y.Int64())), nil
		case token.AND_NOT:
			return z.AndNot(x, y), nil
		default:
			return nil, UnknownOpErr
		}
	case *ast.UnaryExpr:
		var z *big.Int
		var err error
		if z, err = Eval(nn.X); err != nil {
			return nil, err
		}
		switch nn.Op {
		case token.SUB: // -x
			return z.Neg(z), nil
		case token.XOR: // ^x
			return z.Not(z), nil
		case token.ADD: // +x (useless)
			return z, nil
		}
	case *ast.BasicLit:
		z := new(big.Int)
		switch nn.Kind {
		case token.INT:
			z.SetString(nn.Value, 0)
			return z, nil
		default:
			return nil, UnknownLitErr
		}
	case *ast.ParenExpr:
		z, err := Eval(nn.X)
		if err != nil {
			return nil, err
		}
		return z, nil
	case *ast.CallExpr:
		ident, ok := nn.Fun.(*ast.Ident)
		if !ok {
			return nil, UnknownTokenErr // quarter to four am; dunno correct error
		}
		var f Func
		f, ok = FuncMap[ident.Name]
		if !ok {
			return nil, UnknownFuncErr
		}
		var aerr error
		args := make([]*big.Int, len(nn.Args))
		for i, a := range nn.Args {
			if args[i], aerr = Eval(a); aerr != nil {
				return nil, aerr
			}
		}
		x, xerr := f(args...)
		if xerr != nil {
			return nil, xerr
		}
		return x, nil
	}
	return nil, UnknownTokenErr
}
Exemplo n.º 16
0
// GeneratePQ implements [2.2.1.1. Generation of p, q] in page 8
func GeneratePQ(m, L int) (p, q *big.Int) {
	// step 1: Set m' = m/160
	mp := m/160 + 1
	// step 2: Set L' = L/160
	Lp := L/160 + 1
	// step 3: Set N' = L/1024
	Np := L/1024 + 1

	var SEED *big.Int
	for {
		// step 4: Select an arbitrary bit string SEED such that the length of SEED >= m
		SEED = cryptoRandomBigInt(m / 8)
		if SEED == nil {
			continue
		}
		// step 5: Set U = 0
		U := big.NewInt(0)
		// step 6: For i = 0 to m' - 1
		//         U = U + (SHA1[SEED + i] XOR SHA1[SEED + m' + 1]) * 2^(160*i)
		for i := 0; i < mp; i++ {
			Up := new(big.Int)
			xorPart1 := new(big.Int)
			t := new(big.Int)
			t.Add(SEED, big.NewInt(int64(i))) // SEED + i
			sha := sha1.Sum(t.Bytes())
			xorPart1.SetBytes(sha[:]) // SHA1[SEED + i] -> xorPart1
			xorPart2 := new(big.Int)
			t.Add(t, big.NewInt(int64(mp))) // SEED + i + m'
			sha = sha1.Sum(t.Bytes())
			xorPart2.SetBytes(sha[:])  // SHA1[SEED + m' + i] -> xorPart2
			Up.Xor(xorPart1, xorPart2) // XOR
			v := new(big.Int)
			v.Mul(big.NewInt(160), big.NewInt(int64(i)))
			v.Exp(big.NewInt(2), v, nil) // 2^(160*i)
			Up.Mul(Up, v)
			U.Add(U, Up) // U = U + ...
		}
		// step 5: Form q from U mod (2^m), and setting MSB and LSB to 1
		t := big.NewInt(2)
		t.Exp(t, big.NewInt(160), nil)
		U.Mod(U, t)

		q = new(big.Int)
		q.Set(U)
		q.SetBit(q, 0, 1)
		q.SetBit(q, m-1, 1)

		// step 6: test whether q is prime
		if q.ProbablyPrime(100) {
			// step 7: If q is not prime then go to step 4
			break
		}
	}
	// step 8: Let counter = 0
	counter := 0
	for {
		// step 9: Set R = seed + 2*m' + (L' * counter)
		R := new(big.Int)
		R.Set(SEED)
		t := new(big.Int)
		t.Mul(big.NewInt(2), big.NewInt(int64(mp)))
		R.Add(R, t)
		t.Mul(big.NewInt(int64(Lp)), big.NewInt(int64(counter)))
		R.Add(R, t)
		// step 10: Set V = 0
		V := big.NewInt(0)
		// step 12: For i = 0 to L'-1 do V = V + SHA1(R + i) * 2^(160*i)
		for i := 0; i < Lp; i++ {
			sha := new(big.Int)
			sha.Add(R, big.NewInt(int64(i)))
			shaBytes := sha1.Sum(sha.Bytes())
			sha.SetBytes(shaBytes[:])
			second := new(big.Int)
			second.Mul(big.NewInt(160), big.NewInt(int64(i)))
			second.Exp(big.NewInt(2), second, nil)
			sha.Mul(sha, second)
			V.Add(V, sha)
		}
		// step 13: W = V mod 2^L
		W := new(big.Int)
		t.Exp(big.NewInt(2), big.NewInt(int64(L)), nil)
		W.Mod(V, t)
		// step 14: X = W OR 2^(L-1)
		X := new(big.Int)
		X.SetBit(W, L-1, 1)
		// step 15: Set p = X - (X mod (2*q)) + 1
		p = new(big.Int)
		p.Set(X)
		t.Mul(big.NewInt(2), q)
		X.Mod(X, t)
		p.Sub(p, X)
		p.Add(p, big.NewInt(1))
		// step 16: If p > 2^(L-1), test whether p is prime
		t.Exp(big.NewInt(2), big.NewInt(int64(L-1)), nil)
		if p.Cmp(t) == 1 {
			if p.ProbablyPrime(100) {
				// step 17: If p is prime, output p, q, seed, counter and stop
				break
			}
		}
		// step 18: Set counter = counter + 1
		counter++
		// step 19: If counter < (4096 * N) then go to 8
		if counter >= 4096*Np { // !! where is N? !!
			return nil, nil
		}
	}
	return
}