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

Golang crypto.PubkeyToAddress函数代码示例

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

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



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

示例1: testGetReceipt

func testGetReceipt(t *testing.T, protocol int) {
	// Define three accounts to simulate transactions with
	acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
	acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
	acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
	acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)

	// Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_makerts_test)
	generator := func(i int, block *core.BlockGen) {
		switch i {
		case 0:
			// In block 1, the test bank sends account #1 some ether.
			tx, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(testBankKey)
			block.AddTx(tx)
		case 1:
			// In block 2, the test bank sends some more ether to account #1.
			// acc1Addr passes it on to account #2.
			tx1, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testBankKey)
			tx2, _ := types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(acc1Key)
			block.AddTx(tx1)
			block.AddTx(tx2)
		case 2:
			// Block 3 is empty but was mined by account #2.
			block.SetCoinbase(acc2Addr)
			block.SetExtra([]byte("yeehaw"))
		case 3:
			// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
			b2 := block.PrevBlock(1).Header()
			b2.Extra = []byte("foo")
			block.AddUncle(b2)
			b3 := block.PrevBlock(2).Header()
			b3.Extra = []byte("foo")
			block.AddUncle(b3)
		}
	}
	// Assemble the test environment
	pm := newTestProtocolManager(4, generator, nil)
	peer, _ := newTestPeer("peer", protocol, pm, true)
	defer peer.close()

	// Collect the hashes to request, and the response to expect
	hashes := []common.Hash{}
	for i := uint64(0); i <= pm.chainman.CurrentBlock().NumberU64(); i++ {
		for _, tx := range pm.chainman.GetBlockByNumber(i).Transactions() {
			hashes = append(hashes, tx.Hash())
		}
	}
	receipts := make([]*types.Receipt, len(hashes))
	for i, hash := range hashes {
		receipts[i] = core.GetReceipt(pm.chaindb, hash)
	}
	// Send the hash request and verify the response
	p2p.Send(peer.app, 0x0f, hashes)
	if err := p2p.ExpectMsg(peer.app, 0x10, receipts); err != nil {
		t.Errorf("receipts mismatch: %v", err)
	}
}
开发者ID:NikonMcFly,项目名称:go-ethereum,代码行数:57,代码来源:handler_test.go


示例2: TestSignerPromotion

// Tests that subsequent signers can be promoted, each requiring half plus one
// votes for it to pass through.
func TestSignerPromotion(t *testing.T) {
	// Prefund a few accounts to authorize with and create the oracle
	keys := make([]*ecdsa.PrivateKey, 5)
	for i := 0; i < len(keys); i++ {
		keys[i], _ = crypto.GenerateKey()
	}
	key, oracle, sim := setupReleaseTest(t, keys...)

	// Gradually promote the keys, until all are authorized
	keys = append([]*ecdsa.PrivateKey{key}, keys...)
	for i := 1; i < len(keys); i++ {
		// Check that no votes are accepted from the not yet authed user
		if _, err := oracle.Promote(bind.NewKeyedTransactor(keys[i]), common.Address{}); err != nil {
			t.Fatalf("Iter #%d: failed invalid promotion attempt: %v", i, err)
		}
		sim.Commit()

		pend, err := oracle.AuthProposals(nil)
		if err != nil {
			t.Fatalf("Iter #%d: failed to retrieve active proposals: %v", i, err)
		}
		if len(pend) != 0 {
			t.Fatalf("Iter #%d: proposal count mismatch: have %d, want 0", i, len(pend))
		}
		// Promote with half - 1 voters and check that the user's not yet authorized
		for j := 0; j < i/2; j++ {
			if _, err = oracle.Promote(bind.NewKeyedTransactor(keys[j]), crypto.PubkeyToAddress(keys[i].PublicKey)); err != nil {
				t.Fatalf("Iter #%d: failed valid promotion attempt: %v", i, err)
			}
		}
		sim.Commit()

		signers, err := oracle.Signers(nil)
		if err != nil {
			t.Fatalf("Iter #%d: failed to retrieve list of signers: %v", i, err)
		}
		if len(signers) != i {
			t.Fatalf("Iter #%d: signer count mismatch: have %v, want %v", i, len(signers), i)
		}
		// Promote with the last one needed to pass the promotion
		if _, err = oracle.Promote(bind.NewKeyedTransactor(keys[i/2]), crypto.PubkeyToAddress(keys[i].PublicKey)); err != nil {
			t.Fatalf("Iter #%d: failed valid promotion completion attempt: %v", i, err)
		}
		sim.Commit()

		signers, err = oracle.Signers(nil)
		if err != nil {
			t.Fatalf("Iter #%d: failed to retrieve list of signers: %v", i, err)
		}
		if len(signers) != i+1 {
			t.Fatalf("Iter #%d: signer count mismatch: have %v, want %v", i, len(signers), i+1)
		}
	}
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:56,代码来源:contract_test.go


示例3: 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


示例4: DecryptKey

// DecryptKey decrypts a key from a json blob, returning the private key itself.
func DecryptKey(keyjson []byte, auth string) (*Key, error) {
	// Parse the json into a simple map to fetch the key version
	m := make(map[string]interface{})
	if err := json.Unmarshal(keyjson, &m); err != nil {
		return nil, err
	}
	// Depending on the version try to parse one way or another
	var (
		keyBytes, keyId []byte
		err             error
	)
	if version, ok := m["version"].(string); ok && version == "1" {
		k := new(encryptedKeyJSONV1)
		if err := json.Unmarshal(keyjson, k); err != nil {
			return nil, err
		}
		keyBytes, keyId, err = decryptKeyV1(k, auth)
	} else {
		k := new(encryptedKeyJSONV3)
		if err := json.Unmarshal(keyjson, k); err != nil {
			return nil, err
		}
		keyBytes, keyId, err = decryptKeyV3(k, auth)
	}
	// Handle any decryption errors and return the key
	if err != nil {
		return nil, err
	}
	key := crypto.ToECDSA(keyBytes)
	return &Key{
		Id:         uuid.UUID(keyId),
		Address:    crypto.PubkeyToAddress(key.PublicKey),
		PrivateKey: key,
	}, nil
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:36,代码来源:key_store_passphrase.go


示例5: TestTransactionChainFork

func TestTransactionChainFork(t *testing.T) {
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
	resetState := func() {
		db, _ := ethdb.NewMemDatabase()
		statedb, _ := state.New(common.Hash{}, db)
		pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
		currentState, _ := pool.currentState()
		currentState.AddBalance(addr, big.NewInt(100000000000000))
		pool.resetState()
	}
	resetState()

	tx := transaction(0, big.NewInt(100000), key)
	if err := pool.add(tx); err != nil {
		t.Error("didn't expect error", err)
	}
	pool.RemoveTransactions([]*types.Transaction{tx})

	// reset the pool's internal state
	resetState()
	if err := pool.add(tx); err != nil {
		t.Error("didn't expect error", err)
	}
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:25,代码来源:tx_pool_test.go


示例6: TestTransactionDoubleNonce

func TestTransactionDoubleNonce(t *testing.T) {
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
	resetState := func() {
		db, _ := ethdb.NewMemDatabase()
		statedb := state.New(common.Hash{}, db)
		pool.currentState = func() *state.StateDB { return statedb }
		pool.currentState().AddBalance(addr, big.NewInt(100000000000000))
		pool.resetState()
	}
	resetState()

	tx := transaction(0, big.NewInt(100000), key)
	tx2 := transaction(0, big.NewInt(1000000), key)
	if err := pool.add(tx); err != nil {
		t.Error("didn't expect error", err)
	}
	if err := pool.add(tx2); err != nil {
		t.Error("didn't expect error", err)
	}

	pool.checkQueue()
	if len(pool.pending) != 2 {
		t.Error("expected 2 pending txs. Got", len(pool.pending))
	}
}
开发者ID:RepublicMaster,项目名称:go-ethereum,代码行数:26,代码来源:transaction_pool_test.go


示例7: TestVersionAutoNuke

// Tests that demoting a signer will auto-nuke the currently pending release.
func TestVersionAutoNuke(t *testing.T) {
	// Prefund a few accounts to authorize with and create the oracle
	keys := make([]*ecdsa.PrivateKey, 5)
	for i := 0; i < len(keys); i++ {
		keys[i], _ = crypto.GenerateKey()
	}
	key, oracle, sim := setupReleaseTest(t, keys...)

	// Authorize all the keys as valid signers
	keys = append([]*ecdsa.PrivateKey{key}, keys...)
	for i := 1; i < len(keys); i++ {
		for j := 0; j <= i/2; j++ {
			if _, err := oracle.Promote(bind.NewKeyedTransactor(keys[j]), crypto.PubkeyToAddress(keys[i].PublicKey)); err != nil {
				t.Fatalf("Iter #%d: failed valid promotion attempt: %v", i, err)
			}
		}
		sim.Commit()
	}
	// Make a release proposal and check it's existence
	if _, err := oracle.Release(bind.NewKeyedTransactor(keys[0]), 1, 2, 3, [20]byte{4}); err != nil {
		t.Fatalf("Failed valid proposal attempt: %v", err)
	}
	sim.Commit()

	prop, err := oracle.ProposedVersion(nil)
	if err != nil {
		t.Fatalf("Failed to retrieve active proposal: %v", err)
	}
	if len(prop.Pass) != 1 {
		t.Fatalf("Proposal vote count mismatch: have %d, want 1", len(prop.Pass))
	}
	// Demote a signer and check release proposal deletion
	for i := 0; i <= len(keys)/2; i++ {
		if _, err := oracle.Demote(bind.NewKeyedTransactor(keys[i]), crypto.PubkeyToAddress(keys[len(keys)-1].PublicKey)); err != nil {
			t.Fatalf("Iter #%d: failed valid demotion attempt: %v", i, err)
		}
	}
	sim.Commit()

	prop, err = oracle.ProposedVersion(nil)
	if err != nil {
		t.Fatalf("Failed to retrieve active proposal: %v", err)
	}
	if len(prop.Pass) != 0 {
		t.Fatalf("Proposal vote count mismatch: have %d, want 0", len(prop.Pass))
	}
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:48,代码来源:contract_test.go


示例8: init

func init() {
	ringKeys[0] = benchRootKey
	ringAddrs[0] = benchRootAddr
	for i := 1; i < len(ringKeys); i++ {
		ringKeys[i], _ = crypto.GenerateKey()
		ringAddrs[i] = crypto.PubkeyToAddress(ringKeys[i].PublicKey)
	}
}
开发者ID:nilcons-contrib,项目名称:go-ethereum,代码行数:8,代码来源:bench_test.go


示例9: newKeyFromECDSA

func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
	id := uuid.NewRandom()
	key := &Key{
		Id:         id,
		Address:    crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
		PrivateKey: privateKeyECDSA,
	}
	return key
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:9,代码来源:key.go


示例10: TestContractCreation

// Tests that the version contract can be deployed and the creator is assigned
// the sole authorized signer.
func TestContractCreation(t *testing.T) {
	key, oracle, _ := setupReleaseTest(t)

	owner := crypto.PubkeyToAddress(key.PublicKey)
	signers, err := oracle.Signers(nil)
	if err != nil {
		t.Fatalf("Failed to retrieve list of signers: %v", err)
	}
	if len(signers) != 1 || signers[0] != owner {
		t.Fatalf("Initial signer mismatch: have %v, want %v", signers, owner)
	}
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:14,代码来源:contract_test.go


示例11: TestVersionNuking

// Tests that proposed versions can be nuked out of existence.
func TestVersionNuking(t *testing.T) {
	// Prefund a few accounts to authorize with and create the oracle
	keys := make([]*ecdsa.PrivateKey, 9)
	for i := 0; i < len(keys); i++ {
		keys[i], _ = crypto.GenerateKey()
	}
	key, oracle, sim := setupReleaseTest(t, keys...)

	// Authorize all the keys as valid signers
	keys = append([]*ecdsa.PrivateKey{key}, keys...)
	for i := 1; i < len(keys); i++ {
		for j := 0; j <= i/2; j++ {
			if _, err := oracle.Promote(bind.NewKeyedTransactor(keys[j]), crypto.PubkeyToAddress(keys[i].PublicKey)); err != nil {
				t.Fatalf("Iter #%d: failed valid promotion attempt: %v", i, err)
			}
		}
		sim.Commit()
	}
	// Propose releases with more and more keys, always retaining enough users to nuke the proposals
	for i := 1; i < (len(keys)+1)/2; i++ {
		// Propose release with an initial set of signers
		for j := 0; j < i; j++ {
			if _, err := oracle.Release(bind.NewKeyedTransactor(keys[j]), uint32(i), uint32(i+1), uint32(i+2), [20]byte{byte(i + 3)}); err != nil {
				t.Fatalf("Iter #%d: failed valid proposal attempt: %v", i, err)
			}
		}
		sim.Commit()

		prop, err := oracle.ProposedVersion(nil)
		if err != nil {
			t.Fatalf("Iter #%d: failed to retrieve active proposal: %v", i, err)
		}
		if len(prop.Pass) != i {
			t.Fatalf("Iter #%d: proposal vote count mismatch: have %d, want %d", i, len(prop.Pass), i)
		}
		// Nuke the release with half+1 voters
		for j := i; j <= i+(len(keys)+1)/2; j++ {
			if _, err := oracle.Nuke(bind.NewKeyedTransactor(keys[j])); err != nil {
				t.Fatalf("Iter #%d: failed valid nuke attempt: %v", i, err)
			}
		}
		sim.Commit()

		prop, err = oracle.ProposedVersion(nil)
		if err != nil {
			t.Fatalf("Iter #%d: failed to retrieve active proposal: %v", i, err)
		}
		if len(prop.Pass) != 0 || len(prop.Fail) != 0 {
			t.Fatalf("Iter #%d: proposal vote count mismatch: have %d/%d pass/fail, want 0/0", i, len(prop.Pass), len(prop.Fail))
		}
	}
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:53,代码来源:contract_test.go


示例12: Subscribe

// Start Go API. Not important for this version
func (c *Contract) Subscribe(key *ecdsa.PrivateKey, serviceId *big.Int, amount, price *big.Int, cb func(*Subscription)) (*types.Transaction, error) {
	from := crypto.PubkeyToAddress(key.PublicKey)

	data, err := c.abi.Pack("subscribe", serviceId)
	if err != nil {
		return nil, err
	}

	statedb, err := c.blockchain.State()
	if err != nil {
		return nil, err
	}

	transaction, err := types.NewTransaction(statedb.GetNonce(from), contractAddress, amount, big.NewInt(600000), big.NewInt(50000000000), data).SignECDSA(key)
	if err != nil {
		return nil, err
	}

	evId := c.abi.Events["NewSubscription"].Id()
	filter := filters.New(c.db)
	filter.SetAddresses([]common.Address{contractAddress})
	filter.SetTopics([][]common.Hash{ // TODO refactor, helper
		[]common.Hash{evId},
		[]common.Hash{from.Hash()},
		[]common.Hash{common.BigToHash(serviceId)},
	})
	filter.SetBeginBlock(0)
	filter.SetEndBlock(-1)
	filter.LogCallback = func(log *vm.Log, removed bool) {
		// TODO: do to and from validation here
		/*
			from := log.Topics[1]
			to := log.Topics[2]
		*/
		subscriptionId := common.BytesToHash(log.Data[0:31])
		nonce := common.BytesToBig(log.Data[31:])

		c.channelMu.Lock()
		defer c.channelMu.Unlock()

		channel, exist := c.subs[subscriptionId]
		if !exist {
			channel = NewSubscription(c, subscriptionId, from, serviceId, nonce)
			c.subs[subscriptionId] = channel
		}
		cb(channel)
	}

	c.filters.Add(filter, filters.PendingLogFilter)

	return transaction, nil
}
开发者ID:karalabe,项目名称:etherapis,代码行数:53,代码来源:contract.go


示例13: TestMissingNonce

func TestMissingNonce(t *testing.T) {
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
	pool.currentState().AddBalance(addr, big.NewInt(100000000000000))
	tx := transaction(1, big.NewInt(100000), key)
	if err := pool.add(tx); err != nil {
		t.Error("didn't expect error", err)
	}
	if len(pool.pending) != 0 {
		t.Error("expected 0 pending transactions, got", len(pool.pending))
	}
	if len(pool.queue[addr]) != 1 {
		t.Error("expected 1 queued transaction, got", len(pool.queue[addr]))
	}
}
开发者ID:RepublicMaster,项目名称:go-ethereum,代码行数:15,代码来源:transaction_pool_test.go


示例14: NewKeyedTransactor

// NewKeyedTransactor is a utility method to easily create a transaction signer
// from a single private key.
func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
	keyAddr := crypto.PubkeyToAddress(key.PublicKey)
	return &TransactOpts{
		From: keyAddr,
		Signer: func(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
			if address != keyAddr {
				return nil, errors.New("not authorized to sign this account")
			}
			signature, err := crypto.Sign(tx.SigHash().Bytes(), key)
			if err != nil {
				return nil, err
			}
			return tx.WithSignature(signature)
		},
	}
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:18,代码来源:auth.go


示例15: TestNonceRecovery

func TestNonceRecovery(t *testing.T) {
	const n = 10
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
	pool.currentState().SetNonce(addr, n)
	pool.currentState().AddBalance(addr, big.NewInt(100000000000000))
	pool.resetState()
	tx := transaction(n, big.NewInt(100000), key)
	if err := pool.Add(tx); err != nil {
		t.Error(err)
	}
	// simulate some weird re-order of transactions and missing nonce(s)
	pool.currentState().SetNonce(addr, n-1)
	pool.resetState()
	if fn := pool.pendingState.GetNonce(addr); fn != n+1 {
		t.Errorf("expected nonce to be %d, got %d", n+1, fn)
	}
}
开发者ID:NikonMcFly,项目名称:go-ethereum,代码行数:18,代码来源:transaction_pool_test.go


示例16: TestLogReorgs

func TestLogReorgs(t *testing.T) {
	params.MinGasLimit = big.NewInt(125000)      // Minimum the gas limit may ever be.
	params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.

	var (
		key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
		addr1   = crypto.PubkeyToAddress(key1.PublicKey)
		db, _   = ethdb.NewMemDatabase()
		// this code generates a log
		code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
	)
	genesis := WriteGenesisBlockForTesting(db,
		GenesisAccount{addr1, big.NewInt(10000000000000)},
	)

	evmux := &event.TypeMux{}
	blockchain, _ := NewBlockChain(db, testChainConfig(), FakePow{}, evmux)

	subs := evmux.Subscribe(RemovedLogsEvent{})
	chain, _ := GenerateChain(nil, genesis, db, 2, func(i int, gen *BlockGen) {
		if i == 1 {
			tx, err := types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), big.NewInt(1000000), new(big.Int), code).SignECDSA(key1)
			if err != nil {
				t.Fatalf("failed to create tx: %v", err)
			}
			gen.AddTx(tx)
		}
	})
	if _, err := blockchain.InsertChain(chain); err != nil {
		t.Fatalf("failed to insert chain: %v", err)
	}

	chain, _ = GenerateChain(nil, genesis, db, 3, func(i int, gen *BlockGen) {})
	if _, err := blockchain.InsertChain(chain); err != nil {
		t.Fatalf("failed to insert forked chain: %v", err)
	}

	ev := <-subs.Chan()
	if len(ev.Data.(RemovedLogsEvent).Logs) == 0 {
		t.Error("expected logs")
	}
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:42,代码来源:blockchain_test.go


示例17: setupReleaseTest

// setupReleaseTest creates a blockchain simulator and deploys a version oracle
// contract for testing.
func setupReleaseTest(t *testing.T, prefund ...*ecdsa.PrivateKey) (*ecdsa.PrivateKey, *ReleaseOracle, *backends.SimulatedBackend) {
	// Generate a new random account and a funded simulator
	key, _ := crypto.GenerateKey()
	auth := bind.NewKeyedTransactor(key)

	accounts := []core.GenesisAccount{{Address: auth.From, Balance: big.NewInt(10000000000)}}
	for _, key := range prefund {
		accounts = append(accounts, core.GenesisAccount{Address: crypto.PubkeyToAddress(key.PublicKey), Balance: big.NewInt(10000000000)})
	}
	sim := backends.NewSimulatedBackend(accounts...)

	// Deploy a version oracle contract, commit and return
	_, _, oracle, err := DeployReleaseOracle(auth, sim, []common.Address{auth.From})
	if err != nil {
		t.Fatalf("Failed to deploy version contract: %v", err)
	}
	sim.Commit()

	return key, oracle, sim
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:22,代码来源:contract_test.go


示例18: decryptPreSaleKey

func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error) {
	preSaleKeyStruct := struct {
		EncSeed string
		EthAddr string
		Email   string
		BtcAddr string
	}{}
	err = json.Unmarshal(fileContent, &preSaleKeyStruct)
	if err != nil {
		return nil, err
	}
	encSeedBytes, err := hex.DecodeString(preSaleKeyStruct.EncSeed)
	iv := encSeedBytes[:16]
	cipherText := encSeedBytes[16:]
	/*
		See https://github.com/ethereum/pyethsaletool

		pyethsaletool generates the encryption key from password by
		2000 rounds of PBKDF2 with HMAC-SHA-256 using password as salt (:().
		16 byte key length within PBKDF2 and resulting key is used as AES key
	*/
	passBytes := []byte(password)
	derivedKey := pbkdf2.Key(passBytes, passBytes, 2000, 16, sha256.New)
	plainText, err := aesCBCDecrypt(derivedKey, cipherText, iv)
	if err != nil {
		return nil, err
	}
	ethPriv := crypto.Keccak256(plainText)
	ecKey := crypto.ToECDSA(ethPriv)
	key = &Key{
		Id:         nil,
		Address:    crypto.PubkeyToAddress(ecKey.PublicKey),
		PrivateKey: ecKey,
	}
	derivedAddr := hex.EncodeToString(key.Address.Bytes()) // needed because .Hex() gives leading "0x"
	expectedAddr := preSaleKeyStruct.EthAddr
	if derivedAddr != expectedAddr {
		err = fmt.Errorf("decrypted addr '%s' not equal to expected addr '%s'", derivedAddr, expectedAddr)
	}
	return key, err
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:41,代码来源:presale.go


示例19: makeChain

	"sync/atomic"
	"testing"
	"time"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/params"
)

var (
	testdb, _    = ethdb.NewMemDatabase()
	testKey, _   = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
	testAddress  = crypto.PubkeyToAddress(testKey.PublicKey)
	genesis      = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000))
	unknownBlock = types.NewBlock(&types.Header{GasLimit: params.GenesisGasLimit}, nil, nil, nil)
)

// makeChain creates a chain of n blocks starting at and including parent.
// the returned hash chain is ordered head->parent. In addition, every 3rd block
// contains a transaction and every 5th an uncle to allow testing correct block
// reassembly.
func makeChain(n int, seed byte, parent *types.Block) ([]common.Hash, map[common.Hash]*types.Block) {
	blocks, _ := core.GenerateChain(nil, parent, testdb, n, func(i int, block *core.BlockGen) {
		block.SetCoinbase(common.Address{seed})

		// If the block number is multiple of 3, send a bonus transaction to the miner
		if parent == genesis && i%3 == 0 {
			tx, err := types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testKey)
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:31,代码来源:fetcher_test.go


示例20: ExampleGenerateChain

func ExampleGenerateChain() {
	var (
		key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
		key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
		key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
		addr1   = crypto.PubkeyToAddress(key1.PublicKey)
		addr2   = crypto.PubkeyToAddress(key2.PublicKey)
		addr3   = crypto.PubkeyToAddress(key3.PublicKey)
		db, _   = ethdb.NewMemDatabase()
	)

	// Ensure that key1 has some funds in the genesis block.
	genesis := GenesisBlockForTesting(db, addr1, big.NewInt(1000000))

	// This call generates a chain of 5 blocks. The function runs for
	// each block and adds different features to gen based on the
	// block index.
	chain := GenerateChain(genesis, db, 5, func(i int, gen *BlockGen) {
		switch i {
		case 0:
			// In block 1, addr1 sends addr2 some ether.
			tx, _ := types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(key1)
			gen.AddTx(tx)
		case 1:
			// In block 2, addr1 sends some more ether to addr2.
			// addr2 passes it on to addr3.
			tx1, _ := types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
			tx2, _ := types.NewTransaction(gen.TxNonce(addr2), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
			gen.AddTx(tx1)
			gen.AddTx(tx2)
		case 2:
			// Block 3 is empty but was mined by addr3.
			gen.SetCoinbase(addr3)
			gen.SetExtra([]byte("yeehaw"))
		case 3:
			// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
			b2 := gen.PrevBlock(1).Header()
			b2.Extra = []byte("foo")
			gen.AddUncle(b2)
			b3 := gen.PrevBlock(2).Header()
			b3.Extra = []byte("foo")
			gen.AddUncle(b3)
		}
	})

	// Import the chain. This runs all block validation rules.
	evmux := &event.TypeMux{}
	chainman, _ := NewChainManager(genesis, db, db, FakePow{}, evmux)
	chainman.SetProcessor(NewBlockProcessor(db, db, FakePow{}, chainman, evmux))
	if i, err := chainman.InsertChain(chain); err != nil {
		fmt.Printf("insert error (block %d): %v\n", i, err)
		return
	}

	state := chainman.State()
	fmt.Printf("last block: #%d\n", chainman.CurrentBlock().Number())
	fmt.Println("balance of addr1:", state.GetBalance(addr1))
	fmt.Println("balance of addr2:", state.GetBalance(addr2))
	fmt.Println("balance of addr3:", state.GetBalance(addr3))
	// Output:
	// last block: #5
	// balance of addr1: 989000
	// balance of addr2: 10000
	// balance of addr3: 5906250000000001000
}
开发者ID:haegyung,项目名称:go-ethereum,代码行数:65,代码来源:chain_makers_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang crypto.Sha3函数代码示例发布时间:2022-05-23
下一篇:
Golang crypto.NewKeyStorePassphrase函数代码示例发布时间: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