• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang common.HexToAddress函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: makeBlock

func makeBlock() *types.Block {
	parentHash := common.HexToHash("0x01")
	coinbase := common.HexToAddress("0x01")
	root := common.HexToHash("0x01")
	difficulty := common.Big1
	nonce := uint64(1)
	block := types.NewBlock(parentHash, coinbase, root, difficulty, nonce, nil)

	txto := common.HexToAddress("0x02")
	txamount := big.NewInt(1)
	txgasAmount := big.NewInt(1)
	txgasPrice := big.NewInt(1)
	txdata := []byte{1, 2, 3}

	tx := types.NewTransactionMessage(txto, txamount, txgasAmount, txgasPrice, txdata)
	txs := make([]*types.Transaction, 1)
	txs[0] = tx
	block.SetTransactions(txs)

	uncles := make([]*types.Header, 1)
	uncles[0] = makeHeader()
	block.SetUncles(uncles)

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


示例2: RunState

func RunState(statedb *state.StateDB, env, tx map[string]string) ([]byte, state.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()
		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"]))

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

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


示例3: 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       = FromHex(tx["data"])
		gas        = common.Big(tx["gasLimit"])
		price      = common.Big(tx["gasPrice"])
		value      = common.Big(tx["value"])
		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.SetGasPool(common.Big(env["currentGasLimit"]))

	message := NewMessage(common.BytesToAddress(keyPair.Address()), to, data, value, gas, price)
	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) {
		statedb.Set(snapshot)
	}
	statedb.Update()

	return ret, vmenv.logs, vmenv.Gas, err
}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:33,代码来源:vm.go


示例4: safeGet

func (self *State) safeGet(addr string) *state.StateObject {
	object := self.state.GetStateObject(common.HexToAddress(addr))
	if object == nil {
		object = state.NewStateObject(common.HexToAddress(addr), self.xeth.backend.StateDb())
	}

	return object
}
开发者ID:ruflin,项目名称:go-ethereum,代码行数:8,代码来源:state.go


示例5: SignTransaction

func (self *XEth) SignTransaction(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceStr, codeStr string) (*types.Transaction, error) {
	if len(toStr) > 0 && toStr != "0x" && !isAddress(toStr) {
		return nil, errors.New("Invalid address")
	}

	var (
		from             = common.HexToAddress(fromStr)
		to               = common.HexToAddress(toStr)
		value            = common.Big(valueStr)
		gas              *big.Int
		price            *big.Int
		data             []byte
		contractCreation bool
	)

	if len(gasStr) == 0 {
		gas = DefaultGas()
	} else {
		gas = common.Big(gasStr)
	}

	if len(gasPriceStr) == 0 {
		price = self.DefaultGasPrice()
	} else {
		price = common.Big(gasPriceStr)
	}

	data = common.FromHex(codeStr)
	if len(toStr) == 0 {
		contractCreation = true
	}

	var nonce uint64
	if len(nonceStr) != 0 {
		nonce = common.Big(nonceStr).Uint64()
	} else {
		// XXX: replaced tx pool state with managed state from app
		// state := self.backend.TxPool().State()
		state := self.ManagedState()
		nonce = state.GetNonce(from)
	}
	var tx *types.Transaction
	if contractCreation {
		tx = types.NewContractCreation(nonce, value, gas, price, data)
	} else {
		tx = types.NewTransaction(nonce, to, value, gas, price, data)
	}

	signed, err := self.sign(tx, from, false)
	if err != nil {
		return nil, err
	}

	return signed, nil
}
开发者ID:zramsay,项目名称:geth-tmsp,代码行数:55,代码来源:xeth.go


示例6: init

func init() {
	// Parse the list of DAO accounts to drain
	var list []map[string]string
	if err := json.Unmarshal([]byte(daoDrainListJSON), &list); err != nil {
		panic(fmt.Errorf("Failed to parse DAO drain list: %v", err))
	}
	// Collect all the accounts that need draining
	for _, dao := range list {
		DAODrainList = append(DAODrainList, common.HexToAddress(dao["address"]))
		DAODrainList = append(DAODrainList, common.HexToAddress(dao["extraBalanceAccount"]))
	}
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:12,代码来源:dao.go


示例7: NewEnvFromMap

func NewEnvFromMap(state *state.StateDB, envValues map[string]string, exeValues map[string]string) *Env {
	env := NewEnv(state)

	env.origin = common.HexToAddress(exeValues["caller"])
	//env.parent = common.Hex2Bytes(envValues["previousHash"])
	env.coinbase = common.HexToAddress(envValues["currentCoinbase"])
	env.number = common.Big(envValues["currentNumber"])
	env.time = common.Big(envValues["currentTimestamp"]).Int64()
	env.difficulty = common.Big(envValues["currentDifficulty"])
	env.gasLimit = common.Big(envValues["currentGasLimit"])
	env.Gas = new(big.Int)

	return env
}
开发者ID:ssonneborn22,项目名称:go-ethereum,代码行数:14,代码来源:util.go


示例8: TestNewContractAddress

func TestNewContractAddress(t *testing.T) {
	key, _ := HexToECDSA(testPrivHex)
	addr := common.HexToAddress(testAddrHex)
	genAddr := PubkeyToAddress(key.PublicKey)
	// sanity check before using addr to create contract address
	checkAddr(t, genAddr, addr)

	caddr0 := CreateAddress(addr, 0)
	caddr1 := CreateAddress(addr, 1)
	caddr2 := CreateAddress(addr, 2)
	checkAddr(t, common.HexToAddress("333c3310824b7c685133f2bedb2ca4b8b4df633d"), caddr0)
	checkAddr(t, common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"), caddr1)
	checkAddr(t, common.HexToAddress("c9ddedf451bc62ce88bf9292afb13df35b670699"), caddr2)
}
开发者ID:j4ustin,项目名称:go-ethereum,代码行数:14,代码来源:crypto_test.go


示例9: InsertPreState

// InsertPreState populates the given database with the genesis
// accounts defined by the test.
func (t *BlockTest) InsertPreState(db ethdb.Database, am *accounts.Manager) (*state.StateDB, error) {
	statedb, err := state.New(common.Hash{}, db)
	if err != nil {
		return nil, err
	}
	for addrString, acct := range t.preAccounts {
		addr, err := hex.DecodeString(addrString)
		if err != nil {
			return nil, err
		}
		code, err := hex.DecodeString(strings.TrimPrefix(acct.Code, "0x"))
		if err != nil {
			return nil, err
		}
		balance, ok := new(big.Int).SetString(acct.Balance, 0)
		if !ok {
			return nil, err
		}
		nonce, err := strconv.ParseUint(prepInt(16, acct.Nonce), 16, 64)
		if err != nil {
			return nil, err
		}

		if acct.PrivateKey != "" {
			privkey, err := hex.DecodeString(strings.TrimPrefix(acct.PrivateKey, "0x"))
			err = crypto.ImportBlockTestKey(privkey)
			err = am.TimedUnlock(common.BytesToAddress(addr), "", 999999*time.Second)
			if err != nil {
				return nil, err
			}
		}

		obj := statedb.CreateAccount(common.HexToAddress(addrString))
		obj.SetCode(code)
		obj.SetBalance(balance)
		obj.SetNonce(nonce)
		for k, v := range acct.Storage {
			statedb.SetState(common.HexToAddress(addrString), common.HexToHash(k), common.HexToHash(v))
		}
	}

	root, err := statedb.Commit()
	if err != nil {
		return nil, fmt.Errorf("error writing state: %v", err)
	}
	if t.Genesis.Root() != root {
		return nil, fmt.Errorf("computed state root does not match genesis block: genesis=%x computed=%x", t.Genesis.Root().Bytes()[:4], root.Bytes()[:4])
	}
	return statedb, nil
}
开发者ID:j4ustin,项目名称:go-ethereum,代码行数:52,代码来源:block_test_util.go


示例10: Call

// 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
}
开发者ID:karalabe,项目名称:etherapis,代码行数:51,代码来源:api.go


示例11: InsertPreState

// InsertPreState populates the given database with the genesis
// accounts defined by the test.
func (t *BlockTest) InsertPreState(ethereum *eth.Ethereum) (*state.StateDB, error) {
	db := ethereum.StateDb()
	statedb := state.New(common.Hash{}, db)
	for addrString, acct := range t.preAccounts {
		addr, err := hex.DecodeString(addrString)
		if err != nil {
			return nil, err
		}
		code, err := hex.DecodeString(strings.TrimPrefix(acct.Code, "0x"))
		if err != nil {
			return nil, err
		}
		balance, ok := new(big.Int).SetString(acct.Balance, 0)
		if !ok {
			return nil, err
		}
		nonce, err := strconv.ParseUint(prepInt(16, acct.Nonce), 16, 64)
		if err != nil {
			return nil, err
		}

		if acct.PrivateKey != "" {
			privkey, err := hex.DecodeString(strings.TrimPrefix(acct.PrivateKey, "0x"))
			err = crypto.ImportBlockTestKey(privkey)
			err = ethereum.AccountManager().TimedUnlock(common.BytesToAddress(addr), "", 999999*time.Second)
			if err != nil {
				return nil, err
			}
		}

		obj := statedb.CreateAccount(common.HexToAddress(addrString))
		obj.SetCode(code)
		obj.SetBalance(balance)
		obj.SetNonce(nonce)
		for k, v := range acct.Storage {
			statedb.SetState(common.HexToAddress(addrString), common.HexToHash(k), common.HexToHash(v))
		}
	}
	// sync objects to trie
	statedb.SyncObjects()
	// sync trie to disk
	statedb.Sync()

	if !bytes.Equal(t.Genesis.Root().Bytes(), statedb.Root().Bytes()) {
		return nil, fmt.Errorf("computed state root does not match genesis block %x %x", t.Genesis.Root().Bytes()[:4], statedb.Root().Bytes()[:4])
	}
	return statedb, nil
}
开发者ID:nilcons-contrib,项目名称:go-ethereum,代码行数:50,代码来源:block_test_util.go


示例12: newTester

// newTester creates a test environment based on which the console can operate.
// Please ensure you call Close() on the returned tester to avoid leaks.
func newTester(t *testing.T, confOverride func(*eth.Config)) *tester {
	// Create a temporary storage for the node keys and initialize it
	workspace, err := ioutil.TempDir("", "console-tester-")
	if err != nil {
		t.Fatalf("failed to create temporary keystore: %v", err)
	}
	accman := accounts.NewPlaintextManager(filepath.Join(workspace, "keystore"))

	// Create a networkless protocol stack and start an Ethereum service within
	stack, err := node.New(&node.Config{DataDir: workspace, Name: testInstance, NoDiscovery: true})
	if err != nil {
		t.Fatalf("failed to create node: %v", err)
	}
	ethConf := &eth.Config{
		ChainConfig:    &core.ChainConfig{HomesteadBlock: new(big.Int)},
		Etherbase:      common.HexToAddress(testAddress),
		AccountManager: accman,
		PowTest:        true,
	}
	if confOverride != nil {
		confOverride(ethConf)
	}
	if err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil {
		t.Fatalf("failed to register Ethereum protocol: %v", err)
	}
	// Start the node and assemble the JavaScript console around it
	if err = stack.Start(); err != nil {
		t.Fatalf("failed to start test stack: %v", err)
	}
	client, err := stack.Attach()
	if err != nil {
		t.Fatalf("failed to attach to node: %v", err)
	}
	prompter := &hookedPrompter{scheduler: make(chan string)}
	printer := new(bytes.Buffer)

	console, err := New(Config{
		DataDir:  stack.DataDir(),
		DocRoot:  "testdata",
		Client:   client,
		Prompter: prompter,
		Printer:  printer,
		Preload:  []string{"preload.js"},
	})
	if err != nil {
		t.Fatalf("failed to create JavaScript console: %v", err)
	}
	// Create the final tester and return
	var ethereum *eth.Ethereum
	stack.Service(&ethereum)

	return &tester{
		workspace: workspace,
		stack:     stack,
		ethereum:  ethereum,
		console:   console,
		input:     prompter,
		output:    printer,
	}
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:62,代码来源:console_test.go


示例13: unlockAccount

func unlockAccount(ctx *cli.Context, am *accounts.Manager, addr string, i int, inputpassphrases []string) (addrHex, auth string, passphrases []string) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	var err error
	passphrases = inputpassphrases
	addrHex, err = utils.ParamToAddress(addr, am)
	if err == nil {
		// Attempt to unlock the account 3 times
		attempts := 3
		for tries := 0; tries < attempts; tries++ {
			msg := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", addr, tries+1, attempts)
			auth, passphrases = getPassPhrase(ctx, msg, false, i, passphrases)
			err = am.Unlock(common.HexToAddress(addrHex), auth)
			if err == nil || passphrases != nil {
				break
			}
		}
	}

	if err != nil {
		utils.Fatalf("Unlock account '%s' (%v) failed: %v", addr, addrHex, err)
	}
	fmt.Printf("Account '%s' (%v) unlocked.\n", addr, addrHex)
	return
}
开发者ID:General-Beck,项目名称:go-ethereum,代码行数:25,代码来源:main.go


示例14: TestNewTransactionRes

func TestNewTransactionRes(t *testing.T) {
	to := common.HexToAddress("0x02")
	amount := big.NewInt(1)
	gasAmount := big.NewInt(1)
	gasPrice := big.NewInt(1)
	data := []byte{1, 2, 3}
	tx := types.NewTransactionMessage(to, amount, gasAmount, gasPrice, data)

	tests := map[string]string{
		"hash":             reHash,
		"nonce":            reNum,
		"blockHash":        reHashOpt,
		"blockNum":         reNumOpt,
		"transactionIndex": reNumOpt,
		"from":             reAddress,
		"to":               reAddressOpt,
		"value":            reNum,
		"gas":              reNum,
		"gasPrice":         reNum,
		"input":            reData,
	}

	v := NewTransactionRes(tx)
	v.BlockHash = newHexData(common.HexToHash("0x030201"))
	v.BlockNumber = newHexNum(5)
	v.TxIndex = newHexNum(0)
	j, _ := json.Marshal(v)
	for k, re := range tests {
		match, _ := regexp.MatchString(fmt.Sprintf(`{.*"%s":%s.*}`, k, re), string(j))
		if !match {
			t.Error(fmt.Sprintf("`%s` output json does not match format %s. Source %s", k, re, j))
		}
	}

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


示例15: TestSign

func TestSign(t *testing.T) {
	key, _ := HexToECDSA(testPrivHex)
	addr := common.HexToAddress(testAddrHex)

	msg := Sha3([]byte("foo"))
	sig, err := Sign(msg, key)
	if err != nil {
		t.Errorf("Sign error: %s", err)
	}
	recoveredPub, err := Ecrecover(msg, sig)
	if err != nil {
		t.Errorf("ECRecover error: %s", err)
	}
	recoveredAddr := PubkeyToAddress(*ToECDSAPub(recoveredPub))
	if addr != recoveredAddr {
		t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr)
	}

	// should be equal to SigToPub
	recoveredPub2, err := SigToPub(msg, sig)
	if err != nil {
		t.Errorf("ECRecover error: %s", err)
	}
	recoveredAddr2 := PubkeyToAddress(*recoveredPub2)
	if addr != recoveredAddr2 {
		t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr2)
	}

}
开发者ID:j4ustin,项目名称:go-ethereum,代码行数:29,代码来源:crypto_test.go


示例16: TestLoadECDSAFile

func TestLoadECDSAFile(t *testing.T) {
	keyBytes := common.FromHex(testPrivHex)
	fileName0 := "test_key0"
	fileName1 := "test_key1"
	checkKey := func(k *ecdsa.PrivateKey) {
		checkAddr(t, PubkeyToAddress(k.PublicKey), common.HexToAddress(testAddrHex))
		loadedKeyBytes := FromECDSA(k)
		if !bytes.Equal(loadedKeyBytes, keyBytes) {
			t.Fatalf("private key mismatch: want: %x have: %x", keyBytes, loadedKeyBytes)
		}
	}

	ioutil.WriteFile(fileName0, []byte(testPrivHex), 0600)
	defer os.Remove(fileName0)

	key0, err := LoadECDSA(fileName0)
	if err != nil {
		t.Fatal(err)
	}
	checkKey(key0)

	// again, this time with SaveECDSA instead of manual save:
	err = SaveECDSA(fileName1, key0)
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(fileName1)

	key1, err := LoadECDSA(fileName1)
	if err != nil {
		t.Fatal(err)
	}
	checkKey(key1)
}
开发者ID:j4ustin,项目名称:go-ethereum,代码行数:34,代码来源:crypto_test.go


示例17: TestKeyEncryptDecrypt

// Tests that a json key file can be decrypted and encrypted in multiple rounds.
func TestKeyEncryptDecrypt(t *testing.T) {
	keyjson, err := ioutil.ReadFile("testdata/very-light-scrypt.json")
	if err != nil {
		t.Fatal(err)
	}
	password := ""
	address := common.HexToAddress("45dea0fb0bba44f4fcf290bba71fd57d7117cbb8")

	// Do a few rounds of decryption and encryption
	for i := 0; i < 3; i++ {
		// Try a bad password first
		if _, err := DecryptKey(keyjson, password+"bad"); err == nil {
			t.Errorf("test %d: json key decrypted with bad password", i)
		}
		// Decrypt with the correct password
		key, err := DecryptKey(keyjson, password)
		if err != nil {
			t.Errorf("test %d: json key failed to decrypt: %v", i, err)
		}
		if key.Address != address {
			t.Errorf("test %d: key address mismatch: have %x, want %x", i, key.Address, address)
		}
		// Recrypt with a new password and start over
		password += "new data appended"
		if keyjson, err = EncryptKey(key, password, veryLightScryptN, veryLightScryptP); err != nil {
			t.Errorf("test %d: failed to recrypt key %v", i, err)
		}
	}
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:30,代码来源:key_store_passphrase_test.go


示例18: checkLogs

func checkLogs(tlog []Log, logs state.Logs) error {

	if len(tlog) != len(logs) {
		return fmt.Errorf("log length mismatch. Expected %d, got %d", len(tlog), len(logs))
	} else {
		for i, log := range tlog {
			if common.HexToAddress(log.AddressF) != logs[i].Address {
				return fmt.Errorf("log address expected %v got %x", log.AddressF, logs[i].Address)
			}

			if !bytes.Equal(logs[i].Data, common.FromHex(log.DataF)) {
				return fmt.Errorf("log data expected %v got %x", log.DataF, logs[i].Data)
			}

			if len(log.TopicsF) != len(logs[i].Topics) {
				return fmt.Errorf("log topics length expected %d got %d", len(log.TopicsF), logs[i].Topics)
			} else {
				for j, topic := range log.TopicsF {
					if common.HexToHash(topic) != logs[i].Topics[j] {
						return fmt.Errorf("log topic[%d] expected %v got %x", j, topic, logs[i].Topics[j])
					}
				}
			}
			genBloom := common.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256)

			if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) {
				return fmt.Errorf("bloom mismatch")
			}
		}
	}
	return nil
}
开发者ID:ssonneborn22,项目名称:go-ethereum,代码行数:32,代码来源:util.go


示例19: Subscriptions

// Subscriptions retrieves the given address' subscriptions.
func (a *api) Subscriptions(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	addr, exist := vars["address"]
	if !exist {
		log15.Error("Failed to retrieve subscriptions", "error", "no address specified")
		http.Error(w, "no address specified", http.StatusInternalServerError)
		return
	}

	services, err := a.eapis.Contract().Subscriptions(common.HexToAddress(addr))
	if err != nil {
		log15.Error("Failed to retrieve subscriptions", "error", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	out, err := json.Marshal(services)
	if err != nil {
		log15.Error("Failed to marshal subscriptions", "error", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(out)
}
开发者ID:karalabe,项目名称:etherapis,代码行数:26,代码来源:api.go


示例20: MakeAddress

// MakeAddress converts an account specified directly as a hex encoded string or
// a key index in the key store to an internal account representation.
func MakeAddress(accman *accounts.Manager, account string) (a common.Address, err error) {
	// If the specified account is a valid address, return it
	if common.IsHexAddress(account) {
		return common.HexToAddress(account), nil
	}
	// Otherwise try to interpret the account as a keystore index
	index, err := strconv.Atoi(account)
	if err != nil {
		return a, fmt.Errorf("invalid account address or index %q", account)
	}
	hex, err := accman.AddressByIndex(index)
	if err != nil {
		return a, fmt.Errorf("can't get account #%d (%v)", index, err)
	}
	return common.HexToAddress(hex), nil
}
开发者ID:obscuren,项目名称:etherapis,代码行数:18,代码来源:flags.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang common.HexToHash函数代码示例发布时间:2022-05-23
下一篇:
Golang common.Hex2Bytes函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap