// executeDial calls the dialFunc, and reports the result through the response
// channel when finished. Once the response is sent it also releases all tokens
// it held during the dial.
430892
func (dl *dialLimiter) executeDial(j *dialJob) {
	defer dl.finishedDial(j)
	if j.cancelled() {
		return
	}

	dctx, cancel := context.WithTimeout(j.ctx, j.dialTimeout())
	defer cancel()

	con, err := dl.dialFunc(dctx, j.peer, j.addr)
	select {
	case j.resp <- dialResult{Conn: con, Addr: j.addr, Err: err}:
	case <-j.ctx.Done():
		if err == nil {
			con.Close()
		}
	}
}
1246370
func (vm *VM) execute(callState Interface, eventSink EventSink, caller, callee crypto.Address,
	code, input []byte, value uint64, gas *uint64) (returnData []byte) {
	vm.Debugf("(%d) (%s) %s (code=%d) gas: %v (d) %X\n", vm.stackDepth, caller, callee, len(code), *gas, input)

	logger := vm.logger.With("evm_nonce", vm.nonce)

	if vm.dumpTokens {
		dumpTokens(vm.nonce, caller, callee, code)
	}

	// Program counter - the index into code that tracks current instruction
	pc := int64(0)
	// Provide stack and memory storage - passing in the callState as an error provider
	stack := NewStack(vm.params.DataStackInitialCapacity, vm.params.DataStackMaxDepth, gas, callState)
	memory := vm.memoryProvider(callState)

	for {
		// Check for any error accrued to state
		if callState.Error() != nil {
			return
		}

		var op = codeGetOp(code, pc)
		vm.Debugf("(pc) %-3d (op) %-14s (st) %-4d (gas) %d", pc, op.String(), stack.Len(), *gas)
		// Use BaseOp gas.
		useGasNegative(gas, GasBaseOp, callState)

		switch op {

		case ADD: // 0x01
			x, y := stack.PopBigInt(), stack.PopBigInt()
			sum := new(big.Int).Add(x, y)
			res := stack.PushBigInt(sum)
			vm.Debugf(" %v + %v = %v (%X)\n", x, y, sum, res)

		case MUL: // 0x02
			x, y := stack.PopBigInt(), stack.PopBigInt()
			prod := new(big.Int).Mul(x, y)
			res := stack.PushBigInt(prod)
			vm.Debugf(" %v * %v = %v (%X)\n", x, y, prod, res)

		case SUB: // 0x03
			x, y := stack.PopBigInt(), stack.PopBigInt()
			diff := new(big.Int).Sub(x, y)
			res := stack.PushBigInt(diff)
			vm.Debugf(" %v - %v = %v (%X)\n", x, y, diff, res)

		case DIV: // 0x04
			x, y := stack.PopBigInt(), stack.PopBigInt()
			if y.Sign() == 0 {
				stack.Push(Zero256)
				vm.Debugf(" %x / %x = %v\n", x, y, 0)
			} else {
				div := new(big.Int).Div(x, y)
				res := stack.PushBigInt(div)
				vm.Debugf(" %v / %v = %v (%X)\n", x, y, div, res)
			}

		case SDIV: // 0x05
			x, y := stack.PopBigIntSigned(), stack.PopBigIntSigned()
			if y.Sign() == 0 {
				stack.Push(Zero256)
				vm.Debugf(" %x / %x = %v\n", x, y, 0)
			} else {
				div := new(big.Int).Div(x, y)
				res := stack.PushBigInt(div)
				vm.Debugf(" %v / %v = %v (%X)\n", x, y, div, res)
			}

		case MOD: // 0x06
			x, y := stack.PopBigInt(), stack.PopBigInt()
			if y.Sign() == 0 {
				stack.Push(Zero256)
				vm.Debugf(" %v %% %v = %v\n", x, y, 0)
			} else {
				mod := new(big.Int).Mod(x, y)
				res := stack.PushBigInt(mod)
				vm.Debugf(" %v %% %v = %v (%X)\n", x, y, mod, res)
			}

		case SMOD: // 0x07
			x, y := stack.PopBigIntSigned(), stack.PopBigIntSigned()
			if y.Sign() == 0 {
				stack.Push(Zero256)
				vm.Debugf(" %v %% %v = %v\n", x, y, 0)
			} else {
				mod := new(big.Int).Mod(x, y)
				res := stack.PushBigInt(mod)
				vm.Debugf(" %v %% %v = %v (%X)\n", x, y, mod, res)
			}

		case ADDMOD: // 0x08
			x, y, z := stack.PopBigInt(), stack.PopBigInt(), stack.PopBigInt()
			if z.Sign() == 0 {
				stack.Push(Zero256)
				vm.Debugf(" %v %% %v = %v\n", x, y, 0)
			} else {
				add := new(big.Int).Add(x, y)
				mod := add.Mod(add, z)
				res := stack.PushBigInt(mod)
				vm.Debugf(" %v + %v %% %v = %v (%X)\n", x, y, z, mod, res)
			}

		case MULMOD: // 0x09
			x, y, z := stack.PopBigInt(), stack.PopBigInt(), stack.PopBigInt()
			if z.Sign() == 0 {
				stack.Push(Zero256)
				vm.Debugf(" %v %% %v = %v\n", x, y, 0)
			} else {
				mul := new(big.Int).Mul(x, y)
				mod := mul.Mod(mul, z)
				res := stack.PushBigInt(mod)
				vm.Debugf(" %v * %v %% %v = %v (%X)\n", x, y, z, mod, res)
			}

		case EXP: // 0x0A
			x, y := stack.PopBigInt(), stack.PopBigInt()
			pow := new(big.Int).Exp(x, y, nil)
			res := stack.PushBigInt(pow)
			vm.Debugf(" %v ** %v = %v (%X)\n", x, y, pow, res)

		case SIGNEXTEND: // 0x0B
			back := stack.PopU64()
			if back < Word256Length-1 {
				stack.PushBigInt(SignExtend(back, stack.PopBigInt()))
			}

		case LT: // 0x10
			x, y := stack.PopBigInt(), stack.PopBigInt()
			if x.Cmp(y) < 0 {
				stack.Push(One256)
				vm.Debugf(" %v < %v = %v\n", x, y, 1)
			} else {
				stack.Push(Zero256)
				vm.Debugf(" %v < %v = %v\n", x, y, 0)
			}

		case GT: // 0x11
			x, y := stack.PopBigInt(), stack.PopBigInt()
			if x.Cmp(y) > 0 {
				stack.Push(One256)
				vm.Debugf(" %v > %v = %v\n", x, y, 1)
			} else {
				stack.Push(Zero256)
				vm.Debugf(" %v > %v = %v\n", x, y, 0)
			}

		case SLT: // 0x12
			x, y := stack.PopBigIntSigned(), stack.PopBigIntSigned()
			if x.Cmp(y) < 0 {
				stack.Push(One256)
				vm.Debugf(" %v < %v = %v\n", x, y, 1)
			} else {
				stack.Push(Zero256)
				vm.Debugf(" %v < %v = %v\n", x, y, 0)
			}

		case SGT: // 0x13
			x, y := stack.PopBigIntSigned(), stack.PopBigIntSigned()
			if x.Cmp(y) > 0 {
				stack.Push(One256)
				vm.Debugf(" %v > %v = %v\n", x, y, 1)
			} else {
				stack.Push(Zero256)
				vm.Debugf(" %v > %v = %v\n", x, y, 0)
			}

		case EQ: // 0x14
			x, y := stack.Pop(), stack.Pop()
			if bytes.Equal(x[:], y[:]) {
				stack.Push(One256)
				vm.Debugf(" %X == %X = %v\n", x, y, 1)
			} else {
				stack.Push(Zero256)
				vm.Debugf(" %X == %X = %v\n", x, y, 0)
			}

		case ISZERO: // 0x15
			x := stack.Pop()
			if x.IsZero() {
				stack.Push(One256)
				vm.Debugf(" %X == 0 = %v\n", x, 1)
			} else {
				stack.Push(Zero256)
				vm.Debugf(" %X == 0 = %v\n", x, 0)
			}

		case AND: // 0x16
			x, y := stack.Pop(), stack.Pop()
			z := [32]byte{}
			for i := 0; i < 32; i++ {
				z[i] = x[i] & y[i]
			}
			stack.Push(z)
			vm.Debugf(" %X & %X = %X\n", x, y, z)

		case OR: // 0x17
			x, y := stack.Pop(), stack.Pop()
			z := [32]byte{}
			for i := 0; i < 32; i++ {
				z[i] = x[i] | y[i]
			}
			stack.Push(z)
			vm.Debugf(" %X | %X = %X\n", x, y, z)

		case XOR: // 0x18
			x, y := stack.Pop(), stack.Pop()
			z := [32]byte{}
			for i := 0; i < 32; i++ {
				z[i] = x[i] ^ y[i]
			}
			stack.Push(z)
			vm.Debugf(" %X ^ %X = %X\n", x, y, z)

		case NOT: // 0x19
			x := stack.Pop()
			z := [32]byte{}
			for i := 0; i < 32; i++ {
				z[i] = ^x[i]
			}
			stack.Push(z)
			vm.Debugf(" !%X = %X\n", x, z)

		case BYTE: // 0x1A
			idx := stack.Pop64()
			val := stack.Pop()
			res := byte(0)
			if idx < 32 {
				res = val[idx]
			}
			stack.Push64(int64(res))
			vm.Debugf(" => 0x%X\n", res)

		case SHL: //0x1B
			shift, x := stack.PopBigInt(), stack.PopBigInt()

			if shift.Cmp(Big256) >= 0 {
				reset := big.NewInt(0)
				stack.PushBigInt(reset)
				vm.Debugf(" %v << %v = %v\n", x, shift, reset)
			} else {
				shiftedValue := x.Lsh(x, uint(shift.Uint64()))
				stack.PushBigInt(shiftedValue)
				vm.Debugf(" %v << %v = %v\n", x, shift, shiftedValue)
			}

		case SHR: //0x1C
			shift, x := stack.PopBigInt(), stack.PopBigInt()

			if shift.Cmp(Big256) >= 0 {
				reset := big.NewInt(0)
				stack.PushBigInt(reset)
				vm.Debugf(" %v << %v = %v\n", x, shift, reset)
			} else {
				shiftedValue := x.Rsh(x, uint(shift.Uint64()))
				stack.PushBigInt(shiftedValue)
				vm.Debugf(" %v << %v = %v\n", x, shift, shiftedValue)
			}

		case SAR: //0x1D
			shift, x := stack.PopBigInt(), stack.PopBigIntSigned()

			if shift.Cmp(Big256) >= 0 {
				reset := big.NewInt(0)
				if x.Sign() < 0 {
					reset.SetInt64(-1)
				}
				stack.PushBigInt(reset)
				vm.Debugf(" %v << %v = %v\n", x, shift, reset)
			} else {
				shiftedValue := x.Rsh(x, uint(shift.Uint64()))
				stack.PushBigInt(shiftedValue)
				vm.Debugf(" %v << %v = %v\n", x, shift, shiftedValue)
			}

		case SHA3: // 0x20
			useGasNegative(gas, GasSha3, callState)
			offset, size := stack.PopBigInt(), stack.PopBigInt()
			data := memory.Read(offset, size)
			data = sha3.Sha3(data)
			stack.PushBytes(data)
			vm.Debugf(" => (%v) %X\n", size, data)

		case ADDRESS: // 0x30
			stack.Push(callee.Word256())
			vm.Debugf(" => %X\n", callee)

		case BALANCE: // 0x31
			address := stack.PopAddress()
			useGasNegative(gas, GasGetAccount, callState)
			balance := callState.GetBalance(address)
			stack.PushU64(balance)
			vm.Debugf(" => %v (%X)\n", balance, address)

		case ORIGIN: // 0x32
			stack.Push(vm.origin.Word256())
			vm.Debugf(" => %X\n", vm.origin)

		case CALLER: // 0x33
			stack.Push(caller.Word256())
			vm.Debugf(" => %X\n", caller)

		case CALLVALUE: // 0x34
			stack.PushU64(value)
			vm.Debugf(" => %v\n", value)

		case CALLDATALOAD: // 0x35
			offset := stack.Pop64()
			data := subslice(input, offset, 32, callState)
			res := LeftPadWord256(data)
			stack.Push(res)
			vm.Debugf(" => 0x%X\n", res)

		case CALLDATASIZE: // 0x36
			stack.Push64(int64(len(input)))
			vm.Debugf(" => %d\n", len(input))

		case CALLDATACOPY: // 0x37
			memOff := stack.PopBigInt()
			inputOff := stack.Pop64()
			length := stack.Pop64()
			data := subslice(input, inputOff, length, callState)
			memory.Write(memOff, data)
			vm.Debugf(" => [%v, %v, %v] %X\n", memOff, inputOff, length, data)

		case CODESIZE: // 0x38
			l := int64(len(code))
			stack.Push64(l)
			vm.Debugf(" => %d\n", l)

		case CODECOPY: // 0x39
			memOff := stack.PopBigInt()
			codeOff := stack.Pop64()
			length := stack.Pop64()
			data := subslice(code, codeOff, length, callState)
			memory.Write(memOff, data)
			vm.Debugf(" => [%v, %v, %v] %X\n", memOff, codeOff, length, data)

		case GASPRICE_DEPRECATED: // 0x3A
			stack.Push(Zero256)
			vm.Debugf(" => %X (GASPRICE IS DEPRECATED)\n", Zero256)

		case EXTCODESIZE: // 0x3B
			address := stack.PopAddress()
			useGasNegative(gas, GasGetAccount, callState)
			if callState.Exists(address) {
				code := callState.GetCode(address)
				l := int64(len(code))
				stack.Push64(l)
				vm.Debugf(" => %d\n", l)
			} else {
				if _, ok := registeredNativeContracts[address]; !ok {
					callState.PushError(errors.ErrorCodeUnknownAddress)
					continue
				}
				vm.Debugf(" => returning code size of 1 to indicated existence of native contract at %X\n", address)
				stack.Push(One256)
			}
		case EXTCODECOPY: // 0x3C
			address := stack.PopAddress()
			useGasNegative(gas, GasGetAccount, callState)
			if !callState.Exists(address) {
				if _, ok := registeredNativeContracts[address]; ok {
					vm.Debugf(" => attempted to copy native contract at %v but this is not supported\n", address)
					callState.PushError(errors.ErrorCodeNativeContractCodeCopy)
				}
				callState.PushError(errors.ErrorCodeUnknownAddress)
				continue
			}
			code := callState.GetCode(address)
			memOff := stack.PopBigInt()
			codeOff := stack.Pop64()
			length := stack.Pop64()
			data := subslice(code, codeOff, length, callState)
			memory.Write(memOff, data)
			vm.Debugf(" => [%v, %v, %v] %X\n", memOff, codeOff, length, data)

		case RETURNDATASIZE: // 0x3D
			stack.Push64(int64(len(returnData)))
			vm.Debugf(" => %d\n", len(returnData))

		case RETURNDATACOPY: // 0x3E
			memOff, outputOff, length := stack.PopBigInt(), stack.PopBigInt(), stack.PopBigInt()
			end := new(big.Int).Add(outputOff, length)

			if end.BitLen() > 64 || uint64(len(returnData)) < end.Uint64() {
				callState.PushError(errors.ErrorCodeReturnDataOutOfBounds)
				continue
			}

			memory.Write(memOff, returnData)
			vm.Debugf(" => [%v, %v, %v] %X\n", memOff, outputOff, length, returnData)

		case EXTCODEHASH: // 0x3F
			address := stack.PopAddress()

			if !callState.Exists(address) {
				// In case the account does not exist 0 is pushed to the stack.
				stack.PushU64(0)
			} else {
				code := callState.GetCode(address)
				if code == nil {
					// In case the account does not have code the keccak256 hash of empty data
					code = acm.Bytecode{}
				}

				// keccak256 hash of a contract's code
				var extcodehash Word256
				hash := sha3.NewKeccak256()
				hash.Write(code)
				copy(extcodehash[:], hash.Sum(nil))

				stack.Push(extcodehash)
			}

		case BLOCKHASH: // 0x40
			blockNumber := stack.PopU64()

			if blockNumber >= vm.params.BlockHeight {
				vm.Debugf(" => attempted to get block hash of a non-existent block: %v", blockNumber)
				callState.PushError(errors.ErrorCodeInvalidBlockNumber)
			} else if vm.params.BlockHeight-blockNumber > MaximumAllowedBlockLookBack {
				vm.Debugf(" => attempted to get block hash of a block %d outside of the allowed range "+
					"(must be within %d blocks)", blockNumber, MaximumAllowedBlockLookBack)
				callState.PushError(errors.ErrorCodeBlockNumberOutOfRange)
			} else {
				blockHash, err := callState.GetBlockHash(blockNumber)
				if err != nil {
					vm.Debugf(" => error attempted to get block hash: %v, %v", blockNumber, err)
					callState.PushError(errors.ErrorCodeInvalidBlockNumber)
				} else {
					stack.Push(blockHash)
					vm.Debugf(" => 0x%X\n", blockHash)
				}
			}

		case COINBASE: // 0x41
			stack.Push(Zero256)
			vm.Debugf(" => 0x%X (NOT SUPPORTED)\n", stack.Peek().Bytes())

		case TIMESTAMP: // 0x42
			time := vm.params.BlockTime
			stack.Push64(int64(time))
			vm.Debugf(" => 0x%X\n", time)

		case BLOCKHEIGHT: // 0x43
			number := vm.params.BlockHeight
			stack.PushU64(number)
			vm.Debugf(" => 0x%X\n", number)

		case GASLIMIT: // 0x45
			stack.PushU64(vm.params.GasLimit)
			vm.Debugf(" => %v\n", vm.params.GasLimit)

		case POP: // 0x50
			popped := stack.Pop()
			vm.Debugf(" => 0x%X\n", popped)

		case MLOAD: // 0x51
			offset := stack.PopBigInt()
			data := memory.Read(offset, BigWord256Length)
			stack.Push(LeftPadWord256(data))
			vm.Debugf(" => 0x%X @ 0x%X\n", data, offset)

		case MSTORE: // 0x52
			offset, data := stack.PopBigInt(), stack.Pop()
			memory.Write(offset, data.Bytes())
			vm.Debugf(" => 0x%X @ 0x%X\n", data, offset)

		case MSTORE8: // 0x53
			offset := stack.PopBigInt()
			val64 := stack.Pop64()
			val := byte(val64 & 0xFF)
			memory.Write(offset, []byte{val})
			vm.Debugf(" => [%v] 0x%X\n", offset, val)

		case SLOAD: // 0x54
			loc := stack.Pop()
			data := callState.GetStorage(callee, loc)
			stack.Push(data)
			vm.Debugf("%s {0x%X = 0x%X}\n", callee, loc, data)

		case SSTORE: // 0x55
			loc, data := stack.Pop(), stack.Pop()
			useGasNegative(gas, GasStorageUpdate, callState)
			callState.SetStorage(callee, loc, data)
			vm.Debugf("%s {0x%X := 0x%X}\n", callee, loc, data)

		case JUMP: // 0x56
			to := stack.Pop64()
			vm.jump(code, to, &pc, callState)
			continue

		case JUMPI: // 0x57
			pos := stack.Pop64()
			cond := stack.Pop()
			if !cond.IsZero() {
				vm.jump(code, pos, &pc, callState)
				continue
			}
			vm.Debugf(" ~> false\n")

		case PC: // 0x58
			stack.Push64(pc)

		case MSIZE: // 0x59
			// Note: Solidity will write to this offset expecting to find guaranteed
			// free memory to be allocated for it if a subsequent MSTORE is made to
			// this offset.
			capacity := memory.Capacity()
			stack.PushBigInt(capacity)
			vm.Debugf(" => 0x%X\n", capacity)

		case GAS: // 0x5A
			stack.PushU64(*gas)
			vm.Debugf(" => %X\n", *gas)

		case JUMPDEST: // 0x5B
			vm.Debugf("\n")
			// Do nothing

		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 := int64(op - PUSH1 + 1)
			codeSegment := subslice(code, pc+1, a, callState)
			res := LeftPadWord256(codeSegment)
			stack.Push(res)
			pc += a
			vm.Debugf(" => 0x%X\n", res)

		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)
			vm.Debugf(" => [%d] 0x%X\n", 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)
			vm.Debugf(" => [%d] %X\n", n, stack.Peek())

		case LOG0, LOG1, LOG2, LOG3, LOG4:
			n := int(op - LOG0)
			topics := make([]Word256, n)
			offset, size := stack.PopBigInt(), stack.PopBigInt()
			for i := 0; i < n; i++ {
				topics[i] = stack.Pop()
			}
			data := memory.Read(offset, size)
			callState.PushError(eventSink.Log(&exec.LogEvent{
				Address: callee,
				Topics:  topics,
				Data:    data,
			}))
			vm.Debugf(" => T:%X D:%X\n", topics, data)

		case CREATE, CREATE2: // 0xF0, 0xFB
			returnData = nil
			contractValue := stack.PopU64()
			offset, size := stack.PopBigInt(), stack.PopBigInt()
			input := memory.Read(offset, size)

			// TODO charge for gas to create account _ the code length * GasCreateByte
			useGasNegative(gas, GasCreateAccount, callState)

			var newAccount crypto.Address
			if op == CREATE {
				vm.sequence++
				nonce := make([]byte, txs.HashLength+uint64Length)
				copy(nonce, vm.nonce)
				PutUint64BE(nonce[txs.HashLength:], vm.sequence)
				newAccount = crypto.NewContractAddress(callee, nonce)
			} else if op == CREATE2 {
				salt := stack.Pop()
				newAccount = crypto.NewContractAddress2(callee, salt, callState.GetCode(callee))
			}

			// Check the CreateContract permission for this account
			EnsurePermission(callState, callee, permission.CreateContract)
			if callState.Error() != nil {
				continue
			}

			// Establish a frame in which the putative account exists
			childCallState := callState.NewCache()
			create(childCallState, newAccount)

			// Run the input to get the contract code.
			// NOTE: no need to copy 'input' as per Call contract.
			ret, callErr := vm.Call(childCallState, eventSink, callee, newAccount, input, input, contractValue, gas)
			if callErr != nil {
				stack.Push(Zero256)
				// Note we both set the return buffer and return the result normally
				returnData = ret
			} else {
				// Update the account with its initialised contract code
				childCallState.InitCode(newAccount, ret)
				callState.PushError(childCallState.Sync())
				stack.PushAddress(newAccount)
			}

		case CALL, CALLCODE, DELEGATECALL, STATICCALL: // 0xF1, 0xF2, 0xF4, 0xFA
			returnData = nil

			EnsurePermission(callState, callee, permission.Call)
			if callState.Error() != nil {
				continue
			}
			gasLimit := stack.PopU64()
			address := stack.PopAddress()
			// NOTE: for DELEGATECALL value is preserved from the original
			// caller, as such it is not stored on stack as an argument
			// for DELEGATECALL and should not be popped.  Instead previous
			// caller value is used.  for CALL and CALLCODE value is stored
			// on stack and needs to be overwritten from the given value.
			if op != DELEGATECALL && op != STATICCALL {
				value = stack.PopU64()
			}
			// inputs
			inOffset, inSize := stack.PopBigInt(), stack.PopBigInt()
			// outputs
			retOffset := stack.PopBigInt()
			retSize := stack.Pop64()
			vm.Debugf(" => %v\n", address)

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

			// Ensure that gasLimit is reasonable
			if *gas < gasLimit {
				// EIP150 - the 63/64 rule - rather than errors.CodedError we pass this specified fraction of the total available gas
				gasLimit = *gas - *gas/64
			}
			// NOTE: we will return any used gas later.
			*gas -= gasLimit

			// Begin execution
			var callErr errors.CodedError
			// Establish a stack frame and perform the call
			var childCallState Interface
			if IsRegisteredNativeContract(address) {
				// Native contract
				childCallState = callState.NewCache()
				returnData, callErr = ExecuteNativeContract(address, childCallState, callee, args, &gasLimit, logger)
				childCallState.PushError(callErr)
				// for now we fire the Call event. maybe later we'll fire more particulars
				// NOTE: these fire call go_events and not particular go_events for eg name reg or permissions
				vm.fireCallEvent(eventSink, exec.CallTypeSNative, childCallState, &returnData, callee, address, args, value,
					&gasLimit, childCallState)
			} else {
				// EVM contract
				useGasNegative(gas, GasGetAccount, callState)
				// since CALL is used also for sending funds,
				// acc may not exist yet. This is an errors.CodedError for
				// CALLCODE, but not for CALL, though I don't think
				// ethereum actually cares
				if !callState.Exists(address) {
					if op != CALL {
						callState.PushError(errors.ErrorCodeUnknownAddress)
						continue
					}
					// We're sending funds to a new account so we must create it first
					createAccount(callState, callee, address)
					if callState.Error() != nil {
						continue
					}
				}
				switch op {
				case CALL:
					childCallState = callState.NewCache()
					returnData, callErr = vm.call(childCallState, eventSink, callee, address, callState.GetCode(address),
						args, value, &gasLimit, exec.CallTypeCall)

				case CALLCODE:
					childCallState = callState.NewCache()
					returnData, callErr = vm.call(childCallState, eventSink, callee, callee, callState.GetCode(address),
						args, value, &gasLimit, exec.CallTypeCode)

				case DELEGATECALL:
					childCallState = callState.NewCache()
					returnData, callErr = vm.delegateCall(childCallState, eventSink, caller, callee,
						callState.GetCode(address), args, value, &gasLimit, exec.CallTypeDelegate)

				case STATICCALL:
					childCallState = callState.NewCache(acmstate.ReadOnly)
					returnData, callErr = vm.delegateCall(childCallState, NewLogFreeEventSink(eventSink),
						callee, address, callState.GetCode(address), args, value, &gasLimit, exec.CallTypeStatic)

				default:
					panic(fmt.Errorf("switch statement should be exhaustive so this should not have been reached"))
				}

			}

			if callErr == nil {
				// Sync error is a hard stop
				callState.PushError(childCallState.Sync())
			}

			// Push result
			if callErr != nil {
				vm.Debugf("error from nested sub-call (depth: %v): %s\n", vm.stackDepth, callErr.Error())
				// So we can return nested errors.CodedError if the top level return is an errors.CodedError
				stack.Push(Zero256)

				if callErr.ErrorCode() == errors.ErrorCodeExecutionReverted {
					memory.Write(retOffset, RightPadBytes(returnData, int(retSize)))
				}
			} else {
				stack.Push(One256)

				// Should probably only be necessary when there is no return value and
				// returnData is empty, but since EVM expects retSize to be respected this will
				// defensively pad or truncate the portion of returnData to be returned.
				memory.Write(retOffset, RightPadBytes(returnData, int(retSize)))
			}

			// Handle remaining gas.
			*gas += gasLimit

			vm.Debugf("resume %s (%v)\n", callee, gas)

		case RETURN: // 0xF3
			offset, size := stack.PopBigInt(), stack.PopBigInt()
			output := memory.Read(offset, size)
			vm.Debugf(" => [%v, %v] (%d) 0x%X\n", offset, size, len(output), output)
			return output

		case REVERT: // 0xFD
			offset, size := stack.PopBigInt(), stack.PopBigInt()
			output := memory.Read(offset, size)
			vm.Debugf(" => [%v, %v] (%d) 0x%X\n", offset, size, len(output), output)
			callState.PushError(newRevertException(output))
			return output

		case INVALID: // 0xFE
			callState.PushError(errors.ErrorCodeExecutionAborted)
			return nil

		case SELFDESTRUCT: // 0xFF
			receiver := stack.PopAddress()
			useGasNegative(gas, GasGetAccount, callState)
			if !callState.Exists(receiver) {
				// If receiver address doesn't exist, try to create it
				useGasNegative(gas, GasCreateAccount, callState)
				createAccount(callState, callee, receiver)
				if callState.Error() != nil {
					continue
				}
			}
			balance := callState.GetBalance(callee)
			callState.AddToBalance(receiver, balance)
			callState.RemoveAccount(callee)
			vm.Debugf(" => (%X) %v\n", receiver[:4], balance)
			return nil

		case STOP: // 0x00
			return nil

		default:
			vm.Debugf("(pc) %-3v Unknown opcode %v\n", pc, op)
			callState.PushError(errors.Errorf("unknown opcode %v", op))
			return nil
		}
		pc++
	}
	return
}
1031916
func (vf *VindexFunc) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
	return vf.mapVindex(vcursor, bindVars)
}
1207694
func (dialer *PredicateDialer) Dial(address string, verifyFunc RemoteVerifier) (*grpc.ClientConn, error) {
	cfg := dialer.Config.Load().(comm.ClientConfig)
	cfg.SecOpts.VerifyCertificate = verifyFunc
	client, err := comm.NewGRPCClient(cfg)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	return client.NewConnection(address, "")
}
1261196
func redial(ctx context.Context, url string) chan chan session {
	sessions := make(chan chan session)

	go func() {
		sess := make(chan session)
		defer close(sessions)

		for {
			select {
			case sessions <- sess:
			case <-ctx.Done():
				log.Println("shutting down session factory")
				return
			}

			conn, err := amqp.Dial(url)
			if err != nil {
				log.Fatalf("cannot (re)dial: %v: %q", err, url)
			}

			ch, err := conn.Channel()
			if err != nil {
				log.Fatalf("cannot create channel: %v", err)
			}

			if err := ch.ExchangeDeclare(exchange, "fanout", false, true, false, false, nil); err != nil {
				log.Fatalf("cannot declare fanout exchange: %v", err)
			}

			select {
			case sess <- session{conn, ch}:
			case <-ctx.Done():
				log.Println("shutting down new session")
				return
			}
		}
	}()

	return sessions
}
755584
func NewExecutionFinished(result *JsonResult) *Execution {
	return &Execution{
		Data: &Execution_Data{
			ExecutionType: &Execution_Data_Finished_{
				&Execution_Data_Finished{Data: result}}}}
}
1198552
func (j *JSONPath) Execute(wr io.Writer, data interface{}) error {
	fullResults, err := j.FindResults(data)
	if err != nil {
		return err
	}
	for ix := range fullResults {
		if err := j.PrintResults(wr, fullResults[ix]); err != nil {
			return err
		}
	}
	return nil
}
1024543
func (t *explainTablet) ExecuteBatch(ctx context.Context, target *querypb.Target, queries []*querypb.BoundQuery, asTransaction bool, transactionID int64, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) {
	t.mu.Lock()
	t.currentTime = batchTime.Wait()

	// Since the query is simulated being "sent" over the wire we need to
	// copy the bindVars into the executor to avoid a data race.
	for _, query := range queries {
		query.BindVariables = sqltypes.CopyBindVariables(query.BindVariables)
		t.tabletQueries = append(t.tabletQueries, &TabletQuery{
			Time:     t.currentTime,
			SQL:      query.Sql,
			BindVars: query.BindVariables,
		})
	}
	t.mu.Unlock()

	return t.tsv.ExecuteBatch(ctx, target, queries, asTransaction, transactionID, options)
}
125779
func (a *Agent) executeDirective(directive AttachmentDirective) {
	defer a.wg.Done()

	// We'll start out by attempting to connect to the peer in order to
	// begin the funding workflow.
	nodeID := directive.NodeID
	pub, err := btcec.ParsePubKey(nodeID[:], btcec.S256())
	if err != nil {
		log.Errorf("Unable to parse pubkey %x: %v", nodeID, err)
		return
	}

	connected := make(chan bool)
	errChan := make(chan error)

	// To ensure a call to ConnectToPeer doesn't block the agent from
	// shutting down, we'll launch it in a non-waitgrouped goroutine, that
	// will signal when a result is returned.
	// TODO(halseth): use DialContext to cancel on transport level.
	go func() {
		alreadyConnected, err := a.cfg.ConnectToPeer(
			pub, directive.Addrs,
		)
		if err != nil {
			select {
			case errChan <- err:
			case <-a.quit:
			}
			return
		}

		select {
		case connected <- alreadyConnected:
		case <-a.quit:
			return
		}
	}()

	var alreadyConnected bool
	select {
	case alreadyConnected = <-connected:
	case err = <-errChan:
	case <-a.quit:
		return
	}

	if err != nil {
		log.Warnf("Unable to connect to %x: %v",
			pub.SerializeCompressed(), err)

		// Since we failed to connect to them, we'll mark them as
		// failed so that we don't attempt to connect to them again.
		a.pendingMtx.Lock()
		delete(a.pendingConns, nodeID)
		a.failedNodes[nodeID] = struct{}{}
		a.pendingMtx.Unlock()

		// Finally, we'll trigger the agent to select new peers to
		// connect to.
		a.OnChannelOpenFailure()

		return
	}

	// The connection was successful, though before progressing we must
	// check that we have not already met our quota for max pending open
	// channels. This can happen if multiple directives were spawned but
	// fewer slots were available, and other successful attempts finished
	// first.
	a.pendingMtx.Lock()
	if uint16(len(a.pendingOpens)) >= a.cfg.Constraints.MaxPendingOpens() {
		// Since we've reached our max number of pending opens, we'll
		// disconnect this peer and exit. However, if we were
		// previously connected to them, then we'll make sure to
		// maintain the connection alive.
		if alreadyConnected {
			// Since we succeeded in connecting, we won't add this
			// peer to the failed nodes map, but we will remove it
			// from a.pendingConns so that it can be retried in the
			// future.
			delete(a.pendingConns, nodeID)
			a.pendingMtx.Unlock()
			return
		}

		err = a.cfg.DisconnectPeer(pub)
		if err != nil {
			log.Warnf("Unable to disconnect peer %x: %v",
				pub.SerializeCompressed(), err)
		}

		// Now that we have disconnected, we can remove this node from
		// our pending conns map, permitting subsequent connection
		// attempts.
		delete(a.pendingConns, nodeID)
		a.pendingMtx.Unlock()
		return
	}

	// If we were successful, we'll track this peer in our set of pending
	// opens. We do this here to ensure we don't stall on selecting new
	// peers if the connection attempt happens to take too long.
	delete(a.pendingConns, nodeID)
	a.pendingOpens[nodeID] = Channel{
		Capacity: directive.ChanAmt,
		Node:     nodeID,
	}
	a.pendingMtx.Unlock()

	// We can then begin the funding workflow with this peer.
	err = a.cfg.ChanController.OpenChannel(pub, directive.ChanAmt)
	if err != nil {
		log.Warnf("Unable to open channel to %x of %v: %v",
			pub.SerializeCompressed(), directive.ChanAmt, err)

		// As the attempt failed, we'll clear the peer from the set of
		// pending opens and mark them as failed so we don't attempt to
		// open a channel to them again.
		a.pendingMtx.Lock()
		delete(a.pendingOpens, nodeID)
		a.failedNodes[nodeID] = struct{}{}
		a.pendingMtx.Unlock()

		// Trigger the agent to re-evaluate everything and possibly
		// retry with a different node.
		a.OnChannelOpenFailure()

		// Finally, we should also disconnect the peer if we weren't
		// already connected to them beforehand by an external
		// subsystem.
		if alreadyConnected {
			return
		}

		err = a.cfg.DisconnectPeer(pub)
		if err != nil {
			log.Warnf("Unable to disconnect peer %x: %v",
				pub.SerializeCompressed(), err)
		}
	}

	// Since the channel open was successful and is currently pending,
	// we'll trigger the autopilot agent to query for more peers.
	// TODO(halseth): this triggers a new loop before all the new channels
	// are added to the pending channels map. Should add before executing
	// directive in goroutine?
	a.OnChannelPendingOpen()
}
1268227
func (p *PolicyAuthorizer) executeCodePolicy(policy *Sentinel, scope sentinel.ScopeFn) bool {
	if p.sentinel == nil {
		return true
	}

	if policy.Code == "" || scope == nil {
		return true
	}

	enforcement := policy.EnforcementLevel
	if enforcement == "" {
		enforcement = DefaultPolicyEnforcementLevel
	}

	return p.sentinel.Execute(policy.Code, enforcement, scope())
}
774347
func (q *query) Execute(ctx context.Context, request *querypb.ExecuteRequest) (response *querypb.ExecuteResponse, err error) {
	defer q.server.HandlePanic(&err)
	ctx = callerid.NewContext(callinfo.GRPCCallInfo(ctx),
		request.EffectiveCallerId,
		request.ImmediateCallerId,
	)
	result, err := q.server.Execute(ctx, request.Target, request.Query.Sql, request.Query.BindVariables, request.TransactionId, request.Options)
	if err != nil {
		return nil, vterrors.ToGRPC(err)
	}
	return &querypb.ExecuteResponse{
		Result: sqltypes.ResultToProto3(result),
	}, nil
}
489689
func (vc *vcursorImpl) Execute(method string, query string, BindVars map[string]*querypb.BindVariable, isDML bool) (*sqltypes.Result, error) {
	qr, err := vc.executor.Execute(vc.ctx, method, vc.safeSession, vc.marginComments.Leading+query+vc.marginComments.Trailing, BindVars)
	if err == nil {
		vc.hasPartialDML = true
	}
	return qr, err
}
718477
func (c *Client) ExecuteWrite(flags uint8) error {

	// Acquire and reuse the txBuf, and release it after usage.
	txBuf := <-c.chTxBuf
	defer func() { c.chTxBuf <- txBuf }()

	req := ExecuteWriteRequest(txBuf[:1])
	req.SetAttributeOpcode()
	req.SetFlags(flags)

	b, err := c.sendReq(req)
	if err != nil {
		return err
	}

	// Convert and validate the response.
	rsp := ExecuteWriteResponse(b)
	switch {
	case rsp[0] == ErrorResponseCode && len(rsp) == 5:
		return ble.ATTError(rsp[4])
	case rsp[0] == ErrorResponseCode && len(rsp) == 5:
		fallthrough
	case rsp[0] != rsp.AttributeOpcode():
		return ErrInvalidResponse
	}
	return nil
}
49601
func (e *executor) Execute(ctx context.Context, index string, q *pql.Query, shards []uint64, opt *execOptions) (QueryResponse, error) {
	span, ctx := tracing.StartSpanFromContext(ctx, "Executor.Execute")
	defer span.Finish()

	resp := QueryResponse{}

	// Check for query cancellation.
	if err := validateQueryContext(ctx); err != nil {
		return resp, err
	}

	// Verify that an index is set.
	if index == "" {
		return resp, ErrIndexRequired
	}

	idx := e.Holder.Index(index)
	if idx == nil {
		return resp, ErrIndexNotFound
	}

	// Verify that the number of writes do not exceed the maximum.
	if e.MaxWritesPerRequest > 0 && q.WriteCallN() > e.MaxWritesPerRequest {
		return resp, ErrTooManyWrites
	}

	// Default options.
	if opt == nil {
		opt = &execOptions{}
	}

	// Translate query keys to ids, if necessary.
	// No need to translate a remote call.
	if !opt.Remote {
		if err := e.translateCalls(ctx, index, idx, q.Calls); err != nil {
			return resp, err
		} else if err := validateQueryContext(ctx); err != nil {
			return resp, err
		}
	}

	results, err := e.execute(ctx, index, q, shards, opt)
	if err != nil {
		return resp, err
	} else if err := validateQueryContext(ctx); err != nil {
		return resp, err
	}

	resp.Results = results

	// Fill column attributes if requested.
	if opt.ColumnAttrs {
		// Consolidate all column ids across all calls.
		var columnIDs []uint64
		for _, result := range results {
			bm, ok := result.(*Row)
			if !ok {
				continue
			}
			columnIDs = uint64Slice(columnIDs).merge(bm.Columns())
		}

		// Retrieve column attributes across all calls.
		columnAttrSets, err := e.readColumnAttrSets(e.Holder.Index(index), columnIDs)
		if err != nil {
			return resp, errors.Wrap(err, "reading column attrs")
		}

		// Translate column attributes, if necessary.
		if idx.Keys() {
			for _, col := range columnAttrSets {
				v, err := e.Holder.translateFile.TranslateColumnToString(index, col.ID)
				if err != nil {
					return resp, err
				}
				col.Key, col.ID = v, 0
			}
		}

		resp.ColumnAttrSets = columnAttrSets
	}

	// Translate response objects from ids to keys, if necessary.
	// No need to translate a remote call.
	if !opt.Remote {
		if err := e.translateResults(ctx, index, idx, q.Calls, results); err != nil {
			return resp, err
		} else if err := validateQueryContext(ctx); err != nil {
			return resp, err
		}
	}

	return resp, nil
}
765519
func (m *Internal) executeKeyringOp(
	args *structs.KeyringRequest,
	reply *structs.KeyringResponses,
	wan bool) {

	if wan {
		mgr := m.srv.KeyManagerWAN()
		m.executeKeyringOpMgr(mgr, args, reply, wan, "")
	} else {
		segments := m.srv.LANSegments()
		for name, segment := range segments {
			mgr := segment.KeyManager()
			m.executeKeyringOpMgr(mgr, args, reply, wan, name)
		}
	}
}
940278
func DefaultDial(connectionTimeout time.Duration) func(network, addr string) (net.Conn, error) {
	return func(network, addr string) (net.Conn, error) {
		conn, err := net.DialTimeout(network, addr, connectionTimeout)
		if err != nil {
			return nil, err
		}

		// Heartbeating hasn't started yet, don't stall forever on a dead server.
		// A deadline is set for TLS and AMQP handshaking. After AMQP is established,
		// the deadline is cleared in openComplete.
		if err := conn.SetDeadline(time.Now().Add(connectionTimeout)); err != nil {
			return nil, err
		}

		return conn, nil
	}
}
602901
func (e *ClientExecutor) Execute(b *imagebuilder.Builder, node *parser.Node) error {
	for i, child := range node.Children {
		step := b.Step()
		if err := step.Resolve(child); err != nil {
			return err
		}
		glog.V(4).Infof("step: %s", step.Original)
		if e.LogFn != nil {
			// original may have unescaped %, so perform fmt escaping
			e.LogFn(strings.Replace(step.Original, "%", "%%", -1))
		}
		noRunsRemaining := !b.RequiresStart(&parser.Node{Children: node.Children[i+1:]})

		if err := b.Run(step, e, noRunsRemaining); err != nil {
			return err
		}
	}

	return nil
}