Example #1
0
func (self *Registrar) SetUrlHint(urlhint string, addr common.Address) (txhash string, err error) {
	if urlhint != "" {
		UrlHintAddr = urlhint
	} else {
		if !zero.MatchString(UrlHintAddr) {
			return
		}
		nameHex, extra := encodeName(UrlHintName, 2)
		urlHintAbi := resolveAbi + nameHex + extra
		glog.V(logger.Detail).Infof("UrlHint address query data: %s to %s", urlHintAbi, GlobalRegistrarAddr)
		var res string
		res, _, err = self.backend.Call("", GlobalRegistrarAddr, "", "", "", urlHintAbi)
		if len(res) >= 40 {
			UrlHintAddr = "0x" + res[len(res)-40:len(res)]
		}
		if err != nil || zero.MatchString(UrlHintAddr) {
			if (addr == common.Address{}) {
				err = fmt.Errorf("UrlHint address not found and sender for creation not given")
				return
			}
			txhash, err = self.backend.Transact(addr.Hex(), "", "", "", "210000", "", UrlHintCode)
			if err != nil {
				err = fmt.Errorf("UrlHint address not found and sender for creation failed: %v", err)
			}
			glog.V(logger.Detail).Infof("created UrlHint @ txhash %v\n", txhash)
		} else {
			glog.V(logger.Detail).Infof("UrlHint found @ %v\n", HashRegAddr)
			return
		}
	}

	return
}
Example #2
0
// SetUrlToHash(from, hash, url) registers a url to a content hash so that the content can be fetched
// address is used as sender for the transaction and will be the owner of a new
// registry entry on first time use
// FIXME: silently doing nothing if sender is not the owner
// note that with content addressed storage, this step is no longer necessary
func (self *Registrar) SetUrlToHash(address common.Address, hash common.Hash, url string) (txh string, err error) {
	hashHex := common.Bytes2Hex(hash[:])
	var urlHex string
	urlb := []byte(url)
	var cnt byte
	n := len(urlb)

	for n > 0 {
		if n > 32 {
			n = 32
		}
		urlHex = common.Bytes2Hex(urlb[:n])
		urlb = urlb[n:]
		n = len(urlb)
		bcnt := make([]byte, 32)
		bcnt[31] = cnt
		data := registerUrlAbi +
			hashHex +
			common.Bytes2Hex(bcnt) +
			common.Bytes2Hex(common.Hex2BytesFixed(urlHex, 32))
		txh, err = self.backend.Transact(
			address.Hex(),
			UrlHintAddr,
			"", "", "", "",
			data,
		)
		if err != nil {
			return
		}
		cnt++
	}
	return
}
Example #3
0
func (self *Registrar) SetHashReg(hashreg string, addr common.Address) (txhash string, err error) {
	if hashreg != "" {
		HashRegAddr = hashreg
	} else {
		if !zero.MatchString(HashRegAddr) {
			return
		}
		nameHex, extra := encodeName(HashRegName, 2)
		hashRegAbi := resolveAbi + nameHex + extra
		glog.V(logger.Detail).Infof("\ncall HashRegAddr %v with %v\n", GlobalRegistrarAddr, hashRegAbi)
		var res string
		res, _, err = self.backend.Call("", GlobalRegistrarAddr, "", "", "", hashRegAbi)
		if len(res) >= 40 {
			HashRegAddr = "0x" + res[len(res)-40:len(res)]
		}
		if err != nil || zero.MatchString(HashRegAddr) {
			if (addr == common.Address{}) {
				err = fmt.Errorf("HashReg address not found and sender for creation not given")
				return
			}

			txhash, err = self.backend.Transact(addr.Hex(), "", "", "", "", "", HashRegCode)
			if err != nil {
				err = fmt.Errorf("HashReg address not found and sender for creation failed: %v", err)
			}
			glog.V(logger.Detail).Infof("created HashRegAddr @ txhash %v\n", txhash)
		} else {
			glog.V(logger.Detail).Infof("HashRegAddr found at @ %v\n", HashRegAddr)
			return
		}
	}

	return
}
Example #4
0
func opCreate(instr instruction, env Environment, context *Context, memory *Memory, stack *stack) {
	var (
		value        = stack.pop()
		offset, size = stack.pop(), stack.pop()
		input        = memory.Get(offset.Int64(), size.Int64())
		gas          = new(big.Int).Set(context.Gas)
		addr         common.Address
	)

	context.UseGas(context.Gas)
	ret, suberr, ref := env.Create(context, input, gas, context.Price, value)
	if suberr != nil {
		stack.push(new(big.Int))

	} else {
		// gas < len(ret) * Createinstr.dataGas == 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())

	}
}
Example #5
0
// called as first step in the registration process on HashReg
func (self *Registrar) SetOwner(address common.Address) (txh string, err error) {
	return self.backend.Transact(
		address.Hex(),
		HashRegAddr,
		"", "", "", "",
		setOwnerAbi,
	)
}
Example #6
0
// SetNonce sets the new canonical nonce for the managed state
func (ms *ManagedState) SetNonce(addr common.Address, nonce uint64) {
	ms.mu.Lock()
	defer ms.mu.Unlock()

	so := ms.GetOrNewStateObject(addr)
	so.SetNonce(nonce)

	ms.accounts[addr.Str()] = newAccount(so)
}
Example #7
0
// NewStateObject create a state object whether it exist in the trie or not
func (self *StateDB) newStateObject(addr common.Address) *StateObject {
	if glog.V(logger.Core) {
		glog.Infof("(+) %x\n", addr)
	}

	stateObject := NewStateObject(addr, self.db)
	self.stateObjects[addr.Str()] = stateObject

	return stateObject
}
Example #8
0
// ReserveName(from, name) reserves name for the sender address in the globalRegistrar
// the tx needs to be mined to take effect
func (self *Registrar) ReserveName(address common.Address, name string) (txh string, err error) {
	nameHex, extra := encodeName(name, 2)
	abi := reserveAbi + nameHex + extra
	glog.V(logger.Detail).Infof("Reserve data: %s", abi)
	return self.backend.Transact(
		address.Hex(),
		GlobalRegistrarAddr,
		"", "", "", "",
		abi,
	)
}
Example #9
0
// SetAddressToName(from, name, addr) will set the Address to address for name
// in the globalRegistrar using from as the sender of the transaction
// the tx needs to be mined to take effect
func (self *Registrar) SetAddressToName(from common.Address, name string, address common.Address) (txh string, err error) {
	nameHex, extra := encodeName(name, 6)
	addrHex := encodeAddress(address)

	abi := registerAbi + nameHex + addrHex + trueHex + extra
	glog.V(logger.Detail).Infof("SetAddressToName data: %s to %s ", abi, GlobalRegistrarAddr)

	return self.backend.Transact(
		from.Hex(),
		GlobalRegistrarAddr,
		"", "", "", "",
		abi,
	)
}
Example #10
0
// NameToAddr(from, name) queries the registrar for the address on name
func (self *Registrar) NameToAddr(from common.Address, name string) (address common.Address, err error) {
	nameHex, extra := encodeName(name, 2)
	abi := resolveAbi + nameHex + extra
	glog.V(logger.Detail).Infof("NameToAddr data: %s", abi)
	res, _, err := self.backend.Call(
		from.Hex(),
		GlobalRegistrarAddr,
		"", "", "",
		abi,
	)
	if err != nil {
		return
	}
	address = common.HexToAddress(res)
	return
}
Example #11
0
func (self *XEth) doSign(from common.Address, hash common.Hash, didUnlock bool) ([]byte, error) {
	sig, err := self.backend.AccountManager().Sign(accounts.Account{Address: from}, hash.Bytes())
	if err == accounts.ErrLocked {
		if didUnlock {
			return nil, fmt.Errorf("signer account still locked after successful unlock")
		}
		if !self.frontend.UnlockAccount(from.Bytes()) {
			return nil, fmt.Errorf("could not unlock signer account")
		}
		// retry signing, the account should now be unlocked.
		return self.doSign(from, hash, true)
	} else if err != nil {
		return nil, err
	}
	return sig, nil
}
Example #12
0
// registers some content hash to a key/code hash
// e.g., the contract Info combined Json Doc's ContentHash
// to CodeHash of a contract or hash of a domain
func (self *Registrar) SetHashToHash(address common.Address, codehash, dochash common.Hash) (txh string, err error) {
	_, err = self.SetOwner(address)
	if err != nil {
		return
	}
	codehex := common.Bytes2Hex(codehash[:])
	dochex := common.Bytes2Hex(dochash[:])

	data := registerContentHashAbi + codehex + dochex
	glog.V(logger.Detail).Infof("SetHashToHash data: %s sent  to %v\n", data, HashRegAddr)
	return self.backend.Transact(
		address.Hex(),
		HashRegAddr,
		"", "", "", "",
		data,
	)
}
Example #13
0
// populate the managed state
func (ms *ManagedState) getAccount(addr common.Address) *account {
	straddr := addr.Str()
	if account, ok := ms.accounts[straddr]; !ok {
		so := ms.GetOrNewStateObject(addr)
		ms.accounts[straddr] = newAccount(so)
	} else {
		// Always make sure the state account nonce isn't actually higher
		// than the tracked one.
		so := ms.StateDB.GetStateObject(addr)
		if so != nil && uint64(len(account.nonces))+account.nstart < so.nonce {
			ms.accounts[straddr] = newAccount(so)
		}

	}

	return ms.accounts[straddr]
}
Example #14
0
func (self *Registrar) SetGlobalRegistrar(namereg string, addr common.Address) (txhash string, err error) {
	if namereg != "" {
		GlobalRegistrarAddr = namereg
		return
	}
	if GlobalRegistrarAddr == "0x0" || GlobalRegistrarAddr == "0x" {
		if (addr == common.Address{}) {
			err = fmt.Errorf("GlobalRegistrar address not found and sender for creation not given")
			return
		} else {
			txhash, err = self.backend.Transact(addr.Hex(), "", "", "", "800000", "", GlobalRegistrarCode)
			if err != nil {
				err = fmt.Errorf("GlobalRegistrar address not found and sender for creation failed: %v", err)
				return
			}
		}
	}
	return
}
Example #15
0
// Retrieve a state object given my the address. Nil if not found
func (self *StateDB) GetStateObject(addr common.Address) (stateObject *StateObject) {
	stateObject = self.stateObjects[addr.Str()]
	if stateObject != nil {
		if stateObject.deleted {
			stateObject = nil
		}

		return stateObject
	}

	data := self.trie.Get(addr[:])
	if len(data) == 0 {
		return nil
	}

	stateObject = NewStateObjectFromBytes(addr, []byte(data), self.db)
	self.SetStateObject(stateObject)

	return stateObject
}
Example #16
0
func (ms *ManagedState) hasAccount(addr common.Address) bool {
	_, ok := ms.accounts[addr.Str()]
	return ok
}
Example #17
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++

	}
}
Example #18
0
func encodeAddress(address common.Address) string {
	return addressAbiPrefix + address.Hex()[2:]
}