本文整理匯總了Golang中github.com/ethereum/go-ethereum/common.HexToAddress函數的典型用法代碼示例。如果您正苦於以下問題:Golang HexToAddress函數的具體用法?Golang HexToAddress怎麽用?Golang HexToAddress使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了HexToAddress函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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"]))
}
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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 := ð.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(ðereum)
return &tester{
workspace: workspace,
stack: stack,
ethereum: ethereum,
console: console,
input: prompter,
output: printer,
}
}
示例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
}
示例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))
}
}
}
示例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)
}
}