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


Golang types.NewBlock函数代码示例

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


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

示例1: GenerateChain

// GenerateChain creates a chain of n blocks. The first block's
// parent will be the provided parent. db is used to store
// intermediate states and should contain the parent's state trie.
//
// The generator function is called with a new block generator for
// every block. Any transactions and uncles added to the generator
// become part of the block. If gen is nil, the blocks will be empty
// and their coinbase will be the zero address.
//
// Blocks created by GenerateChain do not contain valid proof of work
// values. Inserting them into BlockChain requires use of FakePow or
// a similar non-validating proof of work implementation.
func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
	statedb, err := state.New(parent.Root(), db)
	if err != nil {
		panic(err)
	}
	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
	genblock := func(i int, h *types.Header) (*types.Block, types.Receipts) {
		b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb}
		if gen != nil {
			gen(i, b)
		}
		AccumulateRewards(statedb, h, b.uncles)
		root, err := statedb.Commit()
		if err != nil {
			panic(fmt.Sprintf("state write error: %v", err))
		}
		h.Root = root
		return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts
	}
	for i := 0; i < n; i++ {
		header := makeHeader(parent, statedb)
		block, receipt := genblock(i, header)
		blocks[i] = block
		receipts[i] = receipt
		parent = block
	}
	return blocks, receipts
}
开发者ID:j4ustin,项目名称:go-ethereum,代码行数:40,代码来源:chain_makers.go

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

示例3: NewBlock

// Block creation & chain handling
func (bc *ChainManager) NewBlock(coinbase common.Address) *types.Block {
	bc.mu.RLock()
	defer bc.mu.RUnlock()

	var (
		root       common.Hash
		parentHash common.Hash
	)

	if bc.currentBlock != nil {
		root = bc.currentBlock.Header().Root
		parentHash = bc.lastBlockHash
	}

	block := types.NewBlock(
		parentHash,
		coinbase,
		root,
		common.BigPow(2, 32),
		0,
		nil)
	block.SetUncles(nil)
	block.SetTransactions(nil)
	block.SetReceipts(nil)

	parent := bc.currentBlock
	if parent != nil {
		header := block.Header()
		header.Difficulty = CalcDifficulty(block.Header(), parent.Header())
		header.Number = new(big.Int).Add(parent.Header().Number, common.Big1)
		header.GasLimit = CalcGasLimit(parent)
	}

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

示例4: TestNonExistingParentAttack60

// Tests that if a peer returns an invalid chain with a block pointing to a non-
// existing parent, it is correctly detected and handled.
func TestNonExistingParentAttack60(t *testing.T) {
	tester := newTester()

	// Forge a single-link chain with a forged header
	hashes, blocks := makeChain(1, 0, genesis)
	tester.newPeer("valid", eth60, hashes, blocks)

	wrongblock := types.NewBlock(&types.Header{}, nil, nil, nil)
	wrongblock.Td = blocks[hashes[0]].Td
	hashes, blocks = makeChain(1, 0, wrongblock)
	tester.newPeer("attack", eth60, hashes, blocks)

	// Try and sync with the malicious node and check that it fails
	if err := tester.sync("attack", nil); err == nil {
		t.Fatalf("block synchronization succeeded")
	}
	if tester.hasBlock(hashes[0]) {
		t.Fatalf("tester accepted unknown-parent block: %v", blocks[hashes[0]])
	}
	// Try to synchronize with the valid chain and make sure it succeeds
	if err := tester.sync("valid", nil); err != nil {
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
	if !tester.hasBlock(tester.peerHashes["valid"][0]) {
		t.Fatalf("tester didn't accept known-parent block: %v", tester.peerBlocks["valid"][hashes[0]])
	}
}
开发者ID:nellyk,项目名称:go-ethereum,代码行数:29,代码来源:downloader_test.go

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

示例6: GPUBench

func GPUBench(gpuid uint64) {
	e := ethash.NewCL([]int{int(gpuid)})

	var h common.Hash
	bogoHeader := &types.Header{
		ParentHash: h,
		Number:     big.NewInt(int64(42)),
		Difficulty: big.NewInt(int64(999999999999999)),
	}
	bogoBlock := types.NewBlock(bogoHeader, nil, nil, nil)

	err := ethash.InitCL(bogoBlock.NumberU64(), e)
	if err != nil {
		fmt.Println("OpenCL init error: ", err)
		return
	}

	stopChan := make(chan struct{})
	reportHashRate := func() {
		for {
			time.Sleep(3 * time.Second)
			fmt.Printf("hashes/s : %v\n", e.GetHashrate())
		}
	}
	fmt.Printf("Starting benchmark (%v seconds)\n", 60)
	go reportHashRate()
	go e.Search(bogoBlock, stopChan, 0)
	time.Sleep(60 * time.Second)
	fmt.Println("OK.")
}
开发者ID:j4ustin,项目名称:go-ethereum,代码行数:30,代码来源:gpu_mining.go

示例7: newChain

func newChain(size int) (chain []*types.Block) {
	var parentHash common.Hash
	for i := 0; i < size; i++ {
		head := &types.Header{ParentHash: parentHash, Number: big.NewInt(int64(i))}
		block := types.NewBlock(head, nil, nil, nil)
		chain = append(chain, block)
		parentHash = block.Hash()
	}
	return chain
}
开发者ID:haegyung,项目名称:go-ethereum,代码行数:10,代码来源:block_cache_test.go

示例8: newChain

func newChain(size int) (chain []*types.Block) {
	var parentHash common.Hash
	for i := 0; i < size; i++ {
		block := types.NewBlock(parentHash, common.Address{}, common.Hash{}, new(big.Int), 0, nil)
		block.Header().Number = big.NewInt(int64(i))
		chain = append(chain, block)
		parentHash = block.Hash()
	}
	return
}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:10,代码来源:block_cache_test.go

示例9: GenesisBlockForTesting

// GenesisBlockForTesting creates a block in which addr has the given wei balance.
// The state trie of the block is written to db.
func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
	statedb := state.New(common.Hash{}, db)
	obj := statedb.GetOrNewStateObject(addr)
	obj.SetBalance(balance)
	statedb.SyncObjects()
	statedb.Sync()
	block := types.NewBlock(&types.Header{
		Difficulty: params.GenesisDifficulty,
		GasLimit:   params.GenesisGasLimit,
		Root:       statedb.Root(),
	}, nil, nil, nil)
	return block
}
开发者ID:NikonMcFly,项目名称:go-ethereum,代码行数:15,代码来源:genesis.go

示例10: pendingBlock

func (self *worker) pendingBlock() *types.Block {
	self.currentMu.Lock()
	defer self.currentMu.Unlock()
	if atomic.LoadInt32(&self.mining) == 0 {
		return types.NewBlock(
			self.current.header,
			self.current.txs,
			nil,
			self.current.receipts,
		)
	}
	return self.current.block
}
开发者ID:haegyung,项目名称:go-ethereum,代码行数:13,代码来源:worker.go

示例11: pending

func (self *worker) pending() (*types.Block, *state.StateDB) {
	self.currentMu.Lock()
	defer self.currentMu.Unlock()

	if atomic.LoadInt32(&self.mining) == 0 {
		return types.NewBlock(
			self.current.header,
			self.current.txs,
			nil,
			self.current.receipts,
		), self.current.state
	}
	return self.current.Block, self.current.state
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:14,代码来源:worker.go

示例12: GenesisBlockForTesting

// GenesisBlockForTesting creates a block in which addr has the given wei balance.
// The state trie of the block is written to db. the passed db needs to contain a state root
func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
	statedb, _ := state.New(common.Hash{}, db)
	obj := statedb.GetOrNewStateObject(addr)
	obj.SetBalance(balance)
	root, err := statedb.Commit()
	if err != nil {
		panic(fmt.Sprintf("cannot write state: %v", err))
	}
	block := types.NewBlock(&types.Header{
		Difficulty: params.GenesisDifficulty,
		GasLimit:   params.GenesisGasLimit,
		Root:       root,
	}, nil, nil, nil)
	return block
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:17,代码来源:genesis.go

示例13: newBlockFromParent

// block time is fixed at 10 seconds
func newBlockFromParent(addr common.Address, parent *types.Block) *types.Block {
	block := types.NewBlock(parent.Hash(), addr, parent.Root(), common.BigPow(2, 32), 0, nil)
	block.SetUncles(nil)
	block.SetTransactions(nil)
	block.SetReceipts(nil)

	header := block.Header()
	header.Difficulty = CalcDifficulty(block.Header(), parent.Header())
	header.Number = new(big.Int).Add(parent.Header().Number, common.Big1)
	header.Time = parent.Header().Time + 10
	header.GasLimit = CalcGasLimit(parent)

	block.Td = parent.Td

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

示例14: GenerateChain

// GenerateChain creates a chain of n blocks. The first block's
// parent will be the provided parent. db is used to store
// intermediate states and should contain the parent's state trie.
//
// The generator function is called with a new block generator for
// every block. Any transactions and uncles added to the generator
// become part of the block. If gen is nil, the blocks will be empty
// and their coinbase will be the zero address.
//
// Blocks created by GenerateChain do not contain valid proof of work
// values. Inserting them into BlockChain requires use of FakePow or
// a similar non-validating proof of work implementation.
func GenerateChain(config *ChainConfig, parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
	genblock := func(i int, h *types.Header, statedb *state.StateDB) (*types.Block, types.Receipts) {
		b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb}

		// Mutate the state and block according to any hard-fork specs
		if config == nil {
			config = MakeChainConfig()
		}
		if daoBlock := config.DAOForkBlock; daoBlock != nil {
			limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
			if h.Number.Cmp(daoBlock) >= 0 && h.Number.Cmp(limit) < 0 {
				if config.DAOForkSupport {
					h.Extra = common.CopyBytes(params.DAOForkBlockExtra)
				}
			}
		}
		if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(h.Number) == 0 {
			ApplyDAOHardFork(statedb)
		}
		// Execute any user modifications to the block and finalize it
		if gen != nil {
			gen(i, b)
		}
		AccumulateRewards(statedb, h, b.uncles)
		root, err := statedb.Commit()
		if err != nil {
			panic(fmt.Sprintf("state write error: %v", err))
		}
		h.Root = root
		return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts
	}
	for i := 0; i < n; i++ {
		statedb, err := state.New(parent.Root(), db)
		if err != nil {
			panic(err)
		}
		header := makeHeader(parent, statedb)
		block, receipt := genblock(i, header, statedb)
		blocks[i] = block
		receipts[i] = receipt
		parent = block
	}
	return blocks, receipts
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:57,代码来源:chain_makers.go

示例15: GenerateChain

// GenerateChain creates a chain of n blocks. The first block's
// parent will be the provided parent. db is used to store
// intermediate states and should contain the parent's state trie.
//
// The generator function is called with a new block generator for
// every block. Any transactions and uncles added to the generator
// become part of the block. If gen is nil, the blocks will be empty
// and their coinbase will be the zero address.
//
// Blocks created by GenerateChain do not contain valid proof of work
// values. Inserting them into ChainManager requires use of FakePow or
// a similar non-validating proof of work implementation.
func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) []*types.Block {
	statedb := state.New(parent.Root(), db)
	blocks := make(types.Blocks, n)
	genblock := func(i int, h *types.Header) *types.Block {
		b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb}
		if gen != nil {
			gen(i, b)
		}
		AccumulateRewards(statedb, h, b.uncles)
		statedb.SyncIntermediate()
		h.Root = statedb.Root()
		return types.NewBlock(h, b.txs, b.uncles, b.receipts)
	}
	for i := 0; i < n; i++ {
		header := makeHeader(parent, statedb)
		block := genblock(i, header)
		blocks[i] = block
		parent = block
	}
	return blocks
}
开发者ID:NikonMcFly,项目名称:go-ethereum,代码行数:33,代码来源:chain_makers.go


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