当前位置: 首页>>代码示例>>Golang>>正文


Golang common.FromHex函数代码示例

本文整理汇总了Golang中github.com/ethereum/go-ethereum/common.FromHex函数的典型用法代码示例。如果您正苦于以下问题:Golang FromHex函数的具体用法?Golang FromHex怎么用?Golang FromHex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了FromHex函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: NewFilter

// NewWhisperFilter creates and registers a new message filter to watch for inbound whisper messages.
func (s *PublicWhisperAPI) NewFilter(args NewFilterArgs) (*rpc.HexNumber, error) {
	if s.w == nil {
		return nil, whisperOffLineErr
	}

	var id int
	filter := Filter{
		To:     crypto.ToECDSAPub(common.FromHex(args.To)),
		From:   crypto.ToECDSAPub(common.FromHex(args.From)),
		Topics: NewFilterTopics(args.Topics...),
		Fn: func(message *Message) {
			wmsg := NewWhisperMessage(message)
			s.messagesMu.RLock() // Only read lock to the filter pool
			defer s.messagesMu.RUnlock()
			if s.messages[id] != nil {
				s.messages[id].insert(wmsg)
			}
		},
	}

	id = s.w.Watch(filter)

	s.messagesMu.Lock()
	s.messages[id] = newWhisperFilter(id, s.w)
	s.messagesMu.Unlock()

	return rpc.NewHexNumber(id), nil
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:29,代码来源:api.go

示例2: Post

func (self *Whisper) Post(payload []string, to, from string, topics []string, priority, ttl uint32) {
	var data []byte
	for _, d := range payload {
		data = append(data, common.FromHex(d)...)
	}

	pk := crypto.ToECDSAPub(common.FromHex(from))
	if key := self.Whisper.GetIdentity(pk); key != nil {
		msg := whisper.NewMessage(data)
		envelope, err := msg.Wrap(time.Duration(priority*100000), whisper.Options{
			TTL:    time.Duration(ttl) * time.Second,
			To:     crypto.ToECDSAPub(common.FromHex(to)),
			From:   key,
			Topics: whisper.NewTopicsFromStrings(topics...),
		})

		if err != nil {
			qlogger.Infoln(err)
			// handle error
			return
		}

		if err := self.Whisper.Send(envelope); err != nil {
			qlogger.Infoln(err)
			// handle error
			return
		}
	} else {
		qlogger.Infoln("unmatched pub / priv for seal")
	}

}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:32,代码来源:whisper.go

示例3: Post

// Post injects a message into the whisper network for distribution.
func (s *PublicWhisperAPI) Post(args PostArgs) (bool, error) {
	if s.w == nil {
		return false, whisperOffLineErr
	}

	// construct whisper message with transmission options
	message := NewMessage(common.FromHex(args.Payload))
	options := Options{
		To:     crypto.ToECDSAPub(common.FromHex(args.To)),
		TTL:    time.Duration(args.TTL) * time.Second,
		Topics: NewTopics(args.Topics...),
	}

	// set sender identity
	if len(args.From) > 0 {
		if key := s.w.GetIdentity(crypto.ToECDSAPub(common.FromHex(args.From))); key != nil {
			options.From = key
		} else {
			return false, fmt.Errorf("unknown identity to send from: %s", args.From)
		}
	}

	// Wrap and send the message
	pow := time.Duration(args.Priority) * time.Millisecond
	envelope, err := message.Wrap(pow, options)
	if err != nil {
		return false, err
	}

	return true, s.w.Send(envelope)
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:32,代码来源:api.go

示例4: Post

// Post injects a message into the whisper network for distribution.
func (self *Whisper) Post(payload string, to, from string, topics []string, priority, ttl uint32) error {
	// Decode the topic strings
	topicsDecoded := make([][]byte, len(topics))
	for i, topic := range topics {
		topicsDecoded[i] = common.FromHex(topic)
	}
	// Construct the whisper message and transmission options
	message := whisper.NewMessage(common.FromHex(payload))
	options := whisper.Options{
		To:     crypto.ToECDSAPub(common.FromHex(to)),
		TTL:    time.Duration(ttl) * time.Second,
		Topics: whisper.NewTopics(topicsDecoded...),
	}
	if len(from) != 0 {
		if key := self.Whisper.GetIdentity(crypto.ToECDSAPub(common.FromHex(from))); key != nil {
			options.From = key
		} else {
			return fmt.Errorf("unknown identity to send from: %s", from)
		}
	}
	// Wrap and send the message
	pow := time.Duration(priority) * time.Millisecond
	envelope, err := message.Wrap(pow, options)
	if err != nil {
		return err
	}
	if err := self.Whisper.Send(envelope); err != nil {
		return err
	}
	return nil
}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:32,代码来源:whisper.go

示例5: EthTransactionByHash

func (self *XEth) EthTransactionByHash(hash string) (tx *types.Transaction, blhash common.Hash, blnum *big.Int, txi uint64) {
	data, _ := self.backend.ExtraDb().Get(common.FromHex(hash))
	if len(data) != 0 {
		tx = types.NewTransactionFromBytes(data)
	} else { // check pending transactions
		tx = self.backend.TxPool().GetTransaction(common.HexToHash(hash))
	}

	// meta
	var txExtra struct {
		BlockHash  common.Hash
		BlockIndex uint64
		Index      uint64
	}

	v, _ := self.backend.ExtraDb().Get(append(common.FromHex(hash), 0x0001))
	r := bytes.NewReader(v)
	err := rlp.Decode(r, &txExtra)
	if err == nil {
		blhash = txExtra.BlockHash
		blnum = big.NewInt(int64(txExtra.BlockIndex))
		txi = txExtra.Index
	} else {
		glog.V(logger.Error).Infoln(err)
	}

	return
}
开发者ID:hiroshi1tanaka,项目名称:gethkey,代码行数:28,代码来源:xeth.go

示例6: EthTransactionByHash

func (self *XEth) EthTransactionByHash(hash string) (tx *types.Transaction, blhash common.Hash, blnum *big.Int, txi uint64) {
	// Due to increasing return params and need to determine if this is from transaction pool or
	// some chain, this probably needs to be refactored for more expressiveness
	data, _ := self.backend.ExtraDb().Get(common.FromHex(hash))
	if len(data) != 0 {
		tx = types.NewTransactionFromBytes(data)
	} else { // check pending transactions
		tx = self.backend.TxPool().GetTransaction(common.HexToHash(hash))
	}

	// meta
	var txExtra struct {
		BlockHash  common.Hash
		BlockIndex uint64
		Index      uint64
	}

	v, dberr := self.backend.ExtraDb().Get(append(common.FromHex(hash), 0x0001))
	// TODO check specifically for ErrNotFound
	if dberr != nil {
		return
	}
	r := bytes.NewReader(v)
	err := rlp.Decode(r, &txExtra)
	if err == nil {
		blhash = txExtra.BlockHash
		blnum = big.NewInt(int64(txExtra.BlockIndex))
		txi = txExtra.Index
	} else {
		glog.V(logger.Error).Infoln(err)
	}

	return
}
开发者ID:GrimDerp,项目名称:go-ethereum,代码行数:34,代码来源:xeth.go

示例7: filterFromMap

func filterFromMap(opts map[string]interface{}) (f whisper.Filter) {
	if to, ok := opts["to"].(string); ok {
		f.To = crypto.ToECDSAPub(common.FromHex(to))
	}
	if from, ok := opts["from"].(string); ok {
		f.From = crypto.ToECDSAPub(common.FromHex(from))
	}
	if topicList, ok := opts["topics"].(*qml.List); ok {
		var topics []string
		topicList.Convert(&topics)
		f.Topics = whisper.NewFilterTopicsFromStringsFlat(topics...)
	}

	return
}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:15,代码来源:whisper.go

示例8: UnmarshalJSON

func (args *PostArgs) UnmarshalJSON(data []byte) (err error) {
	var obj struct {
		From     string        `json:"from"`
		To       string        `json:"to"`
		Topics   []string      `json:"topics"`
		Payload  string        `json:"payload"`
		Priority rpc.HexNumber `json:"priority"`
		TTL      rpc.HexNumber `json:"ttl"`
	}

	if err := json.Unmarshal(data, &obj); err != nil {
		return err
	}

	args.From = obj.From
	args.To = obj.To
	args.Payload = obj.Payload
	args.Priority = obj.Priority.Int64()
	args.TTL = obj.TTL.Int64()

	// decode topic strings
	args.Topics = make([][]byte, len(obj.Topics))
	for i, topic := range obj.Topics {
		args.Topics[i] = common.FromHex(topic)
	}

	return nil
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:28,代码来源:api.go

示例9: RunState

func RunState(ruleSet RuleSet, statedb *state.StateDB, env, tx map[string]string) ([]byte, vm.Logs, *big.Int, error) {
	var (
		data  = common.FromHex(tx["data"])
		gas   = common.Big(tx["gasLimit"])
		price = common.Big(tx["gasPrice"])
		value = common.Big(tx["value"])
		nonce = common.Big(tx["nonce"]).Uint64()
	)

	var to *common.Address
	if len(tx["to"]) > 2 {
		t := common.HexToAddress(tx["to"])
		to = &t
	}
	// Set pre compiled contracts
	vm.Precompiled = vm.PrecompiledContracts()
	snapshot := statedb.Copy()
	gaspool := new(core.GasPool).AddGas(common.Big(env["currentGasLimit"]))

	key, _ := hex.DecodeString(tx["secretKey"])
	addr := crypto.PubkeyToAddress(crypto.ToECDSA(key).PublicKey)
	message := NewMessage(addr, to, data, value, gas, price, nonce)
	vmenv := NewEnvFromMap(ruleSet, statedb, env, tx)
	vmenv.origin = addr
	ret, _, err := core.ApplyMessage(vmenv, message, gaspool)
	if core.IsNonceErr(err) || core.IsInvalidTxErr(err) || core.IsGasLimitErr(err) {
		statedb.Set(snapshot)
	}
	statedb.Commit()

	return ret, vmenv.state.Logs(), vmenv.Gas, err
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:32,代码来源:state_test_util.go

示例10: FromNumber

func (self *XEth) FromNumber(str string) string {
	if common.IsHex(str) {
		str = str[2:]
	}

	return common.BigD(common.FromHex(str)).String()
}
开发者ID:GrimDerp,项目名称:go-ethereum,代码行数:7,代码来源:xeth.go

示例11: unlock

func (js *jsre) unlock(call otto.FunctionCall) otto.Value {
	addr, err := call.Argument(0).ToString()
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	seconds, err := call.Argument(2).ToInteger()
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	arg := call.Argument(1)
	var passphrase string
	if arg.IsUndefined() {
		fmt.Println("Please enter a passphrase now.")
		passphrase, err = readPassword("Passphrase: ", true)
		if err != nil {
			utils.Fatalf("%v", err)
		}
	} else {
		passphrase, err = arg.ToString()
		if err != nil {
			fmt.Println(err)
			return otto.FalseValue()
		}
	}
	am := js.ethereum.AccountManager()
	err = am.TimedUnlock(common.FromHex(addr), passphrase, time.Duration(seconds)*time.Second)
	if err != nil {
		fmt.Printf("Unlock account failed '%v'\n", err)
		return otto.FalseValue()
	}
	return otto.TrueValue()
}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:34,代码来源:admin.go

示例12: RunState

func RunState(statedb *state.StateDB, env, tx map[string]string) ([]byte, state.Logs, *big.Int, error) {
	var (
		keyPair, _ = crypto.NewKeyPairFromSec([]byte(common.Hex2Bytes(tx["secretKey"])))
		data       = common.FromHex(tx["data"])
		gas        = common.Big(tx["gasLimit"])
		price      = common.Big(tx["gasPrice"])
		value      = common.Big(tx["value"])
		nonce      = common.Big(tx["nonce"]).Uint64()
		caddr      = common.HexToAddress(env["currentCoinbase"])
	)

	var to *common.Address
	if len(tx["to"]) > 2 {
		t := common.HexToAddress(tx["to"])
		to = &t
	}
	// Set pre compiled contracts
	vm.Precompiled = vm.PrecompiledContracts()

	snapshot := statedb.Copy()
	coinbase := statedb.GetOrNewStateObject(caddr)
	coinbase.SetGasLimit(common.Big(env["currentGasLimit"]))

	message := NewMessage(common.BytesToAddress(keyPair.Address()), to, data, value, gas, price, nonce)
	vmenv := NewEnvFromMap(statedb, env, tx)
	vmenv.origin = common.BytesToAddress(keyPair.Address())
	ret, _, err := core.ApplyMessage(vmenv, message, coinbase)
	if core.IsNonceErr(err) || core.IsInvalidTxErr(err) || state.IsGasLimitErr(err) {
		statedb.Set(snapshot)
	}
	statedb.Update()

	return ret, vmenv.state.Logs(), vmenv.Gas, err
}
开发者ID:ssonneborn22,项目名称:go-ethereum,代码行数:34,代码来源:state_test_util.go

示例13: GenesisBlock

// GenesisBlock creates a genesis block with the given nonce.
func GenesisBlock(nonce uint64, db common.Database) *types.Block {
	var accounts map[string]struct {
		Balance string
		Code    string
	}
	err := json.Unmarshal(GenesisAccounts, &accounts)
	if err != nil {
		fmt.Println("unable to decode genesis json data:", err)
		os.Exit(1)
	}
	statedb := state.New(common.Hash{}, db)
	for addr, account := range accounts {
		codedAddr := common.Hex2Bytes(addr)
		accountState := statedb.CreateAccount(common.BytesToAddress(codedAddr))
		accountState.SetBalance(common.Big(account.Balance))
		accountState.SetCode(common.FromHex(account.Code))
		statedb.UpdateStateObject(accountState)
	}
	statedb.Sync()

	block := types.NewBlock(&types.Header{
		Difficulty: params.GenesisDifficulty,
		GasLimit:   params.GenesisGasLimit,
		Nonce:      types.EncodeNonce(nonce),
		Root:       statedb.Root(),
	}, nil, nil, nil)
	block.Td = params.GenesisDifficulty
	return block
}
开发者ID:haegyung,项目名称:go-ethereum,代码行数:30,代码来源:genesis.go

示例14: ContractCall

// 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
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:27,代码来源:remote.go

示例15: TestNull

func TestNull(t *testing.T) {
	var trie Trie
	key := make([]byte, 32)
	value := common.FromHex("0x823140710bf13990e4500136726d8b55")
	trie.Update(key, value)
	value = trie.Get(key)
}
开发者ID:Xiaoyang-Zhu,项目名称:go-ethereum,代码行数:7,代码来源:trie_test.go


注:本文中的github.com/ethereum/go-ethereum/common.FromHex函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。