Example #1
0
func NewReciept(contractCreation bool, creationAddress, hash, address []byte) *Receipt {
	return &Receipt{
		contractCreation,
		common.ToHex(creationAddress),
		common.ToHex(hash),
		common.ToHex(address),
	}
}
Example #2
0
func (self *Object) Storage() (storage map[string]string) {
	storage = make(map[string]string)

	it := self.StateObject.Trie().Iterator()
	for it.Next() {
		var data []byte
		rlp.Decode(bytes.NewReader(it.Value), &data)
		storage[common.ToHex(self.Trie().GetKey(it.Key))] = common.ToHex(data)
	}

	return
}
// NewWhisperMessage converts an internal message into an API version.
func NewWhisperMessage(message *whisper.Message) WhisperMessage {
	return WhisperMessage{
		ref: message,

		Payload: common.ToHex(message.Payload),
		From:    common.ToHex(crypto.FromECDSAPub(message.Recover())),
		To:      common.ToHex(crypto.FromECDSAPub(message.To)),
		Sent:    message.Sent.Unix(),
		TTL:     int64(message.TTL / time.Second),
		Hash:    common.ToHex(message.Hash.Bytes()),
	}
}
Example #4
0
func (self *XEth) EachStorage(addr string) string {
	var values []KeyVal
	object := self.State().SafeGet(addr)
	it := object.Trie().Iterator()
	for it.Next() {
		values = append(values, KeyVal{common.ToHex(object.Trie().GetKey(it.Key)), common.ToHex(it.Value)})
	}

	valuesJson, err := json.Marshal(values)
	if err != nil {
		return ""
	}

	return string(valuesJson)
}
Example #5
0
func NewTx(tx *types.Transaction) *Transaction {
	sender, err := tx.From()
	if err != nil {
		return nil
	}
	hash := tx.Hash().Hex()

	var receiver string
	if to := tx.To(); to != nil {
		receiver = to.Hex()
	} else {
		from, _ := tx.From()
		receiver = crypto.CreateAddress(from, tx.Nonce()).Hex()
	}
	createsContract := core.MessageCreatesContract(tx)

	var data string
	if createsContract {
		data = strings.Join(core.Disassemble(tx.Data()), "\n")
	} else {
		data = common.ToHex(tx.Data())
	}

	return &Transaction{ref: tx, Hash: hash, Value: common.CurrencyToString(tx.Value()), Address: receiver, Contract: createsContract, Gas: tx.Gas().String(), GasPrice: tx.GasPrice().String(), Data: data, Sender: sender.Hex(), CreatesContract: createsContract, RawData: common.ToHex(tx.Data())}
}
Example #6
0
// EstimateGasLimit implements ContractTransactor.EstimateGasLimit, delegating
// the gas estimation to the remote node.
func (b *rpcBackend) EstimateGasLimit(sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
	// Pack up the request into an RPC argument
	args := struct {
		From  common.Address  `json:"from"`
		To    *common.Address `json:"to"`
		Value *rpc.HexNumber  `json:"value"`
		Data  string          `json:"data"`
	}{
		From:  sender,
		To:    contract,
		Data:  common.ToHex(data),
		Value: rpc.NewHexNumber(value),
	}
	// Execute the RPC call and retrieve the response
	res, err := b.request("eth_estimateGas", []interface{}{args})
	if err != nil {
		return nil, err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return nil, err
	}
	estimate, ok := new(big.Int).SetString(hex, 0)
	if !ok {
		return nil, fmt.Errorf("invalid estimate hex: %s", hex)
	}
	return estimate, nil
}
Example #7
0
// ContractCall implements ContractCaller.ContractCall, delegating the execution of
// a contract call to the remote node, returning the reply to for local processing.
func (b *rpcBackend) ContractCall(contract common.Address, data []byte, pending bool) ([]byte, error) {
	// Pack up the request into an RPC argument
	args := struct {
		To   common.Address `json:"to"`
		Data string         `json:"data"`
	}{
		To:   contract,
		Data: common.ToHex(data),
	}
	// Execute the RPC call and retrieve the response
	block := "latest"
	if pending {
		block = "pending"
	}
	res, err := b.request("eth_call", []interface{}{args, block})
	if err != nil {
		return nil, err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return nil, err
	}
	// Convert the response back to a Go byte slice and return
	return common.FromHex(hex), nil
}
Example #8
0
// Creates a new QML Block from a chain block
func NewBlock(block *types.Block) *Block {
	if block == nil {
		return &Block{}
	}

	ptxs := make([]*Transaction, len(block.Transactions()))
	/*
		for i, tx := range block.Transactions() {
			ptxs[i] = NewTx(tx)
		}
	*/
	txlist := common.NewList(ptxs)

	puncles := make([]*Block, len(block.Uncles()))
	/*
		for i, uncle := range block.Uncles() {
			puncles[i] = NewBlock(types.NewBlockWithHeader(uncle))
		}
	*/
	ulist := common.NewList(puncles)

	return &Block{
		ref: block, Size: block.Size().String(),
		Number: int(block.NumberU64()), GasUsed: block.GasUsed().String(),
		GasLimit: block.GasLimit().String(), Hash: block.Hash().Hex(),
		Transactions: txlist, Uncles: ulist,
		Time:     block.Time(),
		Coinbase: block.Coinbase().Hex(),
		PrevHash: block.ParentHash().Hex(),
		Bloom:    common.ToHex(block.Bloom().Bytes()),
		Raw:      block.String(),
	}
}
Example #9
0
func getWorkPackage(difficulty *big.Int) string {

	if currWork == nil {
		return getErrorResponse("Current work unavailable")
	}

	// Our response object
	response := &ResponseArray{
		Id:      currWork.Id,
		Jsonrpc: currWork.Jsonrpc,
		Result:  currWork.Result[:],
	}

	// Calculte requested difficulty
	diff := new(big.Int).Div(pow256, difficulty)
	diffBytes := string(common.ToHex(diff.Bytes()))

	// Adjust the difficulty for the miner
	response.Result[2] = diffBytes

	// Convert respone object to JSON
	b, _ := json.Marshal(response)

	return string(b)

}
Example #10
0
func startEth(ctx *cli.Context, eth *eth.Ethereum) {
	// Start Ethereum itself
	utils.StartEthereum(eth)
	am := eth.AccountManager()

	account := ctx.GlobalString(utils.UnlockedAccountFlag.Name)
	if len(account) > 0 {
		if account == "primary" {
			accbytes, err := am.Primary()
			if err != nil {
				utils.Fatalf("no primary account: %v", err)
			}
			account = common.ToHex(accbytes)
		}
		unlockAccount(ctx, am, account)
	}
	// Start auxiliary services if enabled.
	if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
		if err := utils.StartRPC(eth, ctx); err != nil {
			utils.Fatalf("Error starting RPC: %v", err)
		}
	}
	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
		if err := eth.StartMining(); err != nil {
			utils.Fatalf("%v", err)
		}
	}
}
Example #11
0
func (self *XEth) SecretToAddress(key string) string {
	pair, err := crypto.NewKeyPairFromSec(common.FromHex(key))
	if err != nil {
		return ""
	}

	return common.ToHex(pair.Address())
}
Example #12
0
// Calculates the sha3 over req.Params.Data
func (self *web3Api) Sha3(req *shared.Request) (interface{}, error) {
	args := new(Sha3Args)
	if err := self.codec.Decode(req.Params, &args); err != nil {
		return nil, err
	}

	return common.ToHex(crypto.Sha3(common.FromHex(args.Data))), nil
}
Example #13
0
// NewIdentity generates a new cryptographic identity for the client, and injects
// it into the known identities for message decryption.
func (s *PublicWhisperAPI) NewIdentity() (string, error) {
	if s.w == nil {
		return "", whisperOffLineErr
	}

	identity := s.w.NewIdentity()
	return common.ToHex(crypto.FromECDSAPub(&identity.PublicKey)), nil
}
Example #14
0
func (self *testBackend) initUrlHint() {
	self.contracts[UrlHintAddr[2:]] = make(map[string]string)
	mapaddr := storageMapping(storageIdx2Addr(1), hash[:])

	key := storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(0)))
	self.contracts[UrlHintAddr[2:]][key] = common.ToHex([]byte(url))
	key = storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(1)))
	self.contracts[UrlHintAddr[2:]][key] = "0x0"
}
Example #15
0
// EstimateGasLimit implements bind.ContractTransactor triing to estimate the gas
// needed to execute a specific transaction based on the current pending state of
// the backend blockchain. There is no guarantee that this is the true gas limit
// requirement as other transactions may be added or removed by miners, but it
// should provide a basis for setting a reasonable default.
func (b *ContractBackend) EstimateGasLimit(sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
	out, err := b.bcapi.EstimateGas(CallArgs{
		From:  sender,
		To:    contract,
		Value: *rpc.NewHexNumber(value),
		Data:  common.ToHex(data),
	})
	return out.BigInt(), err
}
Example #16
0
func (self *XEth) Accounts() []string {
	// TODO: check err?
	accounts, _ := self.backend.AccountManager().Accounts()
	accountAddresses := make([]string, len(accounts))
	for i, ac := range accounts {
		accountAddresses[i] = common.ToHex(ac.Address)
	}
	return accountAddresses
}
Example #17
0
func (self *XEth) Sign(fromStr, hashStr string, didUnlock bool) (string, error) {
	var (
		from = common.HexToAddress(fromStr)
		hash = common.HexToHash(hashStr)
	)
	sig, err := self.doSign(from, hash, didUnlock)
	if err != nil {
		return "", err
	}
	return common.ToHex(sig), nil
}
Example #18
0
func (self *XEth) GetTxReceipt(txhash common.Hash) (receipt *types.Receipt, err error) {
	_, bhash, _, txi := self.EthTransactionByHash(common.ToHex(txhash[:]))
	var receipts types.Receipts
	receipts, err = self.backend.BlockProcessor().GetBlockReceipts(bhash)
	if err == nil {
		if txi < uint64(len(receipts)) {
			receipt = receipts[txi]
		} else {
			err = fmt.Errorf("Invalid tx index")
		}
	}
	return
}
Example #19
0
// ContractCall implements bind.ContractCaller executing an Ethereum contract
// call with the specified data as the input. The pending flag requests execution
// against the pending block, not the stable head of the chain.
func (b *ContractBackend) ContractCall(contract common.Address, data []byte, pending bool) ([]byte, error) {
	// Convert the input args to the API spec
	args := CallArgs{
		To:   &contract,
		Data: common.ToHex(data),
	}
	block := rpc.LatestBlockNumber
	if pending {
		block = rpc.PendingBlockNumber
	}
	// Execute the call and convert the output back to Go types
	out, err := b.bcapi.Call(args, block)
	return common.FromHex(out), err
}
Example #20
0
// SendTransaction implements ContractTransactor.SendTransaction, delegating the
// raw transaction injection to the remote node.
func (b *rpcBackend) SendTransaction(tx *types.Transaction) error {
	data, err := rlp.EncodeToBytes(tx)
	if err != nil {
		return err
	}
	res, err := b.request("eth_sendRawTransaction", []interface{}{common.ToHex(data)})
	if err != nil {
		return err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return err
	}
	return nil
}
Example #21
0
// Call forms a transaction from the given arguments and tries to execute it on
// a private VM with a copy of the state. Any changes are therefore only temporary
// and not part of the actual state. This allows for local execution/queries.
func (be *registryAPIBackend) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, string, error) {
	block := be.bc.CurrentBlock()
	statedb, err := state.New(block.Root(), be.chainDb)
	if err != nil {
		return "", "", err
	}

	var from *state.StateObject
	if len(fromStr) == 0 {
		accounts, err := be.am.Accounts()
		if err != nil || len(accounts) == 0 {
			from = statedb.GetOrNewStateObject(common.Address{})
		} else {
			from = statedb.GetOrNewStateObject(accounts[0].Address)
		}
	} else {
		from = statedb.GetOrNewStateObject(common.HexToAddress(fromStr))
	}

	from.SetBalance(common.MaxBig)

	msg := callmsg{
		from:     from,
		gas:      common.Big(gasStr),
		gasPrice: common.Big(gasPriceStr),
		value:    common.Big(valueStr),
		data:     common.FromHex(dataStr),
	}
	if len(toStr) > 0 {
		addr := common.HexToAddress(toStr)
		msg.to = &addr
	}

	if msg.gas.Cmp(big.NewInt(0)) == 0 {
		msg.gas = big.NewInt(50000000)
	}

	if msg.gasPrice.Cmp(big.NewInt(0)) == 0 {
		msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
	}

	header := be.bc.CurrentBlock().Header()
	vmenv := core.NewEnv(statedb, be.bc, msg, header)
	gp := new(core.GasPool).AddGas(common.MaxBig)
	res, gas, err := core.ApplyMessage(vmenv, msg, gp)

	return common.ToHex(res), gas.String(), err
}
Example #22
0
func (s *ProxyServer) handleGetWorkRPC(cs *Session, diff, id string) (reply []string, errorReply *ErrorReply) {
	t := s.currentBlockTemplate()
	minerDifficulty, err := strconv.ParseFloat(diff, 64)
	if err != nil {
		log.Printf("Invalid difficulty %v from %v@%v ", diff, id, cs.ip)
		minerDifficulty = 5
	}
	if len(t.Header) == 0 {
		return nil, &ErrorReply{Code: -1, Message: "Work not ready"}
	}
	minerAdjustedDifficulty := int64(minerDifficulty * 1000000 * 100)
	difficulty := big.NewInt(minerAdjustedDifficulty)
	diff1 := new(big.Int).Div(pow256, difficulty)
	diffBytes := string(common.ToHex(diff1.Bytes()))

	reply = []string{t.Header, t.Seed, diffBytes}
	return
}
Example #23
0
func NewTestBackend() *testBackend {
	self := &testBackend{}
	self.contracts = make(map[string](map[string]string))

	self.contracts[HashRegContractAddress] = make(map[string]string)
	key := storageAddress(storageMapping(storageIdx2Addr(1), codehash[:]))
	self.contracts[HashRegContractAddress][key] = hash.Hex()

	self.contracts[URLHintContractAddress] = make(map[string]string)
	mapaddr := storageMapping(storageIdx2Addr(1), hash[:])

	key = storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(0)))
	self.contracts[URLHintContractAddress][key] = common.ToHex([]byte(url))
	key = storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(1)))
	self.contracts[URLHintContractAddress][key] = "0x00"

	return self
}
Example #24
0
func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, string, error) {
	statedb := self.State().State().Copy()
	var from *state.StateObject
	if len(fromStr) == 0 {
		accounts, err := self.backend.AccountManager().Accounts()
		if err != nil || len(accounts) == 0 {
			from = statedb.GetOrNewStateObject(common.Address{})
		} else {
			from = statedb.GetOrNewStateObject(accounts[0].Address)
		}
	} else {
		from = statedb.GetOrNewStateObject(common.HexToAddress(fromStr))
	}

	from.SetBalance(common.MaxBig)
	from.SetGasLimit(common.MaxBig)

	msg := callmsg{
		from:     from,
		gas:      common.Big(gasStr),
		gasPrice: common.Big(gasPriceStr),
		value:    common.Big(valueStr),
		data:     common.FromHex(dataStr),
	}
	if len(toStr) > 0 {
		addr := common.HexToAddress(toStr)
		msg.to = &addr
	}

	if msg.gas.Cmp(big.NewInt(0)) == 0 {
		msg.gas = big.NewInt(50000000)
	}

	if msg.gasPrice.Cmp(big.NewInt(0)) == 0 {
		msg.gasPrice = self.DefaultGasPrice()
	}

	header := self.CurrentBlock().Header()
	vmenv := core.NewEnv(statedb, self.backend.ChainManager(), msg, header)

	res, gas, err := core.ApplyMessage(vmenv, msg, from)
	return common.ToHex(res), gas.String(), err
}
Example #25
0
func NewTestBackend() *testBackend {
	HashRegAddr = common.BigToAddress(common.Big0).Hex() //[2:]
	UrlHintAddr = common.BigToAddress(common.Big1).Hex() //[2:]
	self := &testBackend{}
	self.contracts = make(map[string](map[string]string))

	self.contracts[HashRegAddr[2:]] = make(map[string]string)
	key := storageAddress(storageMapping(storageIdx2Addr(1), codehash[:]))
	self.contracts[HashRegAddr[2:]][key] = hash.Hex()

	self.contracts[UrlHintAddr[2:]] = make(map[string]string)
	mapaddr := storageMapping(storageIdx2Addr(1), hash[:])

	key = storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(0)))
	self.contracts[UrlHintAddr[2:]][key] = common.ToHex([]byte(url))
	key = storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(1)))
	self.contracts[UrlHintAddr[2:]][key] = "0x0"
	return self
}
Example #26
0
func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, string, error) {
	statedb := self.State().State() //self.eth.ChainManager().TransState()
	var from *state.StateObject
	if len(fromStr) == 0 {
		accounts, err := self.backend.AccountManager().Accounts()
		if err != nil || len(accounts) == 0 {
			from = statedb.GetOrNewStateObject(common.Address{})
		} else {
			from = statedb.GetOrNewStateObject(common.BytesToAddress(accounts[0].Address))
		}
	} else {
		from = statedb.GetOrNewStateObject(common.HexToAddress(fromStr))
	}

	from.SetGasPool(self.backend.ChainManager().GasLimit())
	msg := callmsg{
		from:     from,
		to:       common.HexToAddress(toStr),
		gas:      common.Big(gasStr),
		gasPrice: common.Big(gasPriceStr),
		value:    common.Big(valueStr),
		data:     common.FromHex(dataStr),
	}

	if msg.gas.Cmp(big.NewInt(0)) == 0 {
		msg.gas = DefaultGas()
	}

	if msg.gasPrice.Cmp(big.NewInt(0)) == 0 {
		msg.gasPrice = DefaultGasPrice()
	}

	block := self.CurrentBlock()
	vmenv := core.NewEnv(statedb, self.backend.ChainManager(), msg, block)

	res, gas, err := core.ApplyMessage(vmenv, msg, from)
	return common.ToHex(res), gas.String(), err
}
Example #27
0
func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error {
	// Spec at https://github.com/ethereum/wiki/wiki/JSON-RPC
	glog.V(logger.Debug).Infof("%s %s", req.Method, req.Params)

	switch req.Method {
	case "web3_sha3":
		args := new(Sha3Args)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = common.ToHex(crypto.Sha3(common.FromHex(args.Data)))
	case "web3_clientVersion":
		*reply = api.xeth().ClientVersion()
	case "net_version":
		*reply = api.xeth().NetworkVersion()
	case "net_listening":
		*reply = api.xeth().IsListening()
	case "net_peerCount":
		*reply = newHexNum(api.xeth().PeerCount())
	case "eth_protocolVersion":
		*reply = api.xeth().EthVersion()
	case "eth_coinbase":
		*reply = newHexData(api.xeth().Coinbase())
	case "eth_mining":
		*reply = api.xeth().IsMining()
	case "eth_gasPrice":
		v := xeth.DefaultGasPrice()
		*reply = newHexNum(v.Bytes())
	case "eth_accounts":
		*reply = api.xeth().Accounts()
	case "eth_blockNumber":
		v := api.xeth().CurrentBlock().Number()
		*reply = newHexNum(v.Bytes())
	case "eth_getBalance":
		args := new(GetBalanceArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		*reply = api.xethAtStateNum(args.BlockNumber).BalanceAt(args.Address)
		//v := api.xethAtStateNum(args.BlockNumber).State().SafeGet(args.Address).Balance()
		//*reply = common.ToHex(v.Bytes())
	case "eth_getStorage", "eth_storageAt":
		args := new(GetStorageArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		*reply = api.xethAtStateNum(args.BlockNumber).State().SafeGet(args.Address).Storage()
	case "eth_getStorageAt":
		args := new(GetStorageAtArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		*reply = api.xethAtStateNum(args.BlockNumber).StorageAt(args.Address, args.Key)
	case "eth_getTransactionCount":
		args := new(GetTxCountArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		count := api.xethAtStateNum(args.BlockNumber).TxCountAt(args.Address)
		*reply = newHexNum(big.NewInt(int64(count)).Bytes())
	case "eth_getBlockTransactionCountByHash":
		args := new(HashArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := NewBlockRes(api.xeth().EthBlockByHash(args.Hash), false)
		if block == nil {
			*reply = nil
		} else {
			*reply = newHexNum(big.NewInt(int64(len(block.Transactions))).Bytes())
		}
	case "eth_getBlockTransactionCountByNumber":
		args := new(BlockNumArg)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := NewBlockRes(api.xeth().EthBlockByNumber(args.BlockNumber), false)
		if block == nil {
			*reply = nil
			break
		}

		*reply = newHexNum(big.NewInt(int64(len(block.Transactions))).Bytes())
	case "eth_getUncleCountByBlockHash":
		args := new(HashArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := api.xeth().EthBlockByHash(args.Hash)
		br := NewBlockRes(block, false)
		if br == nil {
			*reply = nil
			break
		}

		*reply = newHexNum(big.NewInt(int64(len(br.Uncles))).Bytes())
	case "eth_getUncleCountByBlockNumber":
		args := new(BlockNumArg)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := api.xeth().EthBlockByNumber(args.BlockNumber)
		br := NewBlockRes(block, false)
		if br == nil {
			*reply = nil
			break
		}

		*reply = newHexNum(big.NewInt(int64(len(br.Uncles))).Bytes())
	case "eth_getData", "eth_getCode":
		args := new(GetDataArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		v := api.xethAtStateNum(args.BlockNumber).CodeAtBytes(args.Address)
		*reply = newHexData(v)
	case "eth_sendTransaction", "eth_transact":
		args := new(NewTxArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		// call ConfirmTransaction first
		tx, _ := json.Marshal(req)
		if !api.xeth().ConfirmTransaction(string(tx)) {
			return fmt.Errorf("Transaction not confirmed")
		}

		// nonce may be nil ("guess" mode)
		var nonce string
		if args.Nonce != nil {
			nonce = args.Nonce.String()
		}

		v, err := api.xeth().Transact(args.From, args.To, nonce, args.Value.String(), args.Gas.String(), args.GasPrice.String(), args.Data)
		if err != nil {
			return err
		}
		*reply = v
	case "eth_call":
		args := new(CallArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		v, err := api.xethAtStateNum(args.BlockNumber).Call(args.From, args.To, args.Value.String(), args.Gas.String(), args.GasPrice.String(), args.Data)
		if err != nil {
			return err
		}
		// TODO unwrap the parent method's ToHex call
		if v == "0x0" {
			*reply = newHexData([]byte{})
		} else {
			*reply = newHexData(common.FromHex(v))
		}
	case "eth_flush":
		return NewNotImplementedError(req.Method)
	case "eth_getBlockByHash":
		args := new(GetBlockByHashArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := api.xeth().EthBlockByHash(args.BlockHash)
		br := NewBlockRes(block, args.IncludeTxs)

		*reply = br
	case "eth_getBlockByNumber":
		args := new(GetBlockByNumberArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := api.xeth().EthBlockByNumber(args.BlockNumber)
		br := NewBlockRes(block, args.IncludeTxs)

		*reply = br
	case "eth_getTransactionByHash":
		args := new(HashArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		tx, bhash, bnum, txi := api.xeth().EthTransactionByHash(args.Hash)
		if tx != nil {
			v := NewTransactionRes(tx)
			v.BlockHash = newHexData(bhash)
			v.BlockNumber = newHexNum(bnum)
			v.TxIndex = newHexNum(txi)
			*reply = v
		}
	case "eth_getTransactionByBlockHashAndIndex":
		args := new(HashIndexArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := api.xeth().EthBlockByHash(args.Hash)
		br := NewBlockRes(block, true)
		if br == nil {
			*reply = nil
			break
		}

		if args.Index >= int64(len(br.Transactions)) || args.Index < 0 {
			// return NewValidationError("Index", "does not exist")
			*reply = nil
		} else {
			*reply = br.Transactions[args.Index]
		}
	case "eth_getTransactionByBlockNumberAndIndex":
		args := new(BlockNumIndexArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := api.xeth().EthBlockByNumber(args.BlockNumber)
		v := NewBlockRes(block, true)
		if v == nil {
			*reply = nil
			break
		}

		if args.Index >= int64(len(v.Transactions)) || args.Index < 0 {
			// return NewValidationError("Index", "does not exist")
			*reply = nil
		} else {
			*reply = v.Transactions[args.Index]
		}
	case "eth_getUncleByBlockHashAndIndex":
		args := new(HashIndexArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		br := NewBlockRes(api.xeth().EthBlockByHash(args.Hash), false)
		if br == nil {
			*reply = nil
			return nil
		}

		if args.Index >= int64(len(br.Uncles)) || args.Index < 0 {
			// return NewValidationError("Index", "does not exist")
			*reply = nil
		} else {
			*reply = br.Uncles[args.Index]
		}
	case "eth_getUncleByBlockNumberAndIndex":
		args := new(BlockNumIndexArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		block := api.xeth().EthBlockByNumber(args.BlockNumber)
		v := NewBlockRes(block, true)

		if v == nil {
			*reply = nil
			return nil
		}

		if args.Index >= int64(len(v.Uncles)) || args.Index < 0 {
			// return NewValidationError("Index", "does not exist")
			*reply = nil
		} else {
			*reply = v.Uncles[args.Index]
		}
	case "eth_getCompilers":
		c := []string{""}
		*reply = c
	case "eth_compileSolidity", "eth_compileLLL", "eth_compileSerpent":
		return NewNotImplementedError(req.Method)
	case "eth_newFilter":
		args := new(BlockFilterArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		id := api.xeth().RegisterFilter(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics)
		*reply = newHexNum(big.NewInt(int64(id)).Bytes())
	case "eth_newBlockFilter":
		args := new(FilterStringArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = newHexNum(api.xeth().NewFilterString(args.Word))
	case "eth_uninstallFilter":
		args := new(FilterIdArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = api.xeth().UninstallFilter(args.Id)
	case "eth_getFilterChanges":
		args := new(FilterIdArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = NewLogsRes(api.xeth().FilterChanged(args.Id))
	case "eth_getFilterLogs":
		args := new(FilterIdArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = NewLogsRes(api.xeth().Logs(args.Id))
	case "eth_getLogs":
		args := new(BlockFilterArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = NewLogsRes(api.xeth().AllLogs(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics))
	case "eth_getWork":
		api.xeth().SetMining(true)
		*reply = api.xeth().RemoteMining().GetWork()
	case "eth_submitWork":
		args := new(SubmitWorkArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = api.xeth().RemoteMining().SubmitWork(args.Nonce, common.HexToHash(args.Digest), common.HexToHash(args.Header))
	case "db_putString":
		args := new(DbArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		if err := args.requirements(); err != nil {
			return err
		}

		api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)

		*reply = true
	case "db_getString":
		args := new(DbArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		if err := args.requirements(); err != nil {
			return err
		}

		res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
		*reply = string(res)
	case "db_putHex":
		args := new(DbHexArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		if err := args.requirements(); err != nil {
			return err
		}

		api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
		*reply = true
	case "db_getHex":
		args := new(DbHexArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}

		if err := args.requirements(); err != nil {
			return err
		}

		res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
		*reply = newHexData(res)

	case "shh_version":
		// Retrieves the currently running whisper protocol version
		*reply = api.xeth().WhisperVersion()

	case "shh_post":
		// Injects a new message into the whisper network
		args := new(WhisperMessageArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		err := api.xeth().Whisper().Post(args.Payload, args.To, args.From, args.Topics, args.Priority, args.Ttl)
		if err != nil {
			return err
		}
		*reply = true

	case "shh_newIdentity":
		// Creates a new whisper identity to use for sending/receiving messages
		*reply = api.xeth().Whisper().NewIdentity()

	case "shh_hasIdentity":
		// Checks if an identity if owned or not
		args := new(WhisperIdentityArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = api.xeth().Whisper().HasIdentity(args.Identity)

	case "shh_newFilter":
		// Create a new filter to watch and match messages with
		args := new(WhisperFilterArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		id := api.xeth().NewWhisperFilter(args.To, args.From, args.Topics)
		*reply = newHexNum(big.NewInt(int64(id)).Bytes())

	case "shh_uninstallFilter":
		// Remove an existing filter watching messages
		args := new(FilterIdArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = api.xeth().UninstallWhisperFilter(args.Id)

	case "shh_getFilterChanges":
		// Retrieve all the new messages arrived since the last request
		args := new(FilterIdArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = api.xeth().WhisperMessagesChanged(args.Id)

	case "shh_getMessages":
		// Retrieve all the cached messages matching a specific, existing filter
		args := new(FilterIdArgs)
		if err := json.Unmarshal(req.Params, &args); err != nil {
			return err
		}
		*reply = api.xeth().WhisperMessages(args.Id)
	case "eth_hashrate":
		*reply = newHexNum(api.xeth().HashRate())

	// case "eth_register":
	// 	// Placeholder for actual type
	// 	args := new(HashIndexArgs)
	// 	if err := json.Unmarshal(req.Params, &args); err != nil {
	// 		return err
	// 	}
	// 	*reply = api.xeth().Register(args.Hash)
	// case "eth_unregister":
	// 	args := new(HashIndexArgs)
	// 	if err := json.Unmarshal(req.Params, &args); err != nil {
	// 		return err
	// 	}
	// 	*reply = api.xeth().Unregister(args.Hash)
	// case "eth_watchTx":
	// 	args := new(HashIndexArgs)
	// 	if err := json.Unmarshal(req.Params, &args); err != nil {
	// 		return err
	// 	}
	// 	*reply = api.xeth().PullWatchTx(args.Hash)
	default:
		return NewNotImplementedError(req.Method)
	}

	glog.V(logger.Detail).Infof("Reply: %T %s\n", reply, reply)
	return nil
}
Example #28
0
// Sha3 applies the ethereum sha3 implementation on the input.
// It assumes the input is hex encoded.
func (s *PublicWeb3API) Sha3(input string) string {
	return common.ToHex(crypto.Keccak256(common.FromHex(input)))
}
Example #29
0
func (self *XEth) CodeAt(address string) string {
	return common.ToHex(self.State().state.GetCode(common.HexToAddress(address)))
}
Example #30
0
func (self *XEth) ToAscii(str string) string {
	padded := common.RightPadBytes([]byte(str), 32)

	return "0x" + common.ToHex(padded)
}