Ejemplo n.º 1
0
// 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
// it could be purely
func (self *Resolver) RegisterUrl(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(),
			UrlHintContractAddress,
			"", txValue, txGas, txGasPrice,
			data,
		)
		if err != nil {
			return
		}
		cnt++
	}
	return
}
Ejemplo n.º 2
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
}
Ejemplo n.º 3
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())

	}
}
Ejemplo n.º 4
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
}
Ejemplo n.º 5
0
func (self *StateDB) Refund(address common.Address, gas *big.Int) {
	addr := address.Str()
	if self.refund[addr] == nil {
		self.refund[addr] = new(big.Int)
	}
	self.refund[addr].Add(self.refund[addr], gas)
}
Ejemplo n.º 6
0
// GetStateObject returns the state object of the given account or nil if the
// account does not exist
func (self *LightState) GetStateObject(ctx context.Context, addr common.Address) (stateObject *StateObject, err error) {
	stateObject = self.stateObjects[addr.Str()]
	if stateObject != nil {
		if stateObject.deleted {
			stateObject = nil
		}
		return stateObject, nil
	}
	data, err := self.trie.Get(ctx, addr[:])
	if err != nil {
		return nil, err
	}
	if len(data) == 0 {
		return nil, nil
	}

	stateObject, err = DecodeObject(ctx, addr, self.odr, []byte(data))
	if err != nil {
		return nil, err
	}

	self.SetStateObject(stateObject)

	return stateObject, nil
}
Ejemplo n.º 7
0
func TestHexdataPtrAddress(t *testing.T) {
	in := common.Address{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
	v := newHexData(&in)
	if bytes.Compare(in.Bytes(), v.data) != 0 {
		t.Errorf("Got % x expected % x", in, v.data)
	}
}
Ejemplo n.º 8
0
func decryptKeyFromFile(keysDirPath string, keyAddr common.Address, auth string) (keyBytes []byte, keyId []byte, err error) {
	fmt.Printf("%v\n", keyAddr.Hex())
	m := make(map[string]interface{})
	err = getKey(keysDirPath, keyAddr, &m)
	if err != nil {
		return
	}

	v := reflect.ValueOf(m["version"])
	if v.Kind() == reflect.String && v.String() == "1" {
		k := new(encryptedKeyJSONV1)
		err = getKey(keysDirPath, keyAddr, &k)
		if err != nil {
			return
		}
		return decryptKeyV1(k, auth)
	} else {
		k := new(encryptedKeyJSONV3)
		err = getKey(keysDirPath, keyAddr, &k)
		if err != nil {
			return
		}
		return decryptKeyV3(k, auth)
	}
}
Ejemplo n.º 9
0
// called as first step in the registration process on HashReg
func (self *Resolver) SetOwner(address common.Address) (txh string, err error) {
	return self.backend.Transact(
		address.Hex(),
		HashRegContractAddress,
		"", txValue, txGas, txGasPrice,
		setOwnerAbi,
	)
}
Ejemplo n.º 10
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,
	)
}
Ejemplo n.º 11
0
// for testing and play temporarily
// ideally the HashReg and UrlHint contracts should be in the genesis block
// if we got build-in support for natspec/contract info
// there should be only one of these officially endorsed
// addresses as constants
// TODO: could get around this with namereg, check
func (self *Resolver) CreateContracts(addr common.Address) (err error) {
	HashRegContractAddress, err = self.backend.Transact(addr.Hex(), "", "", txValue, txGas, txGasPrice, ContractCodeHashReg)
	if err != nil {
		return
	}
	UrlHintContractAddress, err = self.backend.Transact(addr.Hex(), "", "", txValue, txGas, txGasPrice, ContractCodeURLhint)
	glog.V(logger.Detail).Infof("HashReg @ %v\nUrlHint @ %v\n", HashRegContractAddress, UrlHintContractAddress)
	return
}
Ejemplo n.º 12
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)
}
Ejemplo n.º 13
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
}
Ejemplo n.º 14
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,
	)
}
Ejemplo n.º 15
0
// newStateObject creates a state object whether it exists in the state or not
func (self *LightState) newStateObject(addr common.Address) *StateObject {
	if glog.V(logger.Core) {
		glog.Infof("(+) %x\n", addr)
	}

	stateObject := NewStateObject(addr, self.odr)
	stateObject.SetNonce(StartingNonce)
	self.stateObjects[addr.Str()] = stateObject

	return stateObject
}
Ejemplo n.º 16
0
// called as first step in the registration process on HashReg
func (self *Registrar) SetOwner(address common.Address) (txh string, err error) {
	if zero.MatchString(HashRegAddr) {
		return "", fmt.Errorf("HashReg address is not set")
	}
	return self.backend.Transact(
		address.Hex(),
		HashRegAddr,
		"", "", "", "",
		setOwnerAbi,
	)
}
Ejemplo n.º 17
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,
	)
}
Ejemplo n.º 18
0
// PendingAccountNonce implements ContractTransactor.PendingAccountNonce, delegating
// the current account nonce retrieval to the remote node.
func (b *rpcBackend) PendingAccountNonce(account common.Address) (uint64, error) {
	res, err := b.request("eth_getTransactionCount", []interface{}{account.Hex(), "pending"})
	if err != nil {
		return 0, err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return 0, err
	}
	nonce, ok := new(big.Int).SetString(hex, 0)
	if !ok {
		return 0, fmt.Errorf("invalid nonce hex: %s", hex)
	}
	return nonce.Uint64(), nil
}
Ejemplo n.º 19
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
}
Ejemplo n.º 20
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
}
Ejemplo n.º 21
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
// kept
func (self *Resolver) RegisterContentHash(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
	return self.backend.Transact(
		address.Hex(),
		HashRegContractAddress,
		"", txValue, txGas, txGasPrice,
		data,
	)
}
Ejemplo n.º 22
0
func (self *XEth) sign(tx *types.Transaction, from common.Address, didUnlock bool) error {
	sig, err := self.backend.AccountManager().Sign(accounts.Account{Address: from.Bytes()}, tx.Hash().Bytes())
	if err == accounts.ErrLocked {
		if didUnlock {
			return fmt.Errorf("sender account still locked after successful unlock")
		}
		if !self.frontend.UnlockAccount(from.Bytes()) {
			return fmt.Errorf("could not unlock sender account")
		}
		// retry signing, the account should now be unlocked.
		return self.sign(tx, from, true)
	} else if err != nil {
		return err
	}
	tx.SetSignatureValues(sig)
	return nil
}
Ejemplo n.º 23
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,
	)
}
Ejemplo n.º 24
0
// HasCode implements ContractVerifier.HasCode by retrieving any code associated
// with the contract from the remote node, and checking its size.
func (b *rpcBackend) HasCode(contract common.Address, pending bool) (bool, error) {
	// Execute the RPC code retrieval
	block := "latest"
	if pending {
		block = "pending"
	}
	res, err := b.request("eth_getCode", []interface{}{contract.Hex(), block})
	if err != nil {
		return false, err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return false, err
	}
	// Convert the response back to a Go byte slice and return
	return len(common.FromHex(hex)) > 0, nil
}
Ejemplo n.º 25
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]
}
Ejemplo n.º 26
0
// Retrieve a state object given my the address. Nil if not found
func (self *StateDB) GetStateObject(addr common.Address) *StateObject {
	//addr = common.Address(addr)

	stateObject := self.stateObjects[addr.Str()]
	if 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
}
Ejemplo n.º 27
0
func (self *Registrar) SetGlobalRegistrar(namereg string, addr common.Address) (txhash string, err error) {
	if namereg != "" {
		GlobalRegistrarAddr = namereg
		return
	}
	if zero.MatchString(GlobalRegistrarAddr) {
		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
}
Ejemplo n.º 28
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
}
Ejemplo n.º 29
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, err := DecodeObject(addr, self.db, data)
	if err != nil {
		glog.Errorf("can't decode object at %x: %v", addr[:], err)
		return nil
	}
	self.SetStateObject(stateObject)
	return stateObject
}
Ejemplo n.º 30
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) {
	if zero.MatchString(UrlHintAddr) {
		return "", fmt.Errorf("UrlHint address is not set")
	}

	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
}