This commit is contained in:
Felix Lange 2015-10-23 23:18:56 +00:00
commit 83eb453772
61 changed files with 705 additions and 705 deletions

View file

@ -28,8 +28,8 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/logger/glog"
@ -165,7 +165,7 @@ func main() {
type VMEnv struct {
state *state.StateDB
block *types.Block
block *data.Block
transactor *common.Address
value *big.Int

View file

@ -27,8 +27,8 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/logger/glog"
)
@ -168,7 +168,7 @@ func upgradeDB(ctx *cli.Context) {
func dump(ctx *cli.Context) {
chain, chainDb := utils.MakeChain(ctx)
for _, arg := range ctx.Args() {
var block *types.Block
var block *data.Block
if hashish(arg) {
block = chain.GetBlock(common.HexToHash(arg))
} else {

View file

@ -34,7 +34,7 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/logger"
@ -558,7 +558,7 @@ func blockRecovery(ctx *cli.Context) {
glog.Fatalln("could not open db:", err)
}
var block *types.Block
var block *data.Block
if arg[0] == '#' {
block = core.GetBlock(blockDb, core.GetCanonicalHash(blockDb, common.String2Big(arg[1:]).Uint64()))
} else {

View file

@ -28,7 +28,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
@ -190,7 +190,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
stream := rlp.NewStream(fh, 0)
// Run actual the import.
blocks := make(types.Blocks, importBatchSize)
blocks := make(data.Blocks, importBatchSize)
n := 0
for batch := 0; ; batch++ {
// Load a batch of RLP blocks.
@ -199,7 +199,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
}
i := 0
for ; i < importBatchSize; i++ {
var b types.Block
var b data.Block
if err := stream.Decode(&b); err == io.EOF {
break
} else if err != nil {
@ -233,7 +233,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
return nil
}
func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
func hasAllBlocks(chain *core.BlockChain, bs []*data.Block) bool {
for _, b := range bs {
if !chain.HasBlock(b.Hash()) {
return false

View file

@ -23,7 +23,7 @@ import (
"net/http"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/rlp"
@ -34,7 +34,7 @@ var DisableBadBlockReporting = true
// ReportBlock reports the block to the block reporting tool found at
// badblocks.ethdev.com
func ReportBlock(block *types.Block, err error) {
func ReportBlock(block *data.Block, err error) {
if DisableBadBlockReporting {
return
}

View file

@ -24,7 +24,7 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
@ -81,9 +81,9 @@ var (
func genValueTx(nbytes int) func(int, *BlockGen) {
return func(i int, gen *BlockGen) {
toaddr := common.Address{}
data := make([]byte, nbytes)
gas := IntrinsicGas(data)
tx, _ := types.NewTransaction(gen.TxNonce(benchRootAddr), toaddr, big.NewInt(1), gas, nil, data).SignECDSA(benchRootKey)
extraData := make([]byte, nbytes)
gas := IntrinsicGas(extraData)
tx, _ := data.NewTransaction(gen.TxNonce(benchRootAddr), toaddr, big.NewInt(1), gas, nil, extraData).SignECDSA(benchRootKey)
gen.AddTx(tx)
}
}
@ -115,7 +115,7 @@ func genTxRing(naccounts int) func(int, *BlockGen) {
break
}
to := (from + 1) % naccounts
tx := types.NewTransaction(
tx := data.NewTransaction(
gen.TxNonce(ringAddrs[from]),
ringAddrs[to],
benchRootFunds,

View file

@ -23,8 +23,8 @@ import (
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
@ -96,7 +96,7 @@ func NewBlockProcessor(db ethdb.Database, pow pow.PoW, blockchain *BlockChain, e
return sm
}
func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *data.Block, transientProcess bool) (receipts data.Receipts, err error) {
gp := new(GasPool).AddGas(block.GasLimit())
if glog.V(logger.Core) {
glog.Infof("%x: gas (+ %v)", block.Coinbase(), gp)
@ -111,7 +111,7 @@ func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block
return receipts, nil
}
func (self *BlockProcessor) ApplyTransaction(gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
func (self *BlockProcessor) ApplyTransaction(gp *GasPool, statedb *state.StateDB, header *data.Header, tx *data.Transaction, usedGas *big.Int, transientProcess bool) (*data.Receipt, *big.Int, error) {
_, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, header), tx, gp)
if err != nil {
return nil, nil, err
@ -119,7 +119,7 @@ func (self *BlockProcessor) ApplyTransaction(gp *GasPool, statedb *state.StateDB
// Update the state with pending changes
usedGas.Add(usedGas, gas)
receipt := types.NewReceipt(statedb.IntermediateRoot().Bytes(), usedGas)
receipt := data.NewReceipt(statedb.IntermediateRoot().Bytes(), usedGas)
receipt.TxHash = tx.Hash()
receipt.GasUsed = new(big.Int).Set(gas)
if MessageCreatesContract(tx) {
@ -129,7 +129,7 @@ func (self *BlockProcessor) ApplyTransaction(gp *GasPool, statedb *state.StateDB
logs := statedb.GetLogs(tx.Hash())
receipt.Logs = logs
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
receipt.Bloom = data.CreateBloom(data.Receipts{receipt})
glog.V(logger.Debug).Infoln(receipt)
@ -145,9 +145,9 @@ func (self *BlockProcessor) BlockChain() *BlockChain {
return self.bc
}
func (self *BlockProcessor) ApplyTransactions(gp *GasPool, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, error) {
func (self *BlockProcessor) ApplyTransactions(gp *GasPool, statedb *state.StateDB, block *data.Block, txs data.Transactions, transientProcess bool) (data.Receipts, error) {
var (
receipts types.Receipts
receipts data.Receipts
totalUsedGas = big.NewInt(0)
err error
cumulativeSum = new(big.Int)
@ -181,7 +181,7 @@ func (self *BlockProcessor) ApplyTransactions(gp *GasPool, statedb *state.StateD
return receipts, err
}
func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs vm.Logs, err error) {
func (sm *BlockProcessor) RetryProcess(block *data.Block) (logs vm.Logs, err error) {
// Processing a blocks may never happen simultaneously
sm.mutex.Lock()
defer sm.mutex.Unlock()
@ -206,7 +206,7 @@ func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs vm.Logs, err er
// Process block will attempt to process the given block's transactions and applies them
// on top of the block's parent state (given it exists) and will return wether it was
// successful or not.
func (sm *BlockProcessor) Process(block *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
func (sm *BlockProcessor) Process(block *data.Block) (logs vm.Logs, receipts data.Receipts, err error) {
// Processing a blocks may never happen simultaneously
sm.mutex.Lock()
defer sm.mutex.Unlock()
@ -224,7 +224,7 @@ func (sm *BlockProcessor) Process(block *types.Block) (logs vm.Logs, receipts ty
return nil, nil, ParentError(block.ParentHash())
}
func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
func (sm *BlockProcessor) processWithParent(block, parent *data.Block) (logs vm.Logs, receipts data.Receipts, err error) {
// Create a new state based on the parent's root (e.g., create copy)
state, err := state.New(parent.Root(), sm.chainDb)
if err != nil {
@ -251,7 +251,7 @@ func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs vm
// Validate the received block's bloom with the one derived from the generated receipts.
// For valid blocks this should always validate to true.
rbloom := types.CreateBloom(receipts)
rbloom := data.CreateBloom(receipts)
if rbloom != header.Bloom {
err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
return
@ -259,21 +259,21 @@ func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs vm
// The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
// can be used by light clients to make sure they've received the correct Txs
txSha := types.DeriveSha(txs)
txSha := data.DeriveSha(txs)
if txSha != header.TxHash {
err = fmt.Errorf("invalid transaction root hash. received=%x calculated=%x", header.TxHash, txSha)
return
}
// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
receiptSha := types.DeriveSha(receipts)
receiptSha := data.DeriveSha(receipts)
if receiptSha != header.ReceiptHash {
err = fmt.Errorf("invalid receipt root hash. received=%x calculated=%x", header.ReceiptHash, receiptSha)
return
}
// Verify UncleHash before running other uncle validations
unclesSha := types.CalcUncleHash(uncles)
unclesSha := data.CalcUncleHash(uncles)
if unclesSha != header.UncleHash {
err = fmt.Errorf("invalid uncles root hash. received=%x calculated=%x", header.UncleHash, unclesSha)
return
@ -309,7 +309,7 @@ var (
// mining reward. The total reward consists of the static block reward
// and rewards for included uncles. The coinbase of each uncle block is
// also rewarded.
func AccumulateRewards(statedb *state.StateDB, header *types.Header, uncles []*types.Header) {
func AccumulateRewards(statedb *state.StateDB, header *data.Header, uncles []*data.Header) {
reward := new(big.Int).Set(BlockReward)
r := new(big.Int)
for _, uncle := range uncles {
@ -325,9 +325,9 @@ func AccumulateRewards(statedb *state.StateDB, header *types.Header, uncles []*t
statedb.AddBalance(header.Coinbase, reward)
}
func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *types.Block) error {
func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *data.Block) error {
uncles := set.New()
ancestors := make(map[common.Hash]*types.Block)
ancestors := make(map[common.Hash]*data.Block)
for _, ancestor := range sm.bc.GetBlocksFromHash(block.ParentHash(), 7) {
ancestors[ancestor.Hash()] = ancestor
// Include ancestors uncles in the uncle set. Uncles must be unique.
@ -368,7 +368,7 @@ func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *ty
}
// GetBlockReceipts returns the receipts beloniging to the block hash
func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) data.Receipts {
if block := sm.BlockChain().GetBlock(bhash); block != nil {
return GetBlockReceipts(sm.chainDb, block.Hash())
}
@ -379,7 +379,7 @@ func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
// GetLogs returns the logs of the given block. This method is using a two step approach
// where it tries to get it from the (updated) method which gets them from the receipts or
// the depricated way by re-processing the block.
func (sm *BlockProcessor) GetLogs(block *types.Block) (logs vm.Logs, err error) {
func (sm *BlockProcessor) GetLogs(block *data.Block) (logs vm.Logs, err error) {
receipts := GetBlockReceipts(sm.chainDb, block.Hash())
// coalesce logs
for _, receipt := range receipts {
@ -390,7 +390,7 @@ func (sm *BlockProcessor) GetLogs(block *types.Block) (logs vm.Logs, err error)
// ValidateHeader verifies the validity of a header, relying on the database and
// POW behind the block processor.
func (sm *BlockProcessor) ValidateHeader(header *types.Header, checkPow, uncle bool) error {
func (sm *BlockProcessor) ValidateHeader(header *data.Header, checkPow, uncle bool) error {
// Short circuit if the header's already known or its parent missing
if sm.bc.HasHeader(header.Hash()) {
return nil
@ -404,7 +404,7 @@ func (sm *BlockProcessor) ValidateHeader(header *types.Header, checkPow, uncle b
// ValidateHeaderWithParent verifies the validity of a header, relying on the database and
// POW behind the block processor.
func (sm *BlockProcessor) ValidateHeaderWithParent(header, parent *types.Header, checkPow, uncle bool) error {
func (sm *BlockProcessor) ValidateHeaderWithParent(header, parent *data.Header, checkPow, uncle bool) error {
if sm.bc.HasHeader(header.Hash()) {
return nil
}
@ -413,7 +413,7 @@ func (sm *BlockProcessor) ValidateHeaderWithParent(header, parent *types.Header,
// See YP section 4.3.4. "Block Header Validity"
// Validates a header. Returns an error if the header is invalid.
func ValidateHeader(pow pow.PoW, header *types.Header, parent *types.Header, checkPow, uncle bool) error {
func ValidateHeader(pow pow.PoW, header *data.Header, parent *data.Header, checkPow, uncle bool) error {
if big.NewInt(int64(len(header.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
return fmt.Errorf("Header extra data too long (%d)", len(header.Extra))
}
@ -452,7 +452,7 @@ func ValidateHeader(pow pow.PoW, header *types.Header, parent *types.Header, che
if checkPow {
// Verify the nonce of the header. Return an error if it's not valid
if !pow.Verify(types.NewBlockWithHeader(header)) {
if !pow.Verify(data.NewBlockWithHeader(header)) {
return &BlockNonceErr{Hash: header.Hash(), Number: header.Number, Nonce: header.Nonce.Uint64()}
}
}

View file

@ -22,8 +22,8 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
@ -69,7 +69,7 @@ func TestPutReceipt(t *testing.T) {
var hash common.Hash
hash[0] = 2
receipt := new(types.Receipt)
receipt := new(data.Receipt)
receipt.Logs = vm.Logs{&vm.Log{
Address: addr,
Topics: []common.Hash{hash},
@ -81,7 +81,7 @@ func TestPutReceipt(t *testing.T) {
Index: 0,
}}
PutReceipts(db, types.Receipts{receipt})
PutReceipts(db, data.Receipts{receipt})
receipt = GetReceipt(db, common.Hash{})
if receipt == nil {
t.Error("expected to get 1 receipt, got none.")

View file

@ -31,8 +31,8 @@ import (
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
@ -65,18 +65,18 @@ const (
type BlockChain struct {
chainDb ethdb.Database
processor types.BlockProcessor
processor data.BlockProcessor
eventMux *event.TypeMux
genesisBlock *types.Block
genesisBlock *data.Block
// Last known total difficulty
mu sync.RWMutex
chainmu sync.RWMutex
tsmu sync.RWMutex
checkpoint int // checkpoint counts towards the new checkpoint
currentHeader *types.Header // Current head of the header chain (may be above the block chain!)
currentBlock *types.Block // Current head of the block chain
currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!)
currentHeader *data.Header // Current head of the header chain (may be above the block chain!)
currentBlock *data.Block // Current head of the block chain
currentFastBlock *data.Block // Current head of the fast-sync chain (may be above the block chain!)
headerCache *lru.Cache // Cache for the most recent block headers
bodyCache *lru.Cache // Cache for the most recent block bodies
@ -308,7 +308,7 @@ func (self *BlockChain) LastBlockHash() common.Hash {
// CurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the blockchain's internal cache.
func (self *BlockChain) CurrentHeader() *types.Header {
func (self *BlockChain) CurrentHeader() *data.Header {
self.mu.RLock()
defer self.mu.RUnlock()
@ -317,7 +317,7 @@ func (self *BlockChain) CurrentHeader() *types.Header {
// CurrentBlock retrieves the current head block of the canonical chain. The
// block is retrieved from the blockchain's internal cache.
func (self *BlockChain) CurrentBlock() *types.Block {
func (self *BlockChain) CurrentBlock() *data.Block {
self.mu.RLock()
defer self.mu.RUnlock()
@ -326,7 +326,7 @@ func (self *BlockChain) CurrentBlock() *types.Block {
// CurrentFastBlock retrieves the current fast-sync head block of the canonical
// chain. The block is retrieved from the blockchain's internal cache.
func (self *BlockChain) CurrentFastBlock() *types.Block {
func (self *BlockChain) CurrentFastBlock() *data.Block {
self.mu.RLock()
defer self.mu.RUnlock()
@ -340,7 +340,7 @@ func (self *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesis
return self.GetTd(self.currentBlock.Hash()), self.currentBlock.Hash(), self.genesisBlock.Hash()
}
func (self *BlockChain) SetProcessor(proc types.BlockProcessor) {
func (self *BlockChain) SetProcessor(proc data.BlockProcessor) {
self.processor = proc
}
@ -355,7 +355,7 @@ func (bc *BlockChain) Reset() {
// ResetWithGenesisBlock purges the entire blockchain, restoring it to the
// specified genesis state.
func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) {
func (bc *BlockChain) ResetWithGenesisBlock(genesis *data.Block) {
// Dump the entire block chain and purge the caches
bc.SetHead(0)
@ -415,7 +415,7 @@ func (self *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
// from pointing to a possibly old canonical chain (i.e. side chain by now).
//
// Note, this function assumes that the `mu` mutex is held!
func (bc *BlockChain) insert(block *types.Block) {
func (bc *BlockChain) insert(block *data.Block) {
// Add the block to the canonical chain number scheme and mark as the head
if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
glog.Fatalf("failed to insert block number: %v", err)
@ -436,7 +436,7 @@ func (bc *BlockChain) insert(block *types.Block) {
}
// Accessors
func (bc *BlockChain) Genesis() *types.Block {
func (bc *BlockChain) Genesis() *data.Block {
return bc.genesisBlock
}
@ -448,10 +448,10 @@ func (bc *BlockChain) HasHeader(hash common.Hash) bool {
// GetHeader retrieves a block header from the database by hash, caching it if
// found.
func (self *BlockChain) GetHeader(hash common.Hash) *types.Header {
func (self *BlockChain) GetHeader(hash common.Hash) *data.Header {
// Short circuit if the header's already in the cache, retrieve otherwise
if header, ok := self.headerCache.Get(hash); ok {
return header.(*types.Header)
return header.(*data.Header)
}
header := GetHeader(self.chainDb, hash)
if header == nil {
@ -464,7 +464,7 @@ func (self *BlockChain) GetHeader(hash common.Hash) *types.Header {
// GetHeaderByNumber retrieves a block header from the database by number,
// caching it (associated with its hash) if found.
func (self *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
func (self *BlockChain) GetHeaderByNumber(number uint64) *data.Header {
hash := GetCanonicalHash(self.chainDb, number)
if hash == (common.Hash{}) {
return nil
@ -474,10 +474,10 @@ func (self *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
// GetBody retrieves a block body (transactions and uncles) from the database by
// hash, caching it if found.
func (self *BlockChain) GetBody(hash common.Hash) *types.Body {
func (self *BlockChain) GetBody(hash common.Hash) *data.Body {
// Short circuit if the body's already in the cache, retrieve otherwise
if cached, ok := self.bodyCache.Get(hash); ok {
body := cached.(*types.Body)
body := cached.(*data.Body)
return body
}
body := GetBody(self.chainDb, hash)
@ -528,10 +528,10 @@ func (bc *BlockChain) HasBlock(hash common.Hash) bool {
}
// GetBlock retrieves a block from the database by hash, caching it if found.
func (self *BlockChain) GetBlock(hash common.Hash) *types.Block {
func (self *BlockChain) GetBlock(hash common.Hash) *data.Block {
// Short circuit if the block's already in the cache, retrieve otherwise
if block, ok := self.blockCache.Get(hash); ok {
return block.(*types.Block)
return block.(*data.Block)
}
block := GetBlock(self.chainDb, hash)
if block == nil {
@ -544,7 +544,7 @@ func (self *BlockChain) GetBlock(hash common.Hash) *types.Block {
// GetBlockByNumber retrieves a block from the database by number, caching it
// (associated with its hash) if found.
func (self *BlockChain) GetBlockByNumber(number uint64) *types.Block {
func (self *BlockChain) GetBlockByNumber(number uint64) *data.Block {
hash := GetCanonicalHash(self.chainDb, number)
if hash == (common.Hash{}) {
return nil
@ -576,7 +576,7 @@ func (self *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []c
// [deprecated by eth/62]
// GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
func (self *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
func (self *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*data.Block) {
for i := 0; i < n; i++ {
block := self.GetBlock(hash)
if block == nil {
@ -590,8 +590,8 @@ func (self *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*ty
// GetUnclesInChain retrieves all the uncles from a given block backwards until
// a specific distance is reached.
func (self *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
uncles := []*types.Header{}
func (self *BlockChain) GetUnclesInChain(block *data.Block, length int) []*data.Header {
uncles := []*data.Header{}
for i := 0; block != nil && i < length; i++ {
uncles = append(uncles, block.Uncles()...)
block = self.GetBlock(block.ParentHash())
@ -612,13 +612,13 @@ func (bc *BlockChain) Stop() {
}
func (self *BlockChain) procFutureBlocks() {
blocks := make([]*types.Block, self.futureBlocks.Len())
blocks := make([]*data.Block, self.futureBlocks.Len())
for i, hash := range self.futureBlocks.Keys() {
block, _ := self.futureBlocks.Get(hash)
blocks[i] = block.(*types.Block)
blocks[i] = block.(*data.Block)
}
if len(blocks) > 0 {
types.BlockBy(types.Number).Sort(blocks)
data.BlockBy(data.Number).Sort(blocks)
self.InsertChain(blocks)
}
}
@ -641,7 +641,7 @@ const (
// without the real blocks. Hence, writing headers directly should only be done
// in two scenarios: pure-header mode of operation (light clients), or properly
// separated header/block phases (non-archive clients).
func (self *BlockChain) writeHeader(header *types.Header) error {
func (self *BlockChain) writeHeader(header *data.Header) error {
self.wg.Add(1)
defer self.wg.Done()
@ -675,7 +675,7 @@ func (self *BlockChain) writeHeader(header *types.Header) error {
if err := WriteHeadHeaderHash(self.chainDb, header.Hash()); err != nil {
glog.Fatalf("failed to insert head header hash: %v", err)
}
self.currentHeader = types.CopyHeader(header)
self.currentHeader = data.CopyHeader(header)
}
// Irrelevant of the canonical status, write the header itself to the database
if err := WriteTd(self.chainDb, header.Hash(), td); err != nil {
@ -695,7 +695,7 @@ func (self *BlockChain) writeHeader(header *types.Header) error {
// should be done or not. The reason behind the optional check is because some
// of the header retrieval mechanisms already need to verfy nonces, as well as
// because nonces can be verified sparsely, not needing to check each.
func (self *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
func (self *BlockChain) InsertHeaderChain(chain []*data.Header, checkFreq int) (int, error) {
self.wg.Add(1)
defer self.wg.Done()
@ -834,7 +834,7 @@ func (self *BlockChain) Rollback(chain []common.Hash) {
// InsertReceiptChain attempts to complete an already existing header chain with
// transaction and receipt data.
func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
func (self *BlockChain) InsertReceiptChain(blockChain data.Blocks, receiptChain []data.Receipts) (int, error) {
self.wg.Add(1)
defer self.wg.Done()
@ -900,7 +900,7 @@ func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain
}
}
// Write all the data out into the database
if err := WriteBody(self.chainDb, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
if err := WriteBody(self.chainDb, block.Hash(), &data.Body{block.Transactions(), block.Uncles()}); err != nil {
errs[index] = fmt.Errorf("failed to write block body: %v", err)
atomic.AddInt32(&failed, 1)
glog.Fatal(errs[index])
@ -964,7 +964,7 @@ func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain
}
// WriteBlock writes the block to the chain.
func (self *BlockChain) WriteBlock(block *types.Block) (status writeStatus, err error) {
func (self *BlockChain) WriteBlock(block *data.Block) (status writeStatus, err error) {
self.wg.Add(1)
defer self.wg.Done()
@ -1007,7 +1007,7 @@ func (self *BlockChain) WriteBlock(block *types.Block) (status writeStatus, err
// InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. It an error is returned
// it will return the index number of the failing block as well an error describing what went wrong (for possible errors see core/errors.go).
func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
func (self *BlockChain) InsertChain(chain data.Blocks) (int, error) {
self.wg.Add(1)
defer self.wg.Done()
@ -1142,13 +1142,13 @@ func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
// reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
// to be part of the new canonical chain and accumulates potential missing transactions and post an
// event about them
func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
func (self *BlockChain) reorg(oldBlock, newBlock *data.Block) error {
var (
newChain types.Blocks
commonBlock *types.Block
newChain data.Blocks
commonBlock *data.Block
oldStart = oldBlock
newStart = newBlock
deletedTxs types.Transactions
deletedTxs data.Transactions
)
// first reduce whoever is higher bound
@ -1193,7 +1193,7 @@ func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
glog.Infof("Chain split detected @ %x. Reorganising chain from #%v %x to %x", commonHash[:4], numSplit, oldStart.Hash().Bytes()[:4], newStart.Hash().Bytes()[:4])
}
var addedTxs types.Transactions
var addedTxs data.Transactions
// insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
for _, block := range newChain {
// insert the block in the canonical way, re-writing history
@ -1216,7 +1216,7 @@ func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
}
// calculate the difference between deleted and added transactions
diff := types.TxDifference(deletedTxs, addedTxs)
diff := data.TxDifference(deletedTxs, addedTxs)
// When transactions get deleted from the database that means the
// receipts that were created in the fork must also be deleted
for _, tx := range diff {
@ -1258,7 +1258,7 @@ func (self *BlockChain) update() {
}
}
func blockErr(block *types.Block, err error) {
func blockErr(block *data.Block, err error) {
if glog.V(logger.Error) {
glog.Errorf("Bad block #%v (%s)\n", block.Number(), block.Hash().Hex())
glog.Errorf(" %v", err)

View file

@ -28,7 +28,7 @@ import (
"github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
@ -84,8 +84,8 @@ func testFork(t *testing.T, processor *BlockProcessor, i, n int, full bool, comp
}
// Extend the newly created chain
var (
blockChainB []*types.Block
headerChainB []*types.Header
blockChainB []*data.Block
headerChainB []*data.Header
)
if full {
blockChainB = makeBlockChain(processor2.bc.CurrentBlock(), n, db, forkSeed)
@ -127,7 +127,7 @@ func printChain(bc *BlockChain) {
// testBlockChainImport tries to process a chain of blocks, writing them into
// the database if successful.
func testBlockChainImport(chain []*types.Block, processor *BlockProcessor) error {
func testBlockChainImport(chain []*data.Block, processor *BlockProcessor) error {
for _, block := range chain {
// Try and process the block
if _, _, err := processor.Process(block); err != nil {
@ -147,7 +147,7 @@ func testBlockChainImport(chain []*types.Block, processor *BlockProcessor) error
// testHeaderChainImport tries to process a chain of header, writing them into
// the database if successful.
func testHeaderChainImport(chain []*types.Header, processor *BlockProcessor) error {
func testHeaderChainImport(chain []*data.Header, processor *BlockProcessor) error {
for _, header := range chain {
// Try and validate the header
if err := processor.ValidateHeader(header, false, false); err != nil {
@ -162,14 +162,14 @@ func testHeaderChainImport(chain []*types.Header, processor *BlockProcessor) err
return nil
}
func loadChain(fn string, t *testing.T) (types.Blocks, error) {
func loadChain(fn string, t *testing.T) (data.Blocks, error) {
fh, err := os.OpenFile(filepath.Join("..", "_data", fn), os.O_RDONLY, os.ModePerm)
if err != nil {
return nil, err
}
defer fh.Close()
var chain types.Blocks
var chain data.Blocks
if err := rlp.Decode(fh, &chain); err != nil {
return nil, err
}
@ -177,7 +177,7 @@ func loadChain(fn string, t *testing.T) (types.Blocks, error) {
return chain, nil
}
func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) {
func insertChain(done chan bool, blockchain *BlockChain, chain data.Blocks, t *testing.T) {
_, err := blockchain.InsertChain(chain)
if err != nil {
fmt.Println(err)
@ -375,7 +375,7 @@ func TestChainMultipleInsertions(t *testing.T) {
db, _ := ethdb.NewMemDatabase()
const max = 4
chains := make([]types.Blocks, max)
chains := make([]data.Blocks, max)
var longest int
for i := 0; i < max; i++ {
var err error
@ -415,42 +415,42 @@ func TestChainMultipleInsertions(t *testing.T) {
type bproc struct{}
func (bproc) Process(*types.Block) (vm.Logs, types.Receipts, error) { return nil, nil, nil }
func (bproc) ValidateHeader(*types.Header, bool, bool) error { return nil }
func (bproc) ValidateHeaderWithParent(*types.Header, *types.Header, bool, bool) error { return nil }
func (bproc) Process(*data.Block) (vm.Logs, data.Receipts, error) { return nil, nil, nil }
func (bproc) ValidateHeader(*data.Header, bool, bool) error { return nil }
func (bproc) ValidateHeaderWithParent(*data.Header, *data.Header, bool, bool) error { return nil }
func makeHeaderChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Header {
func makeHeaderChainWithDiff(genesis *data.Block, d []int, seed byte) []*data.Header {
blocks := makeBlockChainWithDiff(genesis, d, seed)
headers := make([]*types.Header, len(blocks))
headers := make([]*data.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}
return headers
}
func makeBlockChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Block {
var chain []*types.Block
func makeBlockChainWithDiff(genesis *data.Block, d []int, seed byte) []*data.Block {
var chain []*data.Block
for i, difficulty := range d {
header := &types.Header{
header := &data.Header{
Coinbase: common.Address{seed},
Number: big.NewInt(int64(i + 1)),
Difficulty: big.NewInt(int64(difficulty)),
UncleHash: types.EmptyUncleHash,
TxHash: types.EmptyRootHash,
ReceiptHash: types.EmptyRootHash,
UncleHash: data.EmptyUncleHash,
TxHash: data.EmptyRootHash,
ReceiptHash: data.EmptyRootHash,
}
if i == 0 {
header.ParentHash = genesis.Hash()
} else {
header.ParentHash = chain[i-1].Hash()
}
block := types.NewBlockWithHeader(header)
block := data.NewBlockWithHeader(header)
chain = append(chain, block)
}
return chain
}
func chm(genesis *types.Block, db ethdb.Database) *BlockChain {
func chm(genesis *data.Block, db ethdb.Database) *BlockChain {
var eventMux event.TypeMux
bc := &BlockChain{chainDb: db, genesisBlock: genesis, eventMux: &eventMux, pow: FakePow{}, rand: rand.New(rand.NewSource(0))}
bc.headerCache, _ = lru.New(100)
@ -694,7 +694,7 @@ func TestFastVsFullChains(t *testing.T) {
// If the block number is multiple of 3, send a few bonus transactions to the miner
if i%3 == 2 {
for j := 0; j < i%4+1; j++ {
tx, err := types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key)
tx, err := data.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key)
if err != nil {
panic(err)
}
@ -703,7 +703,7 @@ func TestFastVsFullChains(t *testing.T) {
}
// If the block number is a multiple of 5, add a few bonus uncles to the block
if i%5 == 5 {
block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
block.AddUncle(&data.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
}
})
// Import the chain as an archive node for the comparison baseline
@ -722,7 +722,7 @@ func TestFastVsFullChains(t *testing.T) {
fast, _ := NewBlockChain(fastDb, FakePow{}, new(event.TypeMux))
fast.SetProcessor(NewBlockProcessor(fastDb, FakePow{}, fast, new(event.TypeMux)))
headers := make([]*types.Header, len(blocks))
headers := make([]*data.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}
@ -744,12 +744,12 @@ func TestFastVsFullChains(t *testing.T) {
}
if fblock, ablock := fast.GetBlock(hash), archive.GetBlock(hash); fblock.Hash() != ablock.Hash() {
t.Errorf("block #%d [%x]: block mismatch: have %v, want %v", num, hash, fblock, ablock)
} else if types.DeriveSha(fblock.Transactions()) != types.DeriveSha(ablock.Transactions()) {
} else if data.DeriveSha(fblock.Transactions()) != data.DeriveSha(ablock.Transactions()) {
t.Errorf("block #%d [%x]: transactions mismatch: have %v, want %v", num, hash, fblock.Transactions(), ablock.Transactions())
} else if types.CalcUncleHash(fblock.Uncles()) != types.CalcUncleHash(ablock.Uncles()) {
} else if data.CalcUncleHash(fblock.Uncles()) != data.CalcUncleHash(ablock.Uncles()) {
t.Errorf("block #%d [%x]: uncles mismatch: have %v, want %v", num, hash, fblock.Uncles(), ablock.Uncles())
}
if freceipts, areceipts := GetBlockReceipts(fastDb, hash), GetBlockReceipts(archiveDb, hash); types.DeriveSha(freceipts) != types.DeriveSha(areceipts) {
if freceipts, areceipts := GetBlockReceipts(fastDb, hash), GetBlockReceipts(archiveDb, hash); data.DeriveSha(freceipts) != data.DeriveSha(areceipts) {
t.Errorf("block #%d [%x]: receipts mismatch: have %v, want %v", num, hash, freceipts, areceipts)
}
}
@ -812,7 +812,7 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
fast, _ := NewBlockChain(fastDb, FakePow{}, new(event.TypeMux))
fast.SetProcessor(NewBlockProcessor(fastDb, FakePow{}, fast, new(event.TypeMux)))
headers := make([]*types.Header, len(blocks))
headers := make([]*data.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}
@ -862,30 +862,30 @@ func TestChainTxReorgs(t *testing.T) {
// Create two transactions shared between the chains:
// - postponed: transaction included at a later block in the forked chain
// - swapped: transaction included at the same block number in the forked chain
postponed, _ := types.NewTransaction(0, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
swapped, _ := types.NewTransaction(1, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
postponed, _ := data.NewTransaction(0, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
swapped, _ := data.NewTransaction(1, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
// Create two transactions that will be dropped by the forked chain:
// - pastDrop: transaction dropped retroactively from a past block
// - freshDrop: transaction dropped exactly at the block where the reorg is detected
var pastDrop, freshDrop *types.Transaction
var pastDrop, freshDrop *data.Transaction
// Create three transactions that will be added in the forked chain:
// - pastAdd: transaction added before the reorganiztion is detected
// - freshAdd: transaction added at the exact block the reorg is detected
// - futureAdd: transaction added after the reorg has already finished
var pastAdd, freshAdd, futureAdd *types.Transaction
var pastAdd, freshAdd, futureAdd *data.Transaction
chain, _ := GenerateChain(genesis, db, 3, func(i int, gen *BlockGen) {
switch i {
case 0:
pastDrop, _ = types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
pastDrop, _ = data.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
gen.AddTx(pastDrop) // This transaction will be dropped in the fork from below the split point
gen.AddTx(postponed) // This transaction will be postponed till block #3 in the fork
case 2:
freshDrop, _ = types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
freshDrop, _ = data.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
gen.AddTx(freshDrop) // This transaction will be dropped in the fork from exactly at the split point
gen.AddTx(swapped) // This transaction will be swapped out at the exact height
@ -905,18 +905,18 @@ func TestChainTxReorgs(t *testing.T) {
chain, _ = GenerateChain(genesis, db, 5, func(i int, gen *BlockGen) {
switch i {
case 0:
pastAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
pastAdd, _ = data.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
gen.AddTx(pastAdd) // This transaction needs to be injected during reorg
case 2:
gen.AddTx(postponed) // This transaction was postponed from block #1 in the original chain
gen.AddTx(swapped) // This transaction was swapped from the exact current spot in the original chain
freshAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
freshAdd, _ = data.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
gen.AddTx(freshAdd) // This transaction will be added exactly at reorg time
case 3:
futureAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
futureAdd, _ = data.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
gen.AddTx(futureAdd) // This transaction will be added after a full reorg
}
})
@ -925,7 +925,7 @@ func TestChainTxReorgs(t *testing.T) {
}
// removed tx
for i, tx := range (types.Transactions{pastDrop, freshDrop}) {
for i, tx := range (data.Transactions{pastDrop, freshDrop}) {
if GetTransaction(db, tx.Hash()) != nil {
t.Errorf("drop %d: tx found while shouldn't have been", i)
}
@ -934,7 +934,7 @@ func TestChainTxReorgs(t *testing.T) {
}
}
// added tx
for i, tx := range (types.Transactions{pastAdd, freshAdd, futureAdd}) {
for i, tx := range (data.Transactions{pastAdd, freshAdd, futureAdd}) {
if GetTransaction(db, tx.Hash()) == nil {
t.Errorf("add %d: expected tx to be found", i)
}
@ -943,7 +943,7 @@ func TestChainTxReorgs(t *testing.T) {
}
}
// shared tx
for i, tx := range (types.Transactions{postponed, swapped}) {
for i, tx := range (data.Transactions{postponed, swapped}) {
if GetTransaction(db, tx.Hash()) == nil {
t.Errorf("share %d: expected tx to be found", i)
}

View file

@ -21,8 +21,8 @@ import (
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/pow"
@ -49,15 +49,15 @@ var (
// See GenerateChain for a detailed explanation.
type BlockGen struct {
i int
parent *types.Block
chain []*types.Block
header *types.Header
parent *data.Block
chain []*data.Block
header *data.Header
statedb *state.StateDB
gasPool *GasPool
txs []*types.Transaction
receipts []*types.Receipt
uncles []*types.Header
txs []*data.Transaction
receipts []*data.Receipt
uncles []*data.Header
}
// SetCoinbase sets the coinbase of the generated block.
@ -86,7 +86,7 @@ func (b *BlockGen) SetExtra(data []byte) {
// further limitations on the content of transactions that can be
// added. Notably, contract code relying on the BLOCKHASH instruction
// will panic during execution.
func (b *BlockGen) AddTx(tx *types.Transaction) {
func (b *BlockGen) AddTx(tx *data.Transaction) {
if b.gasPool == nil {
b.SetCoinbase(common.Address{})
}
@ -96,10 +96,10 @@ func (b *BlockGen) AddTx(tx *types.Transaction) {
}
root := b.statedb.IntermediateRoot()
b.header.GasUsed.Add(b.header.GasUsed, gas)
receipt := types.NewReceipt(root.Bytes(), b.header.GasUsed)
receipt := data.NewReceipt(root.Bytes(), b.header.GasUsed)
logs := b.statedb.GetLogs(tx.Hash())
receipt.Logs = logs
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
receipt.Bloom = data.CreateBloom(data.Receipts{receipt})
b.txs = append(b.txs, tx)
b.receipts = append(b.receipts, receipt)
}
@ -109,7 +109,7 @@ func (b *BlockGen) AddTx(tx *types.Transaction) {
//
// AddUncheckedReceipts will cause consensus failures when used during real
// chain processing. This is best used in conjuction with raw block insertion.
func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
func (b *BlockGen) AddUncheckedReceipt(receipt *data.Receipt) {
b.receipts = append(b.receipts, receipt)
}
@ -123,14 +123,14 @@ func (b *BlockGen) TxNonce(addr common.Address) uint64 {
}
// AddUncle adds an uncle header to the generated block.
func (b *BlockGen) AddUncle(h *types.Header) {
func (b *BlockGen) AddUncle(h *data.Header) {
b.uncles = append(b.uncles, h)
}
// PrevBlock returns a previously generated block by number. It panics if
// num is greater or equal to the number of the block being generated.
// For index -1, PrevBlock returns the parent block given to GenerateChain.
func (b *BlockGen) PrevBlock(index int) *types.Block {
func (b *BlockGen) PrevBlock(index int) *data.Block {
if index >= b.i {
panic("block index out of range")
}
@ -163,13 +163,13 @@ func (b *BlockGen) OffsetTime(seconds int64) {
// 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) {
func GenerateChain(parent *data.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*data.Block, []data.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) {
blocks, receipts := make(data.Blocks, n), make([]data.Receipts, n)
genblock := func(i int, h *data.Header) (*data.Block, data.Receipts) {
b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb}
if gen != nil {
gen(i, b)
@ -180,7 +180,7 @@ func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int,
panic(fmt.Sprintf("state write error: %v", err))
}
h.Root = root
return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts
return data.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts
}
for i := 0; i < n; i++ {
header := makeHeader(parent, statedb)
@ -192,14 +192,14 @@ func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int,
return blocks, receipts
}
func makeHeader(parent *types.Block, state *state.StateDB) *types.Header {
func makeHeader(parent *data.Block, state *state.StateDB) *data.Header {
var time *big.Int
if parent.Time() == nil {
time = big.NewInt(10)
} else {
time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
}
return &types.Header{
return &data.Header{
Root: state.IntermediateRoot(),
ParentHash: parent.Hash(),
Coinbase: parent.Coinbase(),
@ -243,9 +243,9 @@ func newCanonical(n int, full bool) (ethdb.Database, *BlockProcessor, error) {
}
// makeHeaderChain creates a deterministic chain of headers rooted at parent.
func makeHeaderChain(parent *types.Header, n int, db ethdb.Database, seed int) []*types.Header {
blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, db, seed)
headers := make([]*types.Header, len(blocks))
func makeHeaderChain(parent *data.Header, n int, db ethdb.Database, seed int) []*data.Header {
blocks := makeBlockChain(data.NewBlockWithHeader(parent), n, db, seed)
headers := make([]*data.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}
@ -253,7 +253,7 @@ func makeHeaderChain(parent *types.Header, n int, db ethdb.Database, seed int) [
}
// makeBlockChain creates a deterministic chain of blocks rooted at parent.
func makeBlockChain(parent *types.Block, n int, db ethdb.Database, seed int) []*types.Block {
func makeBlockChain(parent *data.Block, n int, db ethdb.Database, seed int) []*data.Block {
blocks, _ := GenerateChain(parent, db, n, func(i int, b *BlockGen) {
b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
})

View file

@ -20,7 +20,7 @@ import (
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
@ -51,13 +51,13 @@ func ExampleGenerateChain() {
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)
tx, _ := data.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)
tx1, _ := data.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
tx2, _ := data.NewTransaction(gen.TxNonce(addr2), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
gen.AddTx(tx1)
gen.AddTx(tx2)
case 2:

View file

@ -19,7 +19,7 @@ package core
import (
"runtime"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/pow"
)
@ -32,10 +32,10 @@ type nonceCheckResult struct {
// verifyNoncesFromHeaders starts a concurrent header nonce verification,
// returning a quit channel to abort the operations and a results channel
// to retrieve the async verifications.
func verifyNoncesFromHeaders(checker pow.PoW, headers []*types.Header) (chan<- struct{}, <-chan nonceCheckResult) {
func verifyNoncesFromHeaders(checker pow.PoW, headers []*data.Header) (chan<- struct{}, <-chan nonceCheckResult) {
items := make([]pow.Block, len(headers))
for i, header := range headers {
items[i] = types.NewBlockWithHeader(header)
items[i] = data.NewBlockWithHeader(header)
}
return verifyNonces(checker, items)
}
@ -43,7 +43,7 @@ func verifyNoncesFromHeaders(checker pow.PoW, headers []*types.Header) (chan<- s
// verifyNoncesFromBlocks starts a concurrent block nonce verification,
// returning a quit channel to abort the operations and a results channel
// to retrieve the async verifications.
func verifyNoncesFromBlocks(checker pow.PoW, blocks []*types.Block) (chan<- struct{}, <-chan nonceCheckResult) {
func verifyNoncesFromBlocks(checker pow.PoW, blocks []*data.Block) (chan<- struct{}, <-chan nonceCheckResult) {
items := make([]pow.Block, len(blocks))
for i, block := range blocks {
items[i] = block

View file

@ -23,7 +23,7 @@ import (
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/pow"
)
@ -62,7 +62,7 @@ func TestPowVerification(t *testing.T) {
genesis = GenesisBlockForTesting(testdb, common.Address{}, new(big.Int))
blocks, _ = GenerateChain(genesis, testdb, 8, nil)
)
headers := make([]*types.Header, len(blocks))
headers := make([]*data.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}
@ -74,13 +74,13 @@ func TestPowVerification(t *testing.T) {
switch {
case full && valid:
_, results = verifyNoncesFromBlocks(FakePow{}, []*types.Block{blocks[i]})
_, results = verifyNoncesFromBlocks(FakePow{}, []*data.Block{blocks[i]})
case full && !valid:
_, results = verifyNoncesFromBlocks(failPow{blocks[i].NumberU64()}, []*types.Block{blocks[i]})
_, results = verifyNoncesFromBlocks(failPow{blocks[i].NumberU64()}, []*data.Block{blocks[i]})
case !full && valid:
_, results = verifyNoncesFromHeaders(FakePow{}, []*types.Header{headers[i]})
_, results = verifyNoncesFromHeaders(FakePow{}, []*data.Header{headers[i]})
case !full && !valid:
_, results = verifyNoncesFromHeaders(failPow{headers[i].Number.Uint64()}, []*types.Header{headers[i]})
_, results = verifyNoncesFromHeaders(failPow{headers[i].Number.Uint64()}, []*data.Header{headers[i]})
}
// Wait for the verification result
select {
@ -117,7 +117,7 @@ func testPowConcurrentVerification(t *testing.T, threads int) {
genesis = GenesisBlockForTesting(testdb, common.Address{}, new(big.Int))
blocks, _ = GenerateChain(genesis, testdb, 8, nil)
)
headers := make([]*types.Header, len(blocks))
headers := make([]*data.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}
@ -188,7 +188,7 @@ func testPowConcurrentAbortion(t *testing.T, threads int) {
genesis = GenesisBlockForTesting(testdb, common.Address{}, new(big.Int))
blocks, _ = GenerateChain(genesis, testdb, 1024, nil)
)
headers := make([]*types.Header, len(blocks))
headers := make([]*data.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}

View file

@ -23,7 +23,7 @@ import (
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
@ -87,7 +87,7 @@ func CalcDifficulty(time, parentTime uint64, parentNumber, parentDiff *big.Int)
// CalcGasLimit computes the gas limit of the next block after parent.
// The result may be modified by the caller.
// This is miner strategy, not consensus protocol.
func CalcGasLimit(parent *types.Block) *big.Int {
func CalcGasLimit(parent *data.Block) *big.Int {
// contrib = (parentGasUsed * 3 / 2) / 1024
contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
contrib = contrib.Div(contrib, big.NewInt(2))
@ -169,13 +169,13 @@ func GetHeaderRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
// GetHeader retrieves the block header corresponding to the hash, nil if none
// found.
func GetHeader(db ethdb.Database, hash common.Hash) *types.Header {
data := GetHeaderRLP(db, hash)
if len(data) == 0 {
func GetHeader(db ethdb.Database, hash common.Hash) *data.Header {
raw := GetHeaderRLP(db, hash)
if len(raw) == 0 {
return nil
}
header := new(types.Header)
if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
header := new(data.Header)
if err := rlp.Decode(bytes.NewReader(raw), header); err != nil {
glog.V(logger.Error).Infof("invalid block header RLP for hash %x: %v", hash, err)
return nil
}
@ -190,13 +190,13 @@ func GetBodyRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
// GetBody retrieves the block body (transactons, uncles) corresponding to the
// hash, nil if none found.
func GetBody(db ethdb.Database, hash common.Hash) *types.Body {
data := GetBodyRLP(db, hash)
if len(data) == 0 {
func GetBody(db ethdb.Database, hash common.Hash) *data.Body {
raw := GetBodyRLP(db, hash)
if len(raw) == 0 {
return nil
}
body := new(types.Body)
if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
body := new(data.Body)
if err := rlp.Decode(bytes.NewReader(raw), body); err != nil {
glog.V(logger.Error).Infof("invalid block body RLP for hash %x: %v", hash, err)
return nil
}
@ -220,7 +220,7 @@ func GetTd(db ethdb.Database, hash common.Hash) *big.Int {
// GetBlock retrieves an entire block corresponding to the hash, assembling it
// back from the stored header and body.
func GetBlock(db ethdb.Database, hash common.Hash) *types.Block {
func GetBlock(db ethdb.Database, hash common.Hash) *data.Block {
// Retrieve the block header and body contents
header := GetHeader(db, hash)
if header == nil {
@ -231,7 +231,7 @@ func GetBlock(db ethdb.Database, hash common.Hash) *types.Block {
return nil
}
// Reassemble the block and return
return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
return data.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
}
// WriteCanonicalHash stores the canonical hash for the given block number.
@ -272,7 +272,7 @@ func WriteHeadFastBlockHash(db ethdb.Database, hash common.Hash) error {
}
// WriteHeader serializes a block header into the database.
func WriteHeader(db ethdb.Database, header *types.Header) error {
func WriteHeader(db ethdb.Database, header *data.Header) error {
data, err := rlp.EncodeToBytes(header)
if err != nil {
return err
@ -287,7 +287,7 @@ func WriteHeader(db ethdb.Database, header *types.Header) error {
}
// WriteBody serializes the body of a block into the database.
func WriteBody(db ethdb.Database, hash common.Hash, body *types.Body) error {
func WriteBody(db ethdb.Database, hash common.Hash, body *data.Body) error {
data, err := rlp.EncodeToBytes(body)
if err != nil {
return err
@ -317,9 +317,9 @@ func WriteTd(db ethdb.Database, hash common.Hash, td *big.Int) error {
}
// WriteBlock serializes a block into the database, header and body separately.
func WriteBlock(db ethdb.Database, block *types.Block) error {
func WriteBlock(db ethdb.Database, block *data.Block) error {
// Store the body first to retain database consistency
if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
if err := WriteBody(db, block.Hash(), &data.Body{block.Transactions(), block.Uncles()}); err != nil {
return err
}
// Store the header too, signaling full block ownership
@ -361,17 +361,17 @@ func DeleteBlock(db ethdb.Database, hash common.Hash) {
// or nil if not found. This method is only used by the upgrade mechanism to
// access the old combined block representation. It will be dropped after the
// network transitions to eth/63.
func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *types.Block {
data, _ := db.Get(append(blockHashPre, hash[:]...))
if len(data) == 0 {
func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *data.Block {
raw, _ := db.Get(append(blockHashPre, hash[:]...))
if len(raw) == 0 {
return nil
}
var block types.StorageBlock
if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
var block data.StorageBlock
if err := rlp.Decode(bytes.NewReader(raw), &block); err != nil {
glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
return nil
}
return (*types.Block)(&block)
return (*data.Block)(&block)
}
// returns a formatted MIP mapped key by adding prefix, canonical number and level
@ -387,12 +387,12 @@ func mipmapKey(num, level uint64) []byte {
// WriteMapmapBloom writes each address included in the receipts' logs to the
// MIP bloom bin.
func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
func WriteMipmapBloom(db ethdb.Database, number uint64, receipts data.Receipts) error {
batch := db.NewBatch()
for _, level := range MIPMapLevels {
key := mipmapKey(number, level)
bloomDat, _ := db.Get(key)
bloom := types.BytesToBloom(bloomDat)
bloom := data.BytesToBloom(bloomDat)
for _, receipt := range receipts {
for _, log := range receipt.Logs {
bloom.Add(log.Address.Big())
@ -408,7 +408,7 @@ func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts)
// GetMipmapBloom returns a bloom filter using the number and level as input
// parameters. For available levels see MIPMapLevels.
func GetMipmapBloom(db ethdb.Database, number, level uint64) types.Bloom {
func GetMipmapBloom(db ethdb.Database, number, level uint64) data.Bloom {
bloomDat, _ := db.Get(mipmapKey(number, level))
return types.BytesToBloom(bloomDat)
return data.BytesToBloom(bloomDat)
}

View file

@ -24,7 +24,7 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/sha3"
@ -88,7 +88,7 @@ func TestHeaderStorage(t *testing.T) {
db, _ := ethdb.NewMemDatabase()
// Create a test header to move around the database and make sure it's really new
header := &types.Header{Extra: []byte("test header")}
header := &data.Header{Extra: []byte("test header")}
if entry := GetHeader(db, header.Hash()); entry != nil {
t.Fatalf("Non existent header returned: %v", entry)
}
@ -123,7 +123,7 @@ func TestBodyStorage(t *testing.T) {
db, _ := ethdb.NewMemDatabase()
// Create a test body to move around the database and make sure it's really new
body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
body := &data.Body{Uncles: []*data.Header{{Extra: []byte("test header")}}}
hasher := sha3.NewKeccak256()
rlp.Encode(hasher, body)
@ -138,7 +138,7 @@ func TestBodyStorage(t *testing.T) {
}
if entry := GetBody(db, hash); entry == nil {
t.Fatalf("Stored body not found")
} else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(types.Transactions(body.Transactions)) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
} else if data.DeriveSha(data.Transactions(entry.Transactions)) != data.DeriveSha(data.Transactions(body.Transactions)) || data.CalcUncleHash(entry.Uncles) != data.CalcUncleHash(body.Uncles) {
t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
}
if entry := GetBodyRLP(db, hash); entry == nil {
@ -163,11 +163,11 @@ func TestBlockStorage(t *testing.T) {
db, _ := ethdb.NewMemDatabase()
// Create a test block to move around the database and make sure it's really new
block := types.NewBlockWithHeader(&types.Header{
block := data.NewBlockWithHeader(&data.Header{
Extra: []byte("test block"),
UncleHash: types.EmptyUncleHash,
TxHash: types.EmptyRootHash,
ReceiptHash: types.EmptyRootHash,
UncleHash: data.EmptyUncleHash,
TxHash: data.EmptyRootHash,
ReceiptHash: data.EmptyRootHash,
})
if entry := GetBlock(db, block.Hash()); entry != nil {
t.Fatalf("Non existent block returned: %v", entry)
@ -194,8 +194,8 @@ func TestBlockStorage(t *testing.T) {
}
if entry := GetBody(db, block.Hash()); entry == nil {
t.Fatalf("Stored body not found")
} else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(block.Transactions()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, &types.Body{block.Transactions(), block.Uncles()})
} else if data.DeriveSha(data.Transactions(entry.Transactions)) != data.DeriveSha(block.Transactions()) || data.CalcUncleHash(entry.Uncles) != data.CalcUncleHash(block.Uncles()) {
t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, &data.Body{block.Transactions(), block.Uncles()})
}
// Delete the block and verify the execution
DeleteBlock(db, block.Hash())
@ -213,11 +213,11 @@ func TestBlockStorage(t *testing.T) {
// Tests that partial block contents don't get reassembled into full blocks.
func TestPartialBlockStorage(t *testing.T) {
db, _ := ethdb.NewMemDatabase()
block := types.NewBlockWithHeader(&types.Header{
block := data.NewBlockWithHeader(&data.Header{
Extra: []byte("test block"),
UncleHash: types.EmptyUncleHash,
TxHash: types.EmptyRootHash,
ReceiptHash: types.EmptyRootHash,
UncleHash: data.EmptyUncleHash,
TxHash: data.EmptyRootHash,
ReceiptHash: data.EmptyRootHash,
})
// Store a header and check that it's not recognized as a block
if err := WriteHeader(db, block.Header()); err != nil {
@ -229,7 +229,7 @@ func TestPartialBlockStorage(t *testing.T) {
DeleteHeader(db, block.Hash())
// Store a body and check that it's not recognized as a block
if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
if err := WriteBody(db, block.Hash(), &data.Body{block.Transactions(), block.Uncles()}); err != nil {
t.Fatalf("Failed to write body into database: %v", err)
}
if entry := GetBlock(db, block.Hash()); entry != nil {
@ -241,7 +241,7 @@ func TestPartialBlockStorage(t *testing.T) {
if err := WriteHeader(db, block.Header()); err != nil {
t.Fatalf("Failed to write header into database: %v", err)
}
if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
if err := WriteBody(db, block.Hash(), &data.Body{block.Transactions(), block.Uncles()}); err != nil {
t.Fatalf("Failed to write body into database: %v", err)
}
if entry := GetBlock(db, block.Hash()); entry == nil {
@ -305,9 +305,9 @@ func TestCanonicalMappingStorage(t *testing.T) {
func TestHeadStorage(t *testing.T) {
db, _ := ethdb.NewMemDatabase()
blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
blockHead := data.NewBlockWithHeader(&data.Header{Extra: []byte("test block header")})
blockFull := data.NewBlockWithHeader(&data.Header{Extra: []byte("test block full")})
blockFast := data.NewBlockWithHeader(&data.Header{Extra: []byte("test block fast")})
// Check that no head entries are in a pristine database
if entry := GetHeadHeaderHash(db); entry != (common.Hash{}) {
@ -344,19 +344,19 @@ func TestHeadStorage(t *testing.T) {
func TestMipmapBloom(t *testing.T) {
db, _ := ethdb.NewMemDatabase()
receipt1 := new(types.Receipt)
receipt1 := new(data.Receipt)
receipt1.Logs = vm.Logs{
&vm.Log{Address: common.BytesToAddress([]byte("test"))},
&vm.Log{Address: common.BytesToAddress([]byte("address"))},
}
receipt2 := new(types.Receipt)
receipt2 := new(data.Receipt)
receipt2.Logs = vm.Logs{
&vm.Log{Address: common.BytesToAddress([]byte("test"))},
&vm.Log{Address: common.BytesToAddress([]byte("address1"))},
}
WriteMipmapBloom(db, 1, types.Receipts{receipt1})
WriteMipmapBloom(db, 2, types.Receipts{receipt2})
WriteMipmapBloom(db, 1, data.Receipts{receipt1})
WriteMipmapBloom(db, 2, data.Receipts{receipt2})
for _, level := range MIPMapLevels {
bloom := GetMipmapBloom(db, 2, level)
@ -367,17 +367,17 @@ func TestMipmapBloom(t *testing.T) {
// reset
db, _ = ethdb.NewMemDatabase()
receipt := new(types.Receipt)
receipt := new(data.Receipt)
receipt.Logs = vm.Logs{
&vm.Log{Address: common.BytesToAddress([]byte("test"))},
}
WriteMipmapBloom(db, 999, types.Receipts{receipt1})
WriteMipmapBloom(db, 999, data.Receipts{receipt1})
receipt = new(types.Receipt)
receipt = new(data.Receipt)
receipt.Logs = vm.Logs{
&vm.Log{Address: common.BytesToAddress([]byte("test 1"))},
}
WriteMipmapBloom(db, 1000, types.Receipts{receipt})
WriteMipmapBloom(db, 1000, data.Receipts{receipt})
bloom := GetMipmapBloom(db, 1000, 1000)
if bloom.TestBytes([]byte("test")) {
@ -404,10 +404,10 @@ func TestMipmapChain(t *testing.T) {
genesis := WriteGenesisBlockForTesting(db, GenesisAccount{addr, big.NewInt(1000000)})
chain, receipts := GenerateChain(genesis, db, 1010, func(i int, gen *BlockGen) {
var receipts types.Receipts
var receipts data.Receipts
switch i {
case 1:
receipt := types.NewReceipt(nil, new(big.Int))
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{
&vm.Log{
Address: addr,
@ -415,12 +415,12 @@ func TestMipmapChain(t *testing.T) {
},
}
gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
case 1000:
receipt := types.NewReceipt(nil, new(big.Int))
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{&vm.Log{Address: addr2}}
gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
}

View file

@ -15,7 +15,7 @@
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package types contains data types related to Ethereum consensus.
package types
package data
import (
"bytes"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
package data
import (
"bytes"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
package data
import (
"fmt"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
package data
import (
"math/big"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
package data
import "github.com/ethereum/go-ethereum/core/vm"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
package data
import (
"bytes"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
package data
import (
"fmt"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
package data
import (
"crypto/ecdsa"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
package data
import (
"bytes"

View file

@ -20,52 +20,52 @@ import (
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/vm"
)
// TxPreEvent is posted when a transaction enters the transaction pool.
type TxPreEvent struct{ Tx *types.Transaction }
type TxPreEvent struct{ Tx *data.Transaction }
// TxPostEvent is posted when a transaction has been processed.
type TxPostEvent struct{ Tx *types.Transaction }
type TxPostEvent struct{ Tx *data.Transaction }
// NewBlockEvent is posted when a block has been imported.
type NewBlockEvent struct{ Block *types.Block }
type NewBlockEvent struct{ Block *data.Block }
// NewMinedBlockEvent is posted when a block has been imported.
type NewMinedBlockEvent struct{ Block *types.Block }
type NewMinedBlockEvent struct{ Block *data.Block }
// RemovedTransactionEvent is posted when a reorg happens
type RemovedTransactionEvent struct{ Txs types.Transactions }
type RemovedTransactionEvent struct{ Txs data.Transactions }
// ChainSplit is posted when a new head is detected
type ChainSplitEvent struct {
Block *types.Block
Block *data.Block
Logs vm.Logs
}
type ChainEvent struct {
Block *types.Block
Block *data.Block
Hash common.Hash
Logs vm.Logs
}
type ChainSideEvent struct {
Block *types.Block
Block *data.Block
Logs vm.Logs
}
type PendingBlockEvent struct {
Block *types.Block
Block *data.Block
Logs vm.Logs
}
type ChainUncleEvent struct {
Block *types.Block
Block *data.Block
}
type ChainHeadEvent struct{ Block *types.Block }
type ChainHeadEvent struct{ Block *data.Block }
type GasPriceChanged struct{ Price *big.Int }

View file

@ -25,8 +25,8 @@ import (
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
@ -34,7 +34,7 @@ import (
)
// WriteGenesisBlock writes the genesis block to the database as block number 0
func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*types.Block, error) {
func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*data.Block, error) {
contents, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
@ -73,8 +73,8 @@ func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*types.Block,
root, stateBatch := statedb.CommitBatch()
difficulty := common.String2Big(genesis.Difficulty)
block := types.NewBlock(&types.Header{
Nonce: types.EncodeNonce(common.String2Big(genesis.Nonce).Uint64()),
block := data.NewBlock(&data.Header{
Nonce: data.EncodeNonce(common.String2Big(genesis.Nonce).Uint64()),
Time: common.String2Big(genesis.Timestamp),
ParentHash: common.HexToHash(genesis.ParentHash),
Extra: common.FromHex(genesis.ExtraData),
@ -117,7 +117,7 @@ func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*types.Block,
// 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 {
func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *data.Block {
statedb, _ := state.New(common.Hash{}, db)
obj := statedb.GetOrNewStateObject(addr)
obj.SetBalance(balance)
@ -125,7 +125,7 @@ func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big
if err != nil {
panic(fmt.Sprintf("cannot write state: %v", err))
}
block := types.NewBlock(&types.Header{
block := data.NewBlock(&data.Header{
Difficulty: params.GenesisDifficulty,
GasLimit: params.GenesisGasLimit,
Root: root,
@ -138,7 +138,7 @@ type GenesisAccount struct {
Balance *big.Int
}
func WriteGenesisBlockForTesting(db ethdb.Database, accounts ...GenesisAccount) *types.Block {
func WriteGenesisBlockForTesting(db ethdb.Database, accounts ...GenesisAccount) *data.Block {
accountJson := "{"
for i, account := range accounts {
if i != 0 {
@ -153,12 +153,12 @@ func WriteGenesisBlockForTesting(db ethdb.Database, accounts ...GenesisAccount)
"gasLimit":"0x%x",
"difficulty":"0x%x",
"alloc": %s
}`, types.EncodeNonce(0), params.GenesisGasLimit.Bytes(), params.GenesisDifficulty.Bytes(), accountJson)
}`, data.EncodeNonce(0), params.GenesisGasLimit.Bytes(), params.GenesisDifficulty.Bytes(), accountJson)
block, _ := WriteGenesisBlock(db, strings.NewReader(testGenesis))
return block
}
func WriteTestNetGenesisBlock(chainDb ethdb.Database, nonce uint64) (*types.Block, error) {
func WriteTestNetGenesisBlock(chainDb ethdb.Database, nonce uint64) (*data.Block, error) {
testGenesis := fmt.Sprintf(`{
"nonce": "0x%x",
"difficulty": "0x20000",
@ -175,11 +175,11 @@ func WriteTestNetGenesisBlock(chainDb ethdb.Database, nonce uint64) (*types.Bloc
"0000000000000000000000000000000000000004": { "balance": "1" },
"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c": { "balance": "1606938044258990275541962092341162602522202993782792835301376" }
}
}`, types.EncodeNonce(nonce))
}`, data.EncodeNonce(nonce))
return WriteGenesisBlock(chainDb, strings.NewReader(testGenesis))
}
func WriteOlympicGenesisBlock(chainDb ethdb.Database, nonce uint64) (*types.Block, error) {
func WriteOlympicGenesisBlock(chainDb ethdb.Database, nonce uint64) (*data.Block, error) {
testGenesis := fmt.Sprintf(`{
"nonce":"0x%x",
"gasLimit":"0x%x",
@ -198,6 +198,6 @@ func WriteOlympicGenesisBlock(chainDb ethdb.Database, nonce uint64) (*types.Bloc
"e6716f9544a56c530d868e4bfbacb172315bdead": {"balance": "1606938044258990275541962092341162602522202993782792835301376"},
"1a26338f0d905e295fccb71fa9ea849ffa12aaf4": {"balance": "1606938044258990275541962092341162602522202993782792835301376"}
}
}`, types.EncodeNonce(nonce), params.GenesisGasLimit.Bytes(), params.GenesisDifficulty.Bytes())
}`, data.EncodeNonce(nonce), params.GenesisGasLimit.Bytes(), params.GenesisDifficulty.Bytes())
return WriteGenesisBlock(chainDb, strings.NewReader(testGenesis))
}

View file

@ -20,7 +20,7 @@ import (
"container/list"
"fmt"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
// "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
@ -35,7 +35,7 @@ type TestManager struct {
db ethdb.Database
txPool *TxPool
blockChain *BlockChain
Blocks []*types.Block
Blocks []*data.Block
}
func (s *TestManager) IsListening() bool {

View file

@ -24,8 +24,8 @@ import (
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
@ -67,14 +67,14 @@ type TxPool struct {
events event.Subscription
mu sync.RWMutex
pending map[common.Hash]*types.Transaction // processable transactions
queue map[common.Address]map[common.Hash]*types.Transaction
pending map[common.Hash]*data.Transaction // processable transactions
queue map[common.Address]map[common.Hash]*data.Transaction
}
func NewTxPool(eventMux *event.TypeMux, currentStateFn stateFn, gasLimitFn func() *big.Int) *TxPool {
pool := &TxPool{
pending: make(map[common.Hash]*types.Transaction),
queue: make(map[common.Address]map[common.Hash]*types.Transaction),
pending: make(map[common.Hash]*data.Transaction),
queue: make(map[common.Address]map[common.Hash]*data.Transaction),
quit: make(chan bool),
eventMux: eventMux,
currentState: currentStateFn,
@ -170,7 +170,7 @@ func (pool *TxPool) Stats() (pending int, queued int) {
// validateTx checks whether a transaction is valid according
// to the consensus rules.
func (pool *TxPool) validateTx(tx *types.Transaction) error {
func (pool *TxPool) validateTx(tx *data.Transaction) error {
// Validate sender
var (
from common.Address
@ -231,7 +231,7 @@ func (pool *TxPool) validateTx(tx *types.Transaction) error {
}
// validate and queue transactions.
func (self *TxPool) add(tx *types.Transaction) error {
func (self *TxPool) add(tx *data.Transaction) error {
hash := tx.Hash()
if self.pending[hash] != nil {
@ -261,16 +261,16 @@ func (self *TxPool) add(tx *types.Transaction) error {
}
// queueTx will queue an unknown transaction
func (self *TxPool) queueTx(hash common.Hash, tx *types.Transaction) {
func (self *TxPool) queueTx(hash common.Hash, tx *data.Transaction) {
from, _ := tx.From() // already validated
if self.queue[from] == nil {
self.queue[from] = make(map[common.Hash]*types.Transaction)
self.queue[from] = make(map[common.Hash]*data.Transaction)
}
self.queue[from][hash] = tx
}
// addTx will add a transaction to the pending (processable queue) list of transactions
func (pool *TxPool) addTx(hash common.Hash, addr common.Address, tx *types.Transaction) {
func (pool *TxPool) addTx(hash common.Hash, addr common.Address, tx *data.Transaction) {
// init delayed since tx pool could have been started before any state sync
if pool.pendingState == nil {
pool.resetState()
@ -290,7 +290,7 @@ func (pool *TxPool) addTx(hash common.Hash, addr common.Address, tx *types.Trans
}
// Add queues a single transaction in the pool if it is valid.
func (self *TxPool) Add(tx *types.Transaction) (err error) {
func (self *TxPool) Add(tx *data.Transaction) (err error) {
self.mu.Lock()
defer self.mu.Unlock()
@ -304,7 +304,7 @@ func (self *TxPool) Add(tx *types.Transaction) (err error) {
}
// AddTransactions attempts to queue all valid transactions in txs.
func (self *TxPool) AddTransactions(txs []*types.Transaction) {
func (self *TxPool) AddTransactions(txs []*data.Transaction) {
self.mu.Lock()
defer self.mu.Unlock()
@ -323,7 +323,7 @@ func (self *TxPool) AddTransactions(txs []*types.Transaction) {
// GetTransaction returns a transaction if it is contained in the pool
// and nil otherwise.
func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
func (tp *TxPool) GetTransaction(hash common.Hash) *data.Transaction {
// check the txs first
if tx, ok := tp.pending[hash]; ok {
return tx
@ -339,7 +339,7 @@ func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
// GetTransactions returns all currently processable transactions.
// The returned slice may be modified by the caller.
func (self *TxPool) GetTransactions() (txs types.Transactions) {
func (self *TxPool) GetTransactions() (txs data.Transactions) {
self.mu.Lock()
defer self.mu.Unlock()
@ -348,7 +348,7 @@ func (self *TxPool) GetTransactions() (txs types.Transactions) {
// invalidate any txs
self.validatePool()
txs = make(types.Transactions, len(self.pending))
txs = make(data.Transactions, len(self.pending))
i := 0
for _, tx := range self.pending {
txs[i] = tx
@ -358,22 +358,22 @@ func (self *TxPool) GetTransactions() (txs types.Transactions) {
}
// GetQueuedTransactions returns all non-processable transactions.
func (self *TxPool) GetQueuedTransactions() types.Transactions {
func (self *TxPool) GetQueuedTransactions() data.Transactions {
self.mu.RLock()
defer self.mu.RUnlock()
var ret types.Transactions
var ret data.Transactions
for _, txs := range self.queue {
for _, tx := range txs {
ret = append(ret, tx)
}
}
sort.Sort(types.TxByNonce{ret})
sort.Sort(data.TxByNonce{ret})
return ret
}
// RemoveTransactions removes all given transactions from the pool.
func (self *TxPool) RemoveTransactions(txs types.Transactions) {
func (self *TxPool) RemoveTransactions(txs data.Transactions) {
self.mu.Lock()
defer self.mu.Unlock()
for _, tx := range txs {
@ -483,7 +483,7 @@ type txQueue []txQueueEntry
type txQueueEntry struct {
hash common.Hash
addr common.Address
*types.Transaction
*data.Transaction
}
func (q txQueue) Len() int { return len(q) }

View file

@ -22,15 +22,15 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
)
func transaction(nonce uint64, gaslimit *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
tx, _ := types.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, big.NewInt(1), nil).SignECDSA(key)
func transaction(nonce uint64, gaslimit *big.Int, key *ecdsa.PrivateKey) *data.Transaction {
tx, _ := data.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, big.NewInt(1), nil).SignECDSA(key)
return tx
}
@ -149,7 +149,7 @@ func TestRemoveTx(t *testing.T) {
func TestNegativeValue(t *testing.T) {
pool, key := setupTxPool()
tx, _ := types.NewTransaction(0, common.Address{}, big.NewInt(-1), big.NewInt(100), big.NewInt(1), nil).SignECDSA(key)
tx, _ := data.NewTransaction(0, common.Address{}, big.NewInt(-1), big.NewInt(100), big.NewInt(1), nil).SignECDSA(key)
from, _ := tx.From()
currentState, _ := pool.currentState()
currentState.AddBalance(from, big.NewInt(1))
@ -175,7 +175,7 @@ func TestTransactionChainFork(t *testing.T) {
if err := pool.add(tx); err != nil {
t.Error("didn't expect error", err)
}
pool.RemoveTransactions([]*types.Transaction{tx})
pool.RemoveTransactions([]*data.Transaction{tx})
// reset the pool's internal state
resetState()
@ -255,7 +255,7 @@ func TestRemovedTxEvent(t *testing.T) {
from, _ := tx.From()
currentState, _ := pool.currentState()
currentState.AddBalance(from, big.NewInt(1000000000000))
pool.eventMux.Post(RemovedTransactionEvent{types.Transactions{tx}})
pool.eventMux.Post(RemovedTransactionEvent{data.Transactions{tx}})
pool.eventMux.Post(ChainHeadEvent{nil})
if len(pool.pending) != 1 {
t.Error("expected 1 pending tx, got", len(pool.pending))

View file

@ -20,7 +20,7 @@ import (
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
@ -34,7 +34,7 @@ var (
)
// PutTransactions stores the transactions in the given database
func PutTransactions(db ethdb.Database, block *types.Block, txs types.Transactions) error {
func PutTransactions(db ethdb.Database, block *data.Block, txs data.Transactions) error {
batch := db.NewBatch()
for i, tx := range block.Transactions() {
@ -71,11 +71,11 @@ func DeleteTransaction(db ethdb.Database, txHash common.Hash) {
db.Delete(txHash[:])
}
func GetTransaction(db ethdb.Database, txhash common.Hash) *types.Transaction {
data, _ := db.Get(txhash[:])
if len(data) != 0 {
var tx types.Transaction
if err := rlp.DecodeBytes(data, &tx); err != nil {
func GetTransaction(db ethdb.Database, txhash common.Hash) *data.Transaction {
raw, _ := db.Get(txhash[:])
if len(raw) != 0 {
var tx data.Transaction
if err := rlp.DecodeBytes(raw, &tx); err != nil {
return nil
}
return &tx
@ -84,12 +84,12 @@ func GetTransaction(db ethdb.Database, txhash common.Hash) *types.Transaction {
}
// PutReceipts stores the receipts in the current database
func PutReceipts(db ethdb.Database, receipts types.Receipts) error {
func PutReceipts(db ethdb.Database, receipts data.Receipts) error {
batch := new(leveldb.Batch)
_, batchWrite := db.(*ethdb.LDBDatabase)
for _, receipt := range receipts {
storageReceipt := (*types.ReceiptForStorage)(receipt)
storageReceipt := (*data.ReceiptForStorage)(receipt)
bytes, err := rlp.EncodeToBytes(storageReceipt)
if err != nil {
return err
@ -119,34 +119,34 @@ func DeleteReceipt(db ethdb.Database, txHash common.Hash) {
}
// GetReceipt returns a receipt by hash
func GetReceipt(db ethdb.Database, txHash common.Hash) *types.Receipt {
data, _ := db.Get(append(receiptsPre, txHash[:]...))
if len(data) == 0 {
func GetReceipt(db ethdb.Database, txHash common.Hash) *data.Receipt {
raw, _ := db.Get(append(receiptsPre, txHash[:]...))
if len(raw) == 0 {
return nil
}
var receipt types.ReceiptForStorage
err := rlp.DecodeBytes(data, &receipt)
var receipt data.ReceiptForStorage
err := rlp.DecodeBytes(raw, &receipt)
if err != nil {
glog.V(logger.Core).Infoln("GetReceipt err:", err)
}
return (*types.Receipt)(&receipt)
return (*data.Receipt)(&receipt)
}
// GetBlockReceipts returns the receipts generated by the transactions
// included in block's given hash.
func GetBlockReceipts(db ethdb.Database, hash common.Hash) types.Receipts {
data, _ := db.Get(append(blockReceiptsPre, hash[:]...))
if len(data) == 0 {
func GetBlockReceipts(db ethdb.Database, hash common.Hash) data.Receipts {
raw, _ := db.Get(append(blockReceiptsPre, hash[:]...))
if len(raw) == 0 {
return nil
}
rs := []*types.ReceiptForStorage{}
if err := rlp.DecodeBytes(data, &rs); err != nil {
rs := []*data.ReceiptForStorage{}
if err := rlp.DecodeBytes(raw, &rs); err != nil {
glog.V(logger.Error).Infof("invalid receipt array RLP for hash %x: %v", hash, err)
return nil
}
receipts := make(types.Receipts, len(rs))
receipts := make(data.Receipts, len(rs))
for i, receipt := range rs {
receipts[i] = (*types.Receipt)(receipt)
receipts[i] = (*data.Receipt)(receipt)
}
return receipts
}
@ -154,10 +154,10 @@ func GetBlockReceipts(db ethdb.Database, hash common.Hash) types.Receipts {
// PutBlockReceipts stores the block's transactions associated receipts
// and stores them by block hash in a single slice. This is required for
// forks and chain reorgs
func PutBlockReceipts(db ethdb.Database, hash common.Hash, receipts types.Receipts) error {
rs := make([]*types.ReceiptForStorage, len(receipts))
func PutBlockReceipts(db ethdb.Database, hash common.Hash, receipts data.Receipts) error {
rs := make([]*data.ReceiptForStorage, len(receipts))
for i, receipt := range receipts {
rs[i] = (*types.ReceiptForStorage)(receipt)
rs[i] = (*data.ReceiptForStorage)(receipt)
}
bytes, err := rlp.EncodeToBytes(rs)
if err != nil {

View file

@ -20,14 +20,14 @@ import (
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
)
type VMEnv struct {
state *state.StateDB
header *types.Header
header *data.Header
msg Message
depth int
chain *BlockChain
@ -36,7 +36,7 @@ type VMEnv struct {
logs []vm.StructLog
}
func NewEnv(state *state.StateDB, chain *BlockChain, msg Message, header *types.Header) *VMEnv {
func NewEnv(state *state.StateDB, chain *BlockChain, msg Message, header *data.Header) *VMEnv {
return &VMEnv{
chain: chain,
state: state,

View file

@ -36,8 +36,8 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/downloader"
@ -92,7 +92,7 @@ type Config struct {
NetworkId int
GenesisNonce int
GenesisFile string
GenesisBlock *types.Block // used by block tests
GenesisBlock *data.Block // used by block tests
FastSync bool
Olympic bool
@ -525,7 +525,7 @@ func (s *Ethereum) PeersInfo() (peersinfo []*PeerInfo) {
return
}
func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
func (s *Ethereum) ResetWithGenesisBlock(gb *data.Block) {
s.blockchain.ResetWithGenesisBlock(gb)
}
@ -738,11 +738,11 @@ func saveBlockchainVersion(db ethdb.Database, bcVersion int) {
// separate header and body entries.
func upgradeChainDatabase(db ethdb.Database) error {
// Short circuit if the head block is stored already as separate header and body
data, err := db.Get([]byte("LastBlock"))
headb, err := db.Get([]byte("LastBlock"))
if err != nil {
return nil
}
head := common.BytesToHash(data)
head := common.BytesToHash(headb)
if block := core.GetBlockByHashOld(db, head); block == nil {
return nil
@ -767,7 +767,7 @@ func upgradeChainDatabase(db ethdb.Database) error {
if err := core.WriteTd(db, block.Hash(), block.DeprecatedTd()); err != nil {
return err
}
if err := core.WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
if err := core.WriteBody(db, block.Hash(), &data.Body{block.Transactions(), block.Uncles()}); err != nil {
return err
}
if err := core.WriteHeader(db, block.Header()); err != nil {
@ -783,7 +783,7 @@ func upgradeChainDatabase(db ethdb.Database) error {
if err := core.WriteTd(db, current.Hash(), current.DeprecatedTd()); err != nil {
return err
}
if err := core.WriteBody(db, current.Hash(), &types.Body{current.Transactions(), current.Uncles()}); err != nil {
if err := core.WriteBody(db, current.Hash(), &data.Body{current.Transactions(), current.Uncles()}); err != nil {
return err
}
if err := core.WriteHeader(db, current.Header()); err != nil {

View file

@ -6,7 +6,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
)
@ -17,18 +17,18 @@ func TestMipmapUpgrade(t *testing.T) {
genesis := core.WriteGenesisBlockForTesting(db)
chain, receipts := core.GenerateChain(genesis, db, 10, func(i int, gen *core.BlockGen) {
var receipts types.Receipts
var receipts data.Receipts
switch i {
case 1:
receipt := types.NewReceipt(nil, new(big.Int))
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{&vm.Log{Address: addr}}
gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
case 2:
receipt := types.NewReceipt(nil, new(big.Int))
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{&vm.Log{Address: addr}}
gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
}
// store the receipts
@ -56,7 +56,7 @@ func TestMipmapUpgrade(t *testing.T) {
}
bloom := core.GetMipmapBloom(db, 1, core.MIPMapLevels[0])
if (bloom == types.Bloom{}) {
if (bloom == data.Bloom{}) {
t.Error("got empty bloom filter")
}

View file

@ -29,7 +29,7 @@ import (
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger"
@ -150,8 +150,8 @@ type Downloader struct {
// Testing hooks
syncInitHook func(uint64, uint64) // Method to call upon initiating a new sync run
bodyFetchHook func([]*types.Header) // Method to call upon starting a block body fetch
receiptFetchHook func([]*types.Header) // Method to call upon starting a receipt fetch
bodyFetchHook func([]*data.Header) // Method to call upon starting a block body fetch
receiptFetchHook func([]*data.Header) // Method to call upon starting a receipt fetch
chainInsertHook func([]*fetchResult) // Method to call upon inserting a chain of blocks (possibly in multiple invocations)
}
@ -1097,7 +1097,7 @@ func (d *Downloader) fetchHeaders(p *peer, td *big.Int, from uint64) error {
pivot := d.queue.FastSyncPivot()
// Keep a count of uncertain headers to roll back
rollback := []*types.Header{}
rollback := []*data.Header{}
defer func() {
if len(rollback) > 0 {
// Flatten the headers and roll them back
@ -1202,7 +1202,7 @@ func (d *Downloader) fetchHeaders(p *peer, td *big.Int, from uint64) error {
if d.mode == FastSync || d.mode == LightSync {
// Collect the yet unknown headers to mark them as uncertain
unknown := make([]*types.Header, 0, len(headers))
unknown := make([]*data.Header, 0, len(headers))
for _, header := range headers {
if !d.hasHeader(header.Hash()) {
unknown = append(unknown, header)
@ -1373,7 +1373,7 @@ func (d *Downloader) fetchNodeData() error {
// also periodically checking for timeouts.
func (d *Downloader) fetchParts(errCancel error, deliveryCh chan dataPack, deliver func(packet dataPack) error, wakeCh chan bool,
expire func() []string, pending func() int, inFlight func() bool, throttle func() bool, reserve func(*peer, int) (*fetchRequest, bool, error),
fetchHook func([]*types.Header), fetch func(*peer, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peer) int,
fetchHook func([]*data.Header), fetch func(*peer, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peer) int,
idle func() ([]*peer, int), setIdle func(*peer), kind string) error {
// Create a ticker to detect expired retrieval tasks
@ -1599,16 +1599,16 @@ func (d *Downloader) process() {
}
// Retrieve the a batch of results to import
var (
blocks = make([]*types.Block, 0, maxResultsProcess)
receipts = make([]types.Receipts, 0, maxResultsProcess)
blocks = make([]*data.Block, 0, maxResultsProcess)
receipts = make([]data.Receipts, 0, maxResultsProcess)
)
items := int(math.Min(float64(len(results)), float64(maxResultsProcess)))
for _, result := range results[:items] {
switch {
case d.mode == FullSync:
blocks = append(blocks, types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles))
blocks = append(blocks, data.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles))
case d.mode == FastSync:
blocks = append(blocks, types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles))
blocks = append(blocks, data.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles))
if result.Header.Number.Uint64() <= pivot {
receipts = append(receipts, result.Receipts)
}
@ -1649,23 +1649,23 @@ func (d *Downloader) DeliverHashes(id string, hashes []common.Hash) (err error)
// DeliverBlocks injects a new batch of blocks received from a remote node.
// This is usually invoked through the BlocksMsg by the protocol handler.
func (d *Downloader) DeliverBlocks(id string, blocks []*types.Block) (err error) {
func (d *Downloader) DeliverBlocks(id string, blocks []*data.Block) (err error) {
return d.deliver(id, d.blockCh, &blockPack{id, blocks}, blockInMeter, blockDropMeter)
}
// DeliverHeaders injects a new batch of blck headers received from a remote
// node into the download schedule.
func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) (err error) {
func (d *Downloader) DeliverHeaders(id string, headers []*data.Header) (err error) {
return d.deliver(id, d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter)
}
// DeliverBodies injects a new batch of block bodies received from a remote node.
func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) (err error) {
func (d *Downloader) DeliverBodies(id string, transactions [][]*data.Transaction, uncles [][]*data.Header) (err error) {
return d.deliver(id, d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter)
}
// DeliverReceipts injects a new batch of receipts received from a remote node.
func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) (err error) {
func (d *Downloader) DeliverReceipts(id string, receipts [][]*data.Receipt) (err error) {
return d.deliver(id, d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter)
}

View file

@ -27,8 +27,8 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
@ -47,14 +47,14 @@ var (
// 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, parentReceipts types.Receipts) ([]common.Hash, map[common.Hash]*types.Header, map[common.Hash]*types.Block, map[common.Hash]types.Receipts) {
func makeChain(n int, seed byte, parent *data.Block, parentReceipts data.Receipts) ([]common.Hash, map[common.Hash]*data.Header, map[common.Hash]*data.Block, map[common.Hash]data.Receipts) {
// Generate the block chain
blocks, receipts := core.GenerateChain(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)
tx, err := data.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testKey)
if err != nil {
panic(err)
}
@ -62,20 +62,20 @@ func makeChain(n int, seed byte, parent *types.Block, parentReceipts types.Recei
}
// If the block number is a multiple of 5, add a bonus uncle to the block
if i%5 == 0 {
block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
block.AddUncle(&data.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
}
})
// Convert the block-chain into a hash-chain and header/block maps
hashes := make([]common.Hash, n+1)
hashes[len(hashes)-1] = parent.Hash()
headerm := make(map[common.Hash]*types.Header, n+1)
headerm := make(map[common.Hash]*data.Header, n+1)
headerm[parent.Hash()] = parent.Header()
blockm := make(map[common.Hash]*types.Block, n+1)
blockm := make(map[common.Hash]*data.Block, n+1)
blockm[parent.Hash()] = parent
receiptm := make(map[common.Hash]types.Receipts, n+1)
receiptm := make(map[common.Hash]data.Receipts, n+1)
receiptm[parent.Hash()] = parentReceipts
for i, b := range blocks {
@ -89,7 +89,7 @@ func makeChain(n int, seed byte, parent *types.Block, parentReceipts types.Recei
// makeChainFork creates two chains of length n, such that h1[:f] and
// h2[:f] are different but have a common suffix of length n-f.
func makeChainFork(n, f int, parent *types.Block, parentReceipts types.Receipts) ([]common.Hash, []common.Hash, map[common.Hash]*types.Header, map[common.Hash]*types.Header, map[common.Hash]*types.Block, map[common.Hash]*types.Block, map[common.Hash]types.Receipts, map[common.Hash]types.Receipts) {
func makeChainFork(n, f int, parent *data.Block, parentReceipts data.Receipts) ([]common.Hash, []common.Hash, map[common.Hash]*data.Header, map[common.Hash]*data.Header, map[common.Hash]*data.Block, map[common.Hash]*data.Block, map[common.Hash]data.Receipts, map[common.Hash]data.Receipts) {
// Create the common suffix
hashes, headers, blocks, receipts := makeChain(n-f, 0, parent, parentReceipts)
@ -121,15 +121,15 @@ type downloadTester struct {
downloader *Downloader
ownHashes []common.Hash // Hash chain belonging to the tester
ownHeaders map[common.Hash]*types.Header // Headers belonging to the tester
ownBlocks map[common.Hash]*types.Block // Blocks belonging to the tester
ownReceipts map[common.Hash]types.Receipts // Receipts belonging to the tester
ownHeaders map[common.Hash]*data.Header // Headers belonging to the tester
ownBlocks map[common.Hash]*data.Block // Blocks belonging to the tester
ownReceipts map[common.Hash]data.Receipts // Receipts belonging to the tester
ownChainTd map[common.Hash]*big.Int // Total difficulties of the blocks in the local chain
peerHashes map[string][]common.Hash // Hash chain belonging to different test peers
peerHeaders map[string]map[common.Hash]*types.Header // Headers belonging to different test peers
peerBlocks map[string]map[common.Hash]*types.Block // Blocks belonging to different test peers
peerReceipts map[string]map[common.Hash]types.Receipts // Receipts belonging to different test peers
peerHeaders map[string]map[common.Hash]*data.Header // Headers belonging to different test peers
peerBlocks map[string]map[common.Hash]*data.Block // Blocks belonging to different test peers
peerReceipts map[string]map[common.Hash]data.Receipts // Receipts belonging to different test peers
peerChainTds map[string]map[common.Hash]*big.Int // Total difficulties of the blocks in the peer chains
lock sync.RWMutex
@ -139,14 +139,14 @@ type downloadTester struct {
func newTester() *downloadTester {
tester := &downloadTester{
ownHashes: []common.Hash{genesis.Hash()},
ownHeaders: map[common.Hash]*types.Header{genesis.Hash(): genesis.Header()},
ownBlocks: map[common.Hash]*types.Block{genesis.Hash(): genesis},
ownReceipts: map[common.Hash]types.Receipts{genesis.Hash(): nil},
ownHeaders: map[common.Hash]*data.Header{genesis.Hash(): genesis.Header()},
ownBlocks: map[common.Hash]*data.Block{genesis.Hash(): genesis},
ownReceipts: map[common.Hash]data.Receipts{genesis.Hash(): nil},
ownChainTd: map[common.Hash]*big.Int{genesis.Hash(): genesis.Difficulty()},
peerHashes: make(map[string][]common.Hash),
peerHeaders: make(map[string]map[common.Hash]*types.Header),
peerBlocks: make(map[string]map[common.Hash]*types.Block),
peerReceipts: make(map[string]map[common.Hash]types.Receipts),
peerHeaders: make(map[string]map[common.Hash]*data.Header),
peerBlocks: make(map[string]map[common.Hash]*data.Block),
peerReceipts: make(map[string]map[common.Hash]data.Receipts),
peerChainTds: make(map[string]map[common.Hash]*big.Int),
}
tester.stateDb, _ = ethdb.NewMemDatabase()
@ -193,7 +193,7 @@ func (dl *downloadTester) hasBlock(hash common.Hash) bool {
}
// getHeader retrieves a header from the testers canonical chain.
func (dl *downloadTester) getHeader(hash common.Hash) *types.Header {
func (dl *downloadTester) getHeader(hash common.Hash) *data.Header {
dl.lock.RLock()
defer dl.lock.RUnlock()
@ -201,7 +201,7 @@ func (dl *downloadTester) getHeader(hash common.Hash) *types.Header {
}
// getBlock retrieves a block from the testers canonical chain.
func (dl *downloadTester) getBlock(hash common.Hash) *types.Block {
func (dl *downloadTester) getBlock(hash common.Hash) *data.Block {
dl.lock.RLock()
defer dl.lock.RUnlock()
@ -209,7 +209,7 @@ func (dl *downloadTester) getBlock(hash common.Hash) *types.Block {
}
// headHeader retrieves the current head header from the canonical chain.
func (dl *downloadTester) headHeader() *types.Header {
func (dl *downloadTester) headHeader() *data.Header {
dl.lock.RLock()
defer dl.lock.RUnlock()
@ -222,7 +222,7 @@ func (dl *downloadTester) headHeader() *types.Header {
}
// headBlock retrieves the current head block from the canonical chain.
func (dl *downloadTester) headBlock() *types.Block {
func (dl *downloadTester) headBlock() *data.Block {
dl.lock.RLock()
defer dl.lock.RUnlock()
@ -237,7 +237,7 @@ func (dl *downloadTester) headBlock() *types.Block {
}
// headFastBlock retrieves the current head fast-sync block from the canonical chain.
func (dl *downloadTester) headFastBlock() *types.Block {
func (dl *downloadTester) headFastBlock() *data.Block {
dl.lock.RLock()
defer dl.lock.RUnlock()
@ -268,7 +268,7 @@ func (dl *downloadTester) getTd(hash common.Hash) *big.Int {
}
// insertHeaders injects a new batch of headers into the simulated chain.
func (dl *downloadTester) insertHeaders(headers []*types.Header, checkFreq int) (int, error) {
func (dl *downloadTester) insertHeaders(headers []*data.Header, checkFreq int) (int, error) {
dl.lock.Lock()
defer dl.lock.Unlock()
@ -297,7 +297,7 @@ func (dl *downloadTester) insertHeaders(headers []*types.Header, checkFreq int)
}
// insertBlocks injects a new batch of blocks into the simulated chain.
func (dl *downloadTester) insertBlocks(blocks types.Blocks) (int, error) {
func (dl *downloadTester) insertBlocks(blocks data.Blocks) (int, error) {
dl.lock.Lock()
defer dl.lock.Unlock()
@ -317,7 +317,7 @@ func (dl *downloadTester) insertBlocks(blocks types.Blocks) (int, error) {
}
// insertReceipts injects a new batch of blocks into the simulated chain.
func (dl *downloadTester) insertReceipts(blocks types.Blocks, receipts []types.Receipts) (int, error) {
func (dl *downloadTester) insertReceipts(blocks data.Blocks, receipts []data.Receipts) (int, error) {
dl.lock.Lock()
defer dl.lock.Unlock()
@ -351,14 +351,14 @@ func (dl *downloadTester) rollback(hashes []common.Hash) {
}
// newPeer registers a new block download source into the downloader.
func (dl *downloadTester) newPeer(id string, version int, hashes []common.Hash, headers map[common.Hash]*types.Header, blocks map[common.Hash]*types.Block, receipts map[common.Hash]types.Receipts) error {
func (dl *downloadTester) newPeer(id string, version int, hashes []common.Hash, headers map[common.Hash]*data.Header, blocks map[common.Hash]*data.Block, receipts map[common.Hash]data.Receipts) error {
return dl.newSlowPeer(id, version, hashes, headers, blocks, receipts, 0)
}
// newSlowPeer registers a new block download source into the downloader, with a
// specific delay time on processing the network packets sent to it, simulating
// potentially slow network IO.
func (dl *downloadTester) newSlowPeer(id string, version int, hashes []common.Hash, headers map[common.Hash]*types.Header, blocks map[common.Hash]*types.Block, receipts map[common.Hash]types.Receipts, delay time.Duration) error {
func (dl *downloadTester) newSlowPeer(id string, version int, hashes []common.Hash, headers map[common.Hash]*data.Header, blocks map[common.Hash]*data.Block, receipts map[common.Hash]data.Receipts, delay time.Duration) error {
dl.lock.Lock()
defer dl.lock.Unlock()
@ -378,9 +378,9 @@ func (dl *downloadTester) newSlowPeer(id string, version int, hashes []common.Ha
dl.peerHashes[id] = make([]common.Hash, len(hashes))
copy(dl.peerHashes[id], hashes)
dl.peerHeaders[id] = make(map[common.Hash]*types.Header)
dl.peerBlocks[id] = make(map[common.Hash]*types.Block)
dl.peerReceipts[id] = make(map[common.Hash]types.Receipts)
dl.peerHeaders[id] = make(map[common.Hash]*data.Header)
dl.peerBlocks[id] = make(map[common.Hash]*data.Block)
dl.peerReceipts[id] = make(map[common.Hash]data.Receipts)
dl.peerChainTds[id] = make(map[common.Hash]*big.Int)
genesis := hashes[len(hashes)-1]
@ -497,7 +497,7 @@ func (dl *downloadTester) peerGetBlocksFn(id string, delay time.Duration) func([
defer dl.lock.RUnlock()
blocks := dl.peerBlocks[id]
result := make([]*types.Block, 0, len(hashes))
result := make([]*data.Block, 0, len(hashes))
for _, hash := range hashes {
if block, ok := blocks[hash]; ok {
result = append(result, block)
@ -543,7 +543,7 @@ func (dl *downloadTester) peerGetAbsHeadersFn(id string, delay time.Duration) fu
// Gather the next batch of headers
hashes := dl.peerHashes[id]
headers := dl.peerHeaders[id]
result := make([]*types.Header, 0, amount)
result := make([]*data.Header, 0, amount)
for i := 0; i < amount && len(hashes)-int(origin)-1-i >= 0; i++ {
if header, ok := headers[hashes[len(hashes)-int(origin)-1-i]]; ok {
result = append(result, header)
@ -570,8 +570,8 @@ func (dl *downloadTester) peerGetBodiesFn(id string, delay time.Duration) func([
blocks := dl.peerBlocks[id]
transactions := make([][]*types.Transaction, 0, len(hashes))
uncles := make([][]*types.Header, 0, len(hashes))
transactions := make([][]*data.Transaction, 0, len(hashes))
uncles := make([][]*data.Header, 0, len(hashes))
for _, hash := range hashes {
if block, ok := blocks[hash]; ok {
@ -597,7 +597,7 @@ func (dl *downloadTester) peerGetReceiptsFn(id string, delay time.Duration) func
receipts := dl.peerReceipts[id]
results := make([][]*types.Receipt, 0, len(hashes))
results := make([][]*data.Receipt, 0, len(hashes))
for _, hash := range hashes {
if receipt, ok := receipts[hash]; ok {
results = append(results, receipt)
@ -839,7 +839,7 @@ func TestInactiveDownloader61(t *testing.T) {
if err := tester.downloader.DeliverHashes("bad peer", []common.Hash{}); err != errNoSyncActive {
t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
}
if err := tester.downloader.DeliverBlocks("bad peer", []*types.Block{}); err != errNoSyncActive {
if err := tester.downloader.DeliverBlocks("bad peer", []*data.Block{}); err != errNoSyncActive {
t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
}
}
@ -850,10 +850,10 @@ func TestInactiveDownloader62(t *testing.T) {
tester := newTester()
// Check that neither block headers nor bodies are accepted
if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
if err := tester.downloader.DeliverHeaders("bad peer", []*data.Header{}); err != errNoSyncActive {
t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
}
if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
if err := tester.downloader.DeliverBodies("bad peer", [][]*data.Transaction{}, [][]*data.Header{}); err != errNoSyncActive {
t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
}
}
@ -864,13 +864,13 @@ func TestInactiveDownloader63(t *testing.T) {
tester := newTester()
// Check that neither block headers nor bodies are accepted
if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
if err := tester.downloader.DeliverHeaders("bad peer", []*data.Header{}); err != errNoSyncActive {
t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
}
if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
if err := tester.downloader.DeliverBodies("bad peer", [][]*data.Transaction{}, [][]*data.Header{}); err != errNoSyncActive {
t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
}
if err := tester.downloader.DeliverReceipts("bad peer", [][]*types.Receipt{}); err != errNoSyncActive {
if err := tester.downloader.DeliverReceipts("bad peer", [][]*data.Receipt{}); err != errNoSyncActive {
t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
}
}
@ -995,10 +995,10 @@ func testEmptyShortCircuit(t *testing.T, protocol int, mode SyncMode) {
// Instrument the downloader to signal body requests
bodiesHave, receiptsHave := int32(0), int32(0)
tester.downloader.bodyFetchHook = func(headers []*types.Header) {
tester.downloader.bodyFetchHook = func(headers []*data.Header) {
atomic.AddInt32(&bodiesHave, int32(len(headers)))
}
tester.downloader.receiptFetchHook = func(headers []*types.Header) {
tester.downloader.receiptFetchHook = func(headers []*data.Header) {
atomic.AddInt32(&receiptsHave, int32(len(headers)))
}
// Synchronise with the peer and make sure all blocks were retrieved

View file

@ -27,8 +27,8 @@ import (
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/logger"
@ -52,7 +52,7 @@ var (
type fetchRequest struct {
Peer *peer // Peer to which the request was sent
Hashes map[common.Hash]int // [eth/61] Requested hashes with their insertion index (priority)
Headers []*types.Header // [eth/62] Requested headers, sorted by request order
Headers []*data.Header // [eth/62] Requested headers, sorted by request order
Time time.Time // Time when the request was made
}
@ -61,10 +61,10 @@ type fetchRequest struct {
type fetchResult struct {
Pending int // Number of data fetches still pending
Header *types.Header
Uncles []*types.Header
Transactions types.Transactions
Receipts types.Receipts
Header *data.Header
Uncles []*data.Header
Transactions data.Transactions
Receipts data.Receipts
}
// queue represents hashes that are either need fetching or are being fetched
@ -78,12 +78,12 @@ type queue struct {
headerHead common.Hash // [eth/62] Hash of the last queued header to verify order
blockTaskPool map[common.Hash]*types.Header // [eth/62] Pending block (body) retrieval tasks, mapping hashes to headers
blockTaskPool map[common.Hash]*data.Header // [eth/62] Pending block (body) retrieval tasks, mapping hashes to headers
blockTaskQueue *prque.Prque // [eth/62] Priority queue of the headers to fetch the blocks (bodies) for
blockPendPool map[string]*fetchRequest // [eth/62] Currently pending block (body) retrieval operations
blockDonePool map[common.Hash]struct{} // [eth/62] Set of the completed block (body) fetches
receiptTaskPool map[common.Hash]*types.Header // [eth/63] Pending receipt retrieval tasks, mapping hashes to headers
receiptTaskPool map[common.Hash]*data.Header // [eth/63] Pending receipt retrieval tasks, mapping hashes to headers
receiptTaskQueue *prque.Prque // [eth/63] Priority queue of the headers to fetch the receipts for
receiptPendPool map[string]*fetchRequest // [eth/63] Currently pending receipt retrieval operations
receiptDonePool map[common.Hash]struct{} // [eth/63] Set of the completed receipt fetches
@ -109,11 +109,11 @@ func newQueue(stateDb ethdb.Database) *queue {
return &queue{
hashPool: make(map[common.Hash]int),
hashQueue: prque.New(),
blockTaskPool: make(map[common.Hash]*types.Header),
blockTaskPool: make(map[common.Hash]*data.Header),
blockTaskQueue: prque.New(),
blockPendPool: make(map[string]*fetchRequest),
blockDonePool: make(map[common.Hash]struct{}),
receiptTaskPool: make(map[common.Hash]*types.Header),
receiptTaskPool: make(map[common.Hash]*data.Header),
receiptTaskQueue: prque.New(),
receiptPendPool: make(map[string]*fetchRequest),
receiptDonePool: make(map[common.Hash]struct{}),
@ -142,12 +142,12 @@ func (q *queue) Reset() {
q.headerHead = common.Hash{}
q.blockTaskPool = make(map[common.Hash]*types.Header)
q.blockTaskPool = make(map[common.Hash]*data.Header)
q.blockTaskQueue.Reset()
q.blockPendPool = make(map[string]*fetchRequest)
q.blockDonePool = make(map[common.Hash]struct{})
q.receiptTaskPool = make(map[common.Hash]*types.Header)
q.receiptTaskPool = make(map[common.Hash]*data.Header)
q.receiptTaskQueue.Reset()
q.receiptPendPool = make(map[string]*fetchRequest)
q.receiptDonePool = make(map[common.Hash]struct{})
@ -303,12 +303,12 @@ func (q *queue) Schedule61(hashes []common.Hash, fifo bool) []common.Hash {
// Schedule adds a set of headers for the download queue for scheduling, returning
// the new headers encountered.
func (q *queue) Schedule(headers []*types.Header, from uint64) []*types.Header {
func (q *queue) Schedule(headers []*data.Header, from uint64) []*data.Header {
q.lock.Lock()
defer q.lock.Unlock()
// Insert all the headers prioritised by the contained block number
inserts := make([]*types.Header, 0, len(headers))
inserts := make([]*data.Header, 0, len(headers))
for _, header := range headers {
// Make sure chain order is honoured and preserved throughout
hash := header.Hash()
@ -529,8 +529,8 @@ func (q *queue) reserveHashes(p *peer, count int, taskQueue *prque.Prque, taskGe
// previously failed downloads. Beside the next batch of needed fetches, it also
// returns a flag whether empty blocks were queued requiring processing.
func (q *queue) ReserveBodies(p *peer, count int) (*fetchRequest, bool, error) {
isNoop := func(header *types.Header) bool {
return header.TxHash == types.EmptyRootHash && header.UncleHash == types.EmptyUncleHash
isNoop := func(header *data.Header) bool {
return header.TxHash == data.EmptyRootHash && header.UncleHash == data.EmptyUncleHash
}
q.lock.Lock()
defer q.lock.Unlock()
@ -542,8 +542,8 @@ func (q *queue) ReserveBodies(p *peer, count int) (*fetchRequest, bool, error) {
// any previously failed downloads. Beside the next batch of needed fetches, it
// also returns a flag whether empty receipts were queued requiring importing.
func (q *queue) ReserveReceipts(p *peer, count int) (*fetchRequest, bool, error) {
isNoop := func(header *types.Header) bool {
return header.ReceiptHash == types.EmptyRootHash
isNoop := func(header *data.Header) bool {
return header.ReceiptHash == data.EmptyRootHash
}
q.lock.Lock()
defer q.lock.Unlock()
@ -558,8 +558,8 @@ func (q *queue) ReserveReceipts(p *peer, count int) (*fetchRequest, bool, error)
// Note, this method expects the queue lock to be already held for writing. The
// reason the lock is not obtained in here is because the parameters already need
// to access the queue, so they already need a lock anyway.
func (q *queue) reserveHeaders(p *peer, count int, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque,
pendPool map[string]*fetchRequest, donePool map[common.Hash]struct{}, isNoop func(*types.Header) bool) (*fetchRequest, bool, error) {
func (q *queue) reserveHeaders(p *peer, count int, taskPool map[common.Hash]*data.Header, taskQueue *prque.Prque,
pendPool map[string]*fetchRequest, donePool map[common.Hash]struct{}, isNoop func(*data.Header) bool) (*fetchRequest, bool, error) {
// Short circuit if the pool has been depleted, or if the peer's already
// downloading something (sanity check not to corrupt state)
if taskQueue.Empty() {
@ -574,12 +574,12 @@ func (q *queue) reserveHeaders(p *peer, count int, taskPool map[common.Hash]*typ
space -= len(request.Headers)
}
// Retrieve a batch of tasks, skipping previously failed ones
send := make([]*types.Header, 0, count)
skip := make([]*types.Header, 0)
send := make([]*data.Header, 0, count)
skip := make([]*data.Header, 0)
progress := false
for proc := 0; proc < space && len(send) < count && !taskQueue.Empty(); proc++ {
header := taskQueue.PopItem().(*types.Header)
header := taskQueue.PopItem().(*data.Header)
// If we're the first to request this task, initialise the result container
index := int(header.Number.Int64() - int64(q.resultOffset))
@ -766,7 +766,7 @@ func (q *queue) expire(timeout time.Duration, pendPool map[string]*fetchRequest,
}
// DeliverBlocks injects a block retrieval response into the download queue.
func (q *queue) DeliverBlocks(id string, blocks []*types.Block) error {
func (q *queue) DeliverBlocks(id string, blocks []*data.Block) error {
q.lock.Lock()
defer q.lock.Unlock()
@ -830,12 +830,12 @@ func (q *queue) DeliverBlocks(id string, blocks []*types.Block) error {
}
// DeliverBodies injects a block body retrieval response into the results queue.
func (q *queue) DeliverBodies(id string, txLists [][]*types.Transaction, uncleLists [][]*types.Header) error {
func (q *queue) DeliverBodies(id string, txLists [][]*data.Transaction, uncleLists [][]*data.Header) error {
q.lock.Lock()
defer q.lock.Unlock()
reconstruct := func(header *types.Header, index int, result *fetchResult) error {
if types.DeriveSha(types.Transactions(txLists[index])) != header.TxHash || types.CalcUncleHash(uncleLists[index]) != header.UncleHash {
reconstruct := func(header *data.Header, index int, result *fetchResult) error {
if data.DeriveSha(data.Transactions(txLists[index])) != header.TxHash || data.CalcUncleHash(uncleLists[index]) != header.UncleHash {
return errInvalidBody
}
result.Transactions = txLists[index]
@ -846,12 +846,12 @@ func (q *queue) DeliverBodies(id string, txLists [][]*types.Transaction, uncleLi
}
// DeliverReceipts injects a receipt retrieval response into the results queue.
func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt) error {
func (q *queue) DeliverReceipts(id string, receiptList [][]*data.Receipt) error {
q.lock.Lock()
defer q.lock.Unlock()
reconstruct := func(header *types.Header, index int, result *fetchResult) error {
if types.DeriveSha(types.Receipts(receiptList[index])) != header.ReceiptHash {
reconstruct := func(header *data.Header, index int, result *fetchResult) error {
if data.DeriveSha(data.Receipts(receiptList[index])) != header.ReceiptHash {
return errInvalidReceipt
}
result.Receipts = receiptList[index]
@ -865,8 +865,8 @@ func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt) error
// Note, this method expects the queue lock to be already held for writing. The
// reason the lock is not obtained in here is because the parameters already need
// to access the queue, so they already need a lock anyway.
func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque, pendPool map[string]*fetchRequest,
donePool map[common.Hash]struct{}, reqTimer metrics.Timer, results int, reconstruct func(header *types.Header, index int, result *fetchResult) error) error {
func (q *queue) deliver(id string, taskPool map[common.Hash]*data.Header, taskQueue *prque.Prque, pendPool map[string]*fetchRequest,
donePool map[common.Hash]struct{}, reqTimer metrics.Timer, results int, reconstruct func(header *data.Header, index int, result *fetchResult) error) error {
// Short circuit if the data was never requested
request := pendPool[id]
if request == nil {

View file

@ -21,7 +21,7 @@ import (
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
)
// headerCheckFn is a callback type for verifying a header's presence in the local chain.
@ -31,19 +31,19 @@ type headerCheckFn func(common.Hash) bool
type blockCheckFn func(common.Hash) bool
// headerRetrievalFn is a callback type for retrieving a header from the local chain.
type headerRetrievalFn func(common.Hash) *types.Header
type headerRetrievalFn func(common.Hash) *data.Header
// blockRetrievalFn is a callback type for retrieving a block from the local chain.
type blockRetrievalFn func(common.Hash) *types.Block
type blockRetrievalFn func(common.Hash) *data.Block
// headHeaderRetrievalFn is a callback type for retrieving the head header from the local chain.
type headHeaderRetrievalFn func() *types.Header
type headHeaderRetrievalFn func() *data.Header
// headBlockRetrievalFn is a callback type for retrieving the head block from the local chain.
type headBlockRetrievalFn func() *types.Block
type headBlockRetrievalFn func() *data.Block
// headFastBlockRetrievalFn is a callback type for retrieving the head fast block from the local chain.
type headFastBlockRetrievalFn func() *types.Block
type headFastBlockRetrievalFn func() *data.Block
// headBlockCommitterFn is a callback for directly committing the head block to a certain entity.
type headBlockCommitterFn func(common.Hash) error
@ -52,13 +52,13 @@ type headBlockCommitterFn func(common.Hash) error
type tdRetrievalFn func(common.Hash) *big.Int
// headerChainInsertFn is a callback type to insert a batch of headers into the local chain.
type headerChainInsertFn func([]*types.Header, int) (int, error)
type headerChainInsertFn func([]*data.Header, int) (int, error)
// blockChainInsertFn is a callback type to insert a batch of blocks into the local chain.
type blockChainInsertFn func(types.Blocks) (int, error)
type blockChainInsertFn func(data.Blocks) (int, error)
// receiptChainInsertFn is a callback type to insert a batch of receipts into the local chain.
type receiptChainInsertFn func(types.Blocks, []types.Receipts) (int, error)
type receiptChainInsertFn func(data.Blocks, []data.Receipts) (int, error)
// chainRollbackFn is a callback type to remove a few recently added elements from the local chain.
type chainRollbackFn func([]common.Hash)
@ -86,7 +86,7 @@ func (p *hashPack) Stats() string { return fmt.Sprintf("%d", len(p.hashes)) }
// blockPack is a batch of blocks returned by a peer (eth/61).
type blockPack struct {
peerId string
blocks []*types.Block
blocks []*data.Block
}
func (p *blockPack) PeerId() string { return p.peerId }
@ -96,7 +96,7 @@ func (p *blockPack) Stats() string { return fmt.Sprintf("%d", len(p.blocks)) }
// headerPack is a batch of block headers returned by a peer.
type headerPack struct {
peerId string
headers []*types.Header
headers []*data.Header
}
func (p *headerPack) PeerId() string { return p.peerId }
@ -106,8 +106,8 @@ func (p *headerPack) Stats() string { return fmt.Sprintf("%d", len(p.headers))
// bodyPack is a batch of block bodies returned by a peer.
type bodyPack struct {
peerId string
transactions [][]*types.Transaction
uncles [][]*types.Header
transactions [][]*data.Transaction
uncles [][]*data.Header
}
func (p *bodyPack) PeerId() string { return p.peerId }
@ -122,7 +122,7 @@ func (p *bodyPack) Stats() string { return fmt.Sprintf("%d:%d", len(p.transactio
// receiptPack is a batch of receipts returned by a peer.
type receiptPack struct {
peerId string
receipts [][]*types.Receipt
receipts [][]*data.Receipt
}
func (p *receiptPack) PeerId() string { return p.peerId }

View file

@ -25,7 +25,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
"gopkg.in/karalabe/cookiejar.v2/collections/prque"
@ -46,7 +46,7 @@ var (
)
// blockRetrievalFn is a callback type for retrieving a block from the local chain.
type blockRetrievalFn func(common.Hash) *types.Block
type blockRetrievalFn func(common.Hash) *data.Block
// blockRequesterFn is a callback type for sending a block retrieval request.
type blockRequesterFn func([]common.Hash) error
@ -58,16 +58,16 @@ type headerRequesterFn func(common.Hash) error
type bodyRequesterFn func([]common.Hash) error
// blockValidatorFn is a callback type to verify a block's header for fast propagation.
type blockValidatorFn func(block *types.Block, parent *types.Block) error
type blockValidatorFn func(block *data.Block, parent *data.Block) error
// blockBroadcasterFn is a callback type for broadcasting a block to connected peers.
type blockBroadcasterFn func(block *types.Block, propagate bool)
type blockBroadcasterFn func(block *data.Block, propagate bool)
// chainHeightFn is a callback type to retrieve the current chain height.
type chainHeightFn func() uint64
// chainInsertFn is a callback type to insert a batch of blocks into the local chain.
type chainInsertFn func(types.Blocks) (int, error)
type chainInsertFn func(data.Blocks) (int, error)
// peerDropFn is a callback type for dropping a peer detected as malicious.
type peerDropFn func(id string)
@ -77,7 +77,7 @@ type peerDropFn func(id string)
type announce struct {
hash common.Hash // Hash of the block being announced
number uint64 // Number of the block being announced (0 = unknown | old protocol)
header *types.Header // Header of the block partially reassembled (new protocol)
header *data.Header // Header of the block partially reassembled (new protocol)
time time.Time // Timestamp of the announcement
origin string // Identifier of the peer originating the notification
@ -89,22 +89,22 @@ type announce struct {
// headerFilterTask represents a batch of headers needing fetcher filtering.
type headerFilterTask struct {
headers []*types.Header // Collection of headers to filter
headers []*data.Header // Collection of headers to filter
time time.Time // Arrival time of the headers
}
// headerFilterTask represents a batch of block bodies (transactions and uncles)
// needing fetcher filtering.
type bodyFilterTask struct {
transactions [][]*types.Transaction // Collection of transactions per block bodies
uncles [][]*types.Header // Collection of uncles per block bodies
transactions [][]*data.Transaction // Collection of transactions per block bodies
uncles [][]*data.Header // Collection of uncles per block bodies
time time.Time // Arrival time of the blocks' contents
}
// inject represents a schedules import operation.
type inject struct {
origin string
block *types.Block
block *data.Block
}
// Fetcher is responsible for accumulating block announcements from various peers
@ -114,7 +114,7 @@ type Fetcher struct {
notify chan *announce
inject chan *inject
blockFilter chan chan []*types.Block
blockFilter chan chan []*data.Block
headerFilter chan chan *headerFilterTask
bodyFilter chan chan *bodyFilterTask
@ -146,7 +146,7 @@ type Fetcher struct {
queueChangeHook func(common.Hash, bool) // Method to call upon adding or deleting a block from the import queue
fetchingHook func([]common.Hash) // Method to call upon starting a block (eth/61) or header (eth/62) fetch
completingHook func([]common.Hash) // Method to call upon starting a block body fetch (eth/62)
importedHook func(*types.Block) // Method to call upon successful block import (both eth/61 and eth/62)
importedHook func(*data.Block) // Method to call upon successful block import (both eth/61 and eth/62)
}
// New creates a block fetcher to retrieve blocks based on hash announcements.
@ -154,7 +154,7 @@ func New(getBlock blockRetrievalFn, validateBlock blockValidatorFn, broadcastBlo
return &Fetcher{
notify: make(chan *announce),
inject: make(chan *inject),
blockFilter: make(chan chan []*types.Block),
blockFilter: make(chan chan []*data.Block),
headerFilter: make(chan chan *headerFilterTask),
bodyFilter: make(chan chan *bodyFilterTask),
done: make(chan common.Hash),
@ -211,7 +211,7 @@ func (f *Fetcher) Notify(peer string, hash common.Hash, number uint64, time time
}
// Enqueue tries to fill gaps the the fetcher's future import queue.
func (f *Fetcher) Enqueue(peer string, block *types.Block) error {
func (f *Fetcher) Enqueue(peer string, block *data.Block) error {
op := &inject{
origin: peer,
block: block,
@ -226,11 +226,11 @@ func (f *Fetcher) Enqueue(peer string, block *types.Block) error {
// FilterBlocks extracts all the blocks that were explicitly requested by the fetcher,
// returning those that should be handled differently.
func (f *Fetcher) FilterBlocks(blocks types.Blocks) types.Blocks {
func (f *Fetcher) FilterBlocks(blocks data.Blocks) data.Blocks {
glog.V(logger.Detail).Infof("[eth/61] filtering %d blocks", len(blocks))
// Send the filter channel to the fetcher
filter := make(chan []*types.Block)
filter := make(chan []*data.Block)
select {
case f.blockFilter <- filter:
@ -254,7 +254,7 @@ func (f *Fetcher) FilterBlocks(blocks types.Blocks) types.Blocks {
// FilterHeaders extracts all the headers that were explicitly requested by the fetcher,
// returning those that should be handled differently.
func (f *Fetcher) FilterHeaders(headers []*types.Header, time time.Time) []*types.Header {
func (f *Fetcher) FilterHeaders(headers []*data.Header, time time.Time) []*data.Header {
glog.V(logger.Detail).Infof("[eth/62] filtering %d headers", len(headers))
// Send the filter channel to the fetcher
@ -282,7 +282,7 @@ func (f *Fetcher) FilterHeaders(headers []*types.Header, time time.Time) []*type
// FilterBodies extracts all the block bodies that were explicitly requested by
// the fetcher, returning those that should be handled differently.
func (f *Fetcher) FilterBodies(transactions [][]*types.Transaction, uncles [][]*types.Header, time time.Time) ([][]*types.Transaction, [][]*types.Header) {
func (f *Fetcher) FilterBodies(transactions [][]*data.Transaction, uncles [][]*data.Header, time time.Time) ([][]*data.Transaction, [][]*data.Header) {
glog.V(logger.Detail).Infof("[eth/62] filtering %d:%d bodies", len(transactions), len(uncles))
// Send the filter channel to the fetcher
@ -488,7 +488,7 @@ func (f *Fetcher) loop() {
case filter := <-f.blockFilter:
// Blocks arrived, extract any explicit fetches, return all else
var blocks types.Blocks
var blocks data.Blocks
select {
case blocks = <-filter:
case <-f.quit:
@ -496,7 +496,7 @@ func (f *Fetcher) loop() {
}
blockFilterInMeter.Mark(int64(len(blocks)))
explicit, download := []*types.Block{}, []*types.Block{}
explicit, download := []*data.Block{}, []*data.Block{}
for _, block := range blocks {
hash := block.Hash()
@ -540,7 +540,7 @@ func (f *Fetcher) loop() {
// Split the batch of headers into unknown ones (to return to the caller),
// known incomplete ones (requiring body retrievals) and completed blocks.
unknown, incomplete, complete := []*types.Header{}, []*announce{}, []*types.Block{}
unknown, incomplete, complete := []*data.Header{}, []*announce{}, []*data.Block{}
for _, header := range task.headers {
hash := header.Hash()
@ -559,10 +559,10 @@ func (f *Fetcher) loop() {
announce.time = task.time
// If the block is empty (header only), short circuit into the final import queue
if header.TxHash == types.DeriveSha(types.Transactions{}) && header.UncleHash == types.CalcUncleHash([]*types.Header{}) {
if header.TxHash == data.DeriveSha(data.Transactions{}) && header.UncleHash == data.CalcUncleHash([]*data.Header{}) {
glog.V(logger.Detail).Infof("[eth/62] Peer %s: block #%d [%x…] empty, skipping body retrieval", announce.origin, header.Number.Uint64(), header.Hash().Bytes()[:4])
block := types.NewBlockWithHeader(header)
block := data.NewBlockWithHeader(header)
block.ReceivedAt = task.time
complete = append(complete, block)
@ -614,22 +614,22 @@ func (f *Fetcher) loop() {
}
bodyFilterInMeter.Mark(int64(len(task.transactions)))
blocks := []*types.Block{}
blocks := []*data.Block{}
for i := 0; i < len(task.transactions) && i < len(task.uncles); i++ {
// Match up a body to any possible completion request
matched := false
for hash, announce := range f.completing {
if f.queued[hash] == nil {
txnHash := types.DeriveSha(types.Transactions(task.transactions[i]))
uncleHash := types.CalcUncleHash(task.uncles[i])
txnHash := data.DeriveSha(data.Transactions(task.transactions[i]))
uncleHash := data.CalcUncleHash(task.uncles[i])
if txnHash == announce.header.TxHash && uncleHash == announce.header.UncleHash {
// Mark the body matched, reassemble if still unknown
matched = true
if f.getBlock(hash) == nil {
block := types.NewBlockWithHeader(announce.header).WithBody(task.transactions[i], task.uncles[i])
block := data.NewBlockWithHeader(announce.header).WithBody(task.transactions[i], task.uncles[i])
block.ReceivedAt = task.time
blocks = append(blocks, block)
@ -697,7 +697,7 @@ func (f *Fetcher) rescheduleComplete(complete *time.Timer) {
// enqueue schedules a new future import operation, if the block to be imported
// has not yet been seen.
func (f *Fetcher) enqueue(peer string, block *types.Block) {
func (f *Fetcher) enqueue(peer string, block *data.Block) {
hash := block.Hash()
// Ensure the peer isn't DOSing us
@ -736,7 +736,7 @@ func (f *Fetcher) enqueue(peer string, block *types.Block) {
// insert spawns a new goroutine to run a block insertion into the chain. If the
// block's number is at the same height as the current import phase, if updates
// the phase states accordingly.
func (f *Fetcher) insert(peer string, block *types.Block) {
func (f *Fetcher) insert(peer string, block *data.Block) {
hash := block.Hash()
// Run the import on a new thread
@ -767,7 +767,7 @@ func (f *Fetcher) insert(peer string, block *types.Block) {
return
}
// Run the actual import and log any issues
if _, err := f.insertChain(types.Blocks{block}); err != nil {
if _, err := f.insertChain(data.Blocks{block}); err != nil {
glog.V(logger.Warn).Infof("Peer %s: block #%d [%x…] import failed: %v", peer, block.NumberU64(), hash[:4], err)
return
}

View file

@ -26,7 +26,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/params"
@ -37,20 +37,20 @@ var (
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)
unknownBlock = data.NewBlock(&data.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) {
func makeChain(n int, seed byte, parent *data.Block) ([]common.Hash, map[common.Hash]*data.Block) {
blocks, _ := core.GenerateChain(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)
tx, err := data.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testKey)
if err != nil {
panic(err)
}
@ -58,12 +58,12 @@ func makeChain(n int, seed byte, parent *types.Block) ([]common.Hash, map[common
}
// If the block number is a multiple of 5, add a bonus uncle to the block
if i%5 == 0 {
block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
block.AddUncle(&data.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
}
})
hashes := make([]common.Hash, n+1)
hashes[len(hashes)-1] = parent.Hash()
blockm := make(map[common.Hash]*types.Block, n+1)
blockm := make(map[common.Hash]*data.Block, n+1)
blockm[parent.Hash()] = parent
for i, b := range blocks {
hashes[len(hashes)-i-2] = b.Hash()
@ -77,7 +77,7 @@ type fetcherTester struct {
fetcher *Fetcher
hashes []common.Hash // Hash chain belonging to the tester
blocks map[common.Hash]*types.Block // Blocks belonging to the tester
blocks map[common.Hash]*data.Block // Blocks belonging to the tester
drops map[string]bool // Map of peers dropped by the fetcher
lock sync.RWMutex
@ -87,7 +87,7 @@ type fetcherTester struct {
func newTester() *fetcherTester {
tester := &fetcherTester{
hashes: []common.Hash{genesis.Hash()},
blocks: map[common.Hash]*types.Block{genesis.Hash(): genesis},
blocks: map[common.Hash]*data.Block{genesis.Hash(): genesis},
drops: make(map[string]bool),
}
tester.fetcher = New(tester.getBlock, tester.verifyBlock, tester.broadcastBlock, tester.chainHeight, tester.insertChain, tester.dropPeer)
@ -97,7 +97,7 @@ func newTester() *fetcherTester {
}
// getBlock retrieves a block from the tester's block chain.
func (f *fetcherTester) getBlock(hash common.Hash) *types.Block {
func (f *fetcherTester) getBlock(hash common.Hash) *data.Block {
f.lock.RLock()
defer f.lock.RUnlock()
@ -105,12 +105,12 @@ func (f *fetcherTester) getBlock(hash common.Hash) *types.Block {
}
// verifyBlock is a nop placeholder for the block header verification.
func (f *fetcherTester) verifyBlock(block *types.Block, parent *types.Block) error {
func (f *fetcherTester) verifyBlock(block *data.Block, parent *data.Block) error {
return nil
}
// broadcastBlock is a nop placeholder for the block broadcasting.
func (f *fetcherTester) broadcastBlock(block *types.Block, propagate bool) {
func (f *fetcherTester) broadcastBlock(block *data.Block, propagate bool) {
}
// chainHeight retrieves the current height (block number) of the chain.
@ -122,7 +122,7 @@ func (f *fetcherTester) chainHeight() uint64 {
}
// insertChain injects a new blocks into the simulated chain.
func (f *fetcherTester) insertChain(blocks types.Blocks) (int, error) {
func (f *fetcherTester) insertChain(blocks data.Blocks) (int, error) {
f.lock.Lock()
defer f.lock.Unlock()
@ -152,15 +152,15 @@ func (f *fetcherTester) dropPeer(peer string) {
}
// makeBlockFetcher retrieves a block fetcher associated with a simulated peer.
func (f *fetcherTester) makeBlockFetcher(blocks map[common.Hash]*types.Block) blockRequesterFn {
closure := make(map[common.Hash]*types.Block)
func (f *fetcherTester) makeBlockFetcher(blocks map[common.Hash]*data.Block) blockRequesterFn {
closure := make(map[common.Hash]*data.Block)
for hash, block := range blocks {
closure[hash] = block
}
// Create a function that returns blocks from the closure
return func(hashes []common.Hash) error {
// Gather the blocks to return
blocks := make([]*types.Block, 0, len(hashes))
blocks := make([]*data.Block, 0, len(hashes))
for _, hash := range hashes {
if block, ok := closure[hash]; ok {
blocks = append(blocks, block)
@ -174,15 +174,15 @@ func (f *fetcherTester) makeBlockFetcher(blocks map[common.Hash]*types.Block) bl
}
// makeHeaderFetcher retrieves a block header fetcher associated with a simulated peer.
func (f *fetcherTester) makeHeaderFetcher(blocks map[common.Hash]*types.Block, drift time.Duration) headerRequesterFn {
closure := make(map[common.Hash]*types.Block)
func (f *fetcherTester) makeHeaderFetcher(blocks map[common.Hash]*data.Block, drift time.Duration) headerRequesterFn {
closure := make(map[common.Hash]*data.Block)
for hash, block := range blocks {
closure[hash] = block
}
// Create a function that return a header from the closure
return func(hash common.Hash) error {
// Gather the blocks to return
headers := make([]*types.Header, 0, 1)
headers := make([]*data.Header, 0, 1)
if block, ok := closure[hash]; ok {
headers = append(headers, block.Header())
}
@ -194,16 +194,16 @@ func (f *fetcherTester) makeHeaderFetcher(blocks map[common.Hash]*types.Block, d
}
// makeBodyFetcher retrieves a block body fetcher associated with a simulated peer.
func (f *fetcherTester) makeBodyFetcher(blocks map[common.Hash]*types.Block, drift time.Duration) bodyRequesterFn {
closure := make(map[common.Hash]*types.Block)
func (f *fetcherTester) makeBodyFetcher(blocks map[common.Hash]*data.Block, drift time.Duration) bodyRequesterFn {
closure := make(map[common.Hash]*data.Block)
for hash, block := range blocks {
closure[hash] = block
}
// Create a function that returns blocks from the closure
return func(hashes []common.Hash) error {
// Gather the block bodies to return
transactions := make([][]*types.Transaction, 0, len(hashes))
uncles := make([][]*types.Header, 0, len(hashes))
transactions := make([][]*data.Transaction, 0, len(hashes))
uncles := make([][]*data.Header, 0, len(hashes))
for _, hash := range hashes {
if block, ok := closure[hash]; ok {
@ -253,7 +253,7 @@ func verifyCompletingEvent(t *testing.T, completing chan []common.Hash, arrive b
}
// verifyImportEvent verifies that one single event arrive on an import channel.
func verifyImportEvent(t *testing.T, imported chan *types.Block, arrive bool) {
func verifyImportEvent(t *testing.T, imported chan *data.Block, arrive bool) {
if arrive {
select {
case <-imported:
@ -271,7 +271,7 @@ func verifyImportEvent(t *testing.T, imported chan *types.Block, arrive bool) {
// verifyImportCount verifies that exactly count number of events arrive on an
// import hook channel.
func verifyImportCount(t *testing.T, imported chan *types.Block, count int) {
func verifyImportCount(t *testing.T, imported chan *data.Block, count int) {
for i := 0; i < count; i++ {
select {
case <-imported:
@ -283,7 +283,7 @@ func verifyImportCount(t *testing.T, imported chan *types.Block, count int) {
}
// verifyImportDone verifies that no more events are arriving on an import channel.
func verifyImportDone(t *testing.T, imported chan *types.Block) {
func verifyImportDone(t *testing.T, imported chan *data.Block) {
select {
case <-imported:
t.Fatalf("extra block imported")
@ -309,8 +309,8 @@ func testSequentialAnnouncements(t *testing.T, protocol int) {
bodyFetcher := tester.makeBodyFetcher(blocks, 0)
// Iteratively announce blocks until all are imported
imported := make(chan *types.Block)
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
imported := make(chan *data.Block)
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
for i := len(hashes) - 2; i >= 0; i-- {
if protocol < 62 {
@ -351,8 +351,8 @@ func testConcurrentAnnouncements(t *testing.T, protocol int) {
return headerFetcher(hash)
}
// Iteratively announce blocks until all are imported
imported := make(chan *types.Block)
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
imported := make(chan *data.Block)
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
for i := len(hashes) - 2; i >= 0; i-- {
if protocol < 62 {
@ -393,11 +393,11 @@ func testOverlappingAnnouncements(t *testing.T, protocol int) {
// Iteratively announce blocks, but overlap them continuously
overlap := 16
imported := make(chan *types.Block, len(hashes)-1)
imported := make(chan *data.Block, len(hashes)-1)
for i := 0; i < overlap; i++ {
imported <- nil
}
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
for i := len(hashes) - 2; i >= 0; i-- {
if protocol < 62 {
@ -492,8 +492,8 @@ func testRandomArrivalImport(t *testing.T, protocol int) {
bodyFetcher := tester.makeBodyFetcher(blocks, 0)
// Iteratively announce blocks, skipping one entry
imported := make(chan *types.Block, len(hashes)-1)
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
imported := make(chan *data.Block, len(hashes)-1)
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
for i := len(hashes) - 1; i >= 0; i-- {
if i != skip {
@ -533,8 +533,8 @@ func testQueueGapFill(t *testing.T, protocol int) {
bodyFetcher := tester.makeBodyFetcher(blocks, 0)
// Iteratively announce blocks, skipping one entry
imported := make(chan *types.Block, len(hashes)-1)
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
imported := make(chan *data.Block, len(hashes)-1)
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
for i := len(hashes) - 1; i >= 0; i-- {
if i != skip {
@ -569,15 +569,15 @@ func testImportDeduplication(t *testing.T, protocol int) {
bodyFetcher := tester.makeBodyFetcher(blocks, 0)
counter := uint32(0)
tester.fetcher.insertChain = func(blocks types.Blocks) (int, error) {
tester.fetcher.insertChain = func(blocks data.Blocks) (int, error) {
atomic.AddUint32(&counter, uint32(len(blocks)))
return tester.insertChain(blocks)
}
// Instrument the fetching and imported events
fetching := make(chan []common.Hash)
imported := make(chan *types.Block, len(hashes)-1)
imported := make(chan *data.Block, len(hashes)-1)
tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- hashes }
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
// Announce the duplicating block, wait for retrieval, and also propagate directly
if protocol < 62 {
@ -614,7 +614,7 @@ func TestDistantPropagationDiscarding(t *testing.T) {
tester.lock.Lock()
tester.hashes = []common.Hash{head}
tester.blocks = map[common.Hash]*types.Block{head: blocks[head]}
tester.blocks = map[common.Hash]*data.Block{head: blocks[head]}
tester.lock.Unlock()
// Ensure that a block with a lower number than the threshold is discarded
@ -650,7 +650,7 @@ func testDistantAnnouncementDiscarding(t *testing.T, protocol int) {
tester.lock.Lock()
tester.hashes = []common.Hash{head}
tester.blocks = map[common.Hash]*types.Block{head: blocks[head]}
tester.blocks = map[common.Hash]*data.Block{head: blocks[head]}
tester.lock.Unlock()
headerFetcher := tester.makeHeaderFetcher(blocks, -gatherSlack)
@ -689,8 +689,8 @@ func testInvalidNumberAnnouncement(t *testing.T, protocol int) {
headerFetcher := tester.makeHeaderFetcher(blocks, -gatherSlack)
bodyFetcher := tester.makeBodyFetcher(blocks, 0)
imported := make(chan *types.Block)
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
imported := make(chan *data.Block)
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
// Announce a block with a bad number, check for immediate drop
tester.fetcher.Notify("bad", hashes[0], 2, time.Now().Add(-arriveTimeout), nil, headerFetcher, bodyFetcher)
@ -738,8 +738,8 @@ func testEmptyBlockShortCircuit(t *testing.T, protocol int) {
completing := make(chan []common.Hash)
tester.fetcher.completingHook = func(hashes []common.Hash) { completing <- hashes }
imported := make(chan *types.Block)
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
imported := make(chan *data.Block)
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
// Iteratively announce blocks until all are imported
for i := len(hashes) - 2; i >= 0; i-- {
@ -769,8 +769,8 @@ func testHashMemoryExhaustionAttack(t *testing.T, protocol int) {
// Create a tester with instrumented import hooks
tester := newTester()
imported, announces := make(chan *types.Block), int32(0)
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
imported, announces := make(chan *data.Block), int32(0)
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
tester.fetcher.announceChangeHook = func(hash common.Hash, added bool) {
if added {
atomic.AddInt32(&announces, 1)
@ -830,8 +830,8 @@ func TestBlockMemoryExhaustionAttack(t *testing.T) {
// Create a tester with instrumented import hooks
tester := newTester()
imported, enqueued := make(chan *types.Block), int32(0)
tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
imported, enqueued := make(chan *data.Block), int32(0)
tester.fetcher.importedHook = func(block *data.Block) { imported <- block }
tester.fetcher.queueChangeHook = func(hash common.Hash, added bool) {
if added {
atomic.AddInt32(&enqueued, 1)
@ -842,7 +842,7 @@ func TestBlockMemoryExhaustionAttack(t *testing.T) {
// Create a valid chain and a batch of dangling (but in range) blocks
targetBlocks := hashLimit + 2*maxQueueDist
hashes, blocks := makeChain(targetBlocks, 0, genesis)
attack := make(map[common.Hash]*types.Block)
attack := make(map[common.Hash]*data.Block)
for i := byte(0); len(attack) < blockLimit+2*maxQueueDist; i++ {
hashes, blocks := makeChain(maxQueueDist-1, i, unknownBlock)
for _, hash := range hashes[:maxQueueDist-2] {

View file

@ -21,7 +21,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
)
@ -37,8 +37,8 @@ type Filter struct {
addresses []common.Address
topics [][]common.Hash
BlockCallback func(*types.Block, vm.Logs)
TransactionCallback func(*types.Transaction)
BlockCallback func(*data.Block, vm.Logs)
TransactionCallback func(*data.Transaction)
LogsCallback func(vm.Logs)
}
@ -119,7 +119,7 @@ func (self *Filter) mipFind(start, end uint64, depth int) (logs vm.Logs) {
}
func (self *Filter) getLogs(start, end uint64) (logs vm.Logs) {
var block *types.Block
var block *data.Block
for i := start; i <= end; i++ {
hash := core.GetCanonicalHash(self.db, i)
@ -198,11 +198,11 @@ Logs:
return ret
}
func (self *Filter) bloomFilter(block *types.Block) bool {
func (self *Filter) bloomFilter(block *data.Block) bool {
if len(self.addresses) > 0 {
var included bool
for _, addr := range self.addresses {
if types.BloomLookup(block.Bloom(), addr) {
if data.BloomLookup(block.Bloom(), addr) {
included = true
break
}
@ -216,7 +216,7 @@ func (self *Filter) bloomFilter(block *types.Block) bool {
for _, sub := range self.topics {
var included bool
for _, topic := range sub {
if (topic == common.Hash{}) || types.BloomLookup(block.Bloom(), topic) {
if (topic == common.Hash{}) || data.BloomLookup(block.Bloom(), topic) {
included = true
break
}

View file

@ -8,18 +8,18 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
)
func makeReceipt(addr common.Address) *types.Receipt {
receipt := types.NewReceipt(nil, new(big.Int))
func makeReceipt(addr common.Address) *data.Receipt {
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{
&vm.Log{Address: addr},
}
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
receipt.Bloom = data.CreateBloom(data.Receipts{receipt})
return receipt
}
@ -42,23 +42,23 @@ func BenchmarkMipmaps(b *testing.B) {
genesis := core.WriteGenesisBlockForTesting(db, core.GenesisAccount{addr1, big.NewInt(1000000)})
chain, receipts := core.GenerateChain(genesis, db, 100010, func(i int, gen *core.BlockGen) {
var receipts types.Receipts
var receipts data.Receipts
switch i {
case 2403:
receipt := makeReceipt(addr1)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
gen.AddUncheckedReceipt(receipt)
case 1034:
receipt := makeReceipt(addr2)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
gen.AddUncheckedReceipt(receipt)
case 34:
receipt := makeReceipt(addr3)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
gen.AddUncheckedReceipt(receipt)
case 99999:
receipt := makeReceipt(addr4)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
gen.AddUncheckedReceipt(receipt)
}
@ -118,10 +118,10 @@ func TestFilters(t *testing.T) {
genesis := core.WriteGenesisBlockForTesting(db, core.GenesisAccount{addr, big.NewInt(1000000)})
chain, receipts := core.GenerateChain(genesis, db, 1000, func(i int, gen *core.BlockGen) {
var receipts types.Receipts
var receipts data.Receipts
switch i {
case 1:
receipt := types.NewReceipt(nil, new(big.Int))
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{
&vm.Log{
Address: addr,
@ -129,9 +129,9 @@ func TestFilters(t *testing.T) {
},
}
gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
case 2:
receipt := types.NewReceipt(nil, new(big.Int))
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{
&vm.Log{
Address: addr,
@ -139,9 +139,9 @@ func TestFilters(t *testing.T) {
},
}
gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
case 998:
receipt := types.NewReceipt(nil, new(big.Int))
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{
&vm.Log{
Address: addr,
@ -149,9 +149,9 @@ func TestFilters(t *testing.T) {
},
}
gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
case 999:
receipt := types.NewReceipt(nil, new(big.Int))
receipt := data.NewReceipt(nil, new(big.Int))
receipt.Logs = vm.Logs{
&vm.Log{
Address: addr,
@ -159,7 +159,7 @@ func TestFilters(t *testing.T) {
},
}
gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt}
receipts = data.Receipts{receipt}
}
// store the receipts

View file

@ -22,7 +22,7 @@ import (
"sync"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
@ -96,7 +96,7 @@ func (self *GasPriceOracle) listenLoop() {
}
}
func (self *GasPriceOracle) processBlock(block *types.Block) {
func (self *GasPriceOracle) processBlock(block *data.Block) {
i := block.NumberU64()
if i > self.lastProcessed {
self.lastProcessed = i
@ -145,7 +145,7 @@ func (self *GasPriceOracle) processBlock(block *types.Block) {
}
// returns the lowers possible price with which a tx was or could have been included
func (self *GasPriceOracle) lowestPrice(block *types.Block) *big.Int {
func (self *GasPriceOracle) lowestPrice(block *data.Block) *big.Int {
gasUsed := big.NewInt(0)
receipts := self.eth.BlockProcessor().GetBlockReceipts(block.Hash())

View file

@ -26,7 +26,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/eth/fetcher"
"github.com/ethereum/go-ethereum/ethdb"
@ -129,7 +129,7 @@ func NewProtocolManager(fastSync bool, networkId int, mux *event.TypeMux, txpool
blockchain.CurrentHeader, blockchain.CurrentBlock, blockchain.CurrentFastBlock, blockchain.FastSyncCommitHead, blockchain.GetTd,
blockchain.InsertHeaderChain, blockchain.InsertChain, blockchain.InsertReceiptChain, blockchain.Rollback, manager.removePeer)
validator := func(block *types.Block, parent *types.Block) error {
validator := func(block *data.Block, parent *data.Block) error {
return core.ValidateHeader(pow, block.Header(), parent.Header(), true, false)
}
heighter := func() uint64 {
@ -318,7 +318,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
var (
hash common.Hash
bytes common.StorageSize
blocks []*types.Block
blocks []*data.Block
)
for len(blocks) < downloader.MaxBlockFetch && bytes < softResponseLimit {
//Retrieve the hash of the next block
@ -338,7 +338,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
case p.version < eth62 && msg.Code == BlocksMsg:
// Decode the arrived block message
var blocks []*types.Block
var blocks []*data.Block
if err := msg.Decode(&blocks); err != nil {
glog.V(logger.Detail).Infoln("Decode error", err)
blocks = nil
@ -362,12 +362,12 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
// Gather headers until the fetch or network limits is reached
var (
bytes common.StorageSize
headers []*types.Header
headers []*data.Header
unknown bool
)
for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
// Retrieve the next header satisfying the query
var origin *types.Header
var origin *data.Header
if query.Origin.Hash != (common.Hash{}) {
origin = pm.blockchain.GetHeader(query.Origin.Hash)
} else {
@ -419,7 +419,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
case p.version >= eth62 && msg.Code == BlockHeadersMsg:
// A batch of headers arrived to one of our previous requests
var headers []*types.Header
var headers []*data.Header
if err := msg.Decode(&headers); err != nil {
return errResp(ErrDecode, "msg %v: %v", msg, err)
}
@ -469,8 +469,8 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
return errResp(ErrDecode, "msg %v: %v", msg, err)
}
// Deliver them all to the downloader for queuing
trasactions := make([][]*types.Transaction, len(request))
uncles := make([][]*types.Header, len(request))
trasactions := make([][]*data.Transaction, len(request))
uncles := make([][]*data.Header, len(request))
for i, body := range request {
trasactions[i] = body.Transactions
@ -544,7 +544,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
// Retrieve the requested block's receipts, skipping if unknown to us
results := core.GetBlockReceipts(pm.chaindb, hash)
if results == nil {
if header := pm.blockchain.GetHeader(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
if header := pm.blockchain.GetHeader(hash); header == nil || header.ReceiptHash != data.EmptyRootHash {
continue
}
}
@ -560,7 +560,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
case p.version >= eth63 && msg.Code == ReceiptsMsg:
// A batch of receipts arrived to one of our previous requests
var receipts [][]*types.Receipt
var receipts [][]*data.Receipt
if err := msg.Decode(&receipts); err != nil {
return errResp(ErrDecode, "msg %v: %v", msg, err)
}
@ -644,7 +644,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
case msg.Code == TxMsg:
// Transactions arrived, parse all of them and deliver to the pool
var txs []*types.Transaction
var txs []*data.Transaction
if err := msg.Decode(&txs); err != nil {
return errResp(ErrDecode, "msg %v: %v", msg, err)
}
@ -665,7 +665,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
// BroadcastBlock will either propagate a block to a subset of it's peers, or
// will only announce it's availability (depending what's requested).
func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
func (pm *ProtocolManager) BroadcastBlock(block *data.Block, propagate bool) {
hash := block.Hash()
peers := pm.peers.PeersWithoutBlock(hash)
@ -701,12 +701,12 @@ func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
// BroadcastTx will propagate a transaction to all peers which are not known to
// already have the given transaction.
func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *data.Transaction) {
// Broadcast transaction to a batch of peers not knowing about it
peers := pm.peers.PeersWithoutTx(hash)
//FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
for _, peer := range peers {
peer.SendTransactions(types.Transactions{tx})
peer.SendTransactions(data.Transactions{tx})
}
glog.V(logger.Detail).Infoln("broadcast tx to", len(peers), "peers")
}

View file

@ -8,8 +8,8 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/ethdb"
@ -169,7 +169,7 @@ func testGetBlocks(t *testing.T, protocol int) {
for i, tt := range tests {
// Collect the hashes to request, and the response to expect
hashes, seen := []common.Hash{}, make(map[int64]bool)
blocks := []*types.Block{}
blocks := []*data.Block{}
for j := 0; j < tt.random; j++ {
for {
@ -313,7 +313,7 @@ func testGetBlockHeaders(t *testing.T, protocol int) {
// Run each of the tests and verify the results against the chain
for i, tt := range tests {
// Collect the headers to expect in the response
headers := []*types.Header{}
headers := []*data.Header{}
for _, hash := range tt.expect {
headers = append(headers, pm.blockchain.GetBlock(hash).Header())
}
@ -412,13 +412,13 @@ func testGetNodeData(t *testing.T, protocol int) {
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)
tx, _ := data.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)
tx1, _ := data.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testBankKey)
tx2, _ := data.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(acc1Key)
block.AddTx(tx1)
block.AddTx(tx2)
case 2:
@ -503,13 +503,13 @@ func testGetReceipt(t *testing.T, protocol int) {
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)
tx, _ := data.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)
tx1, _ := data.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testBankKey)
tx2, _ := data.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(acc1Key)
block.AddTx(tx1)
block.AddTx(tx2)
case 2:
@ -532,7 +532,7 @@ func testGetReceipt(t *testing.T, protocol int) {
defer peer.close()
// Collect the hashes to request, and the response to expect
hashes, receipts := []common.Hash{}, []types.Receipts{}
hashes, receipts := []common.Hash{}, []data.Receipts{}
for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
block := pm.blockchain.GetBlockByNumber(i)

View file

@ -11,7 +11,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
@ -28,7 +28,7 @@ var (
// newTestProtocolManager creates a new protocol manager for testing purposes,
// with the given number of blocks already known, and potential notification
// channels for different events.
func newTestProtocolManager(fastSync bool, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, error) {
func newTestProtocolManager(fastSync bool, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*data.Transaction) (*ProtocolManager, error) {
var (
evmux = new(event.TypeMux)
pow = new(core.FakePow)
@ -54,7 +54,7 @@ func newTestProtocolManager(fastSync bool, blocks int, generator func(int, *core
// with the given number of blocks already known, and potential notification
// channels for different events. In case of an error, the constructor force-
// fails the test.
func newTestProtocolManagerMust(t *testing.T, fastSync bool, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) *ProtocolManager {
func newTestProtocolManagerMust(t *testing.T, fastSync bool, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*data.Transaction) *ProtocolManager {
pm, err := newTestProtocolManager(fastSync, blocks, generator, newtx)
if err != nil {
t.Fatalf("Failed to create protocol manager: %v", err)
@ -64,15 +64,15 @@ func newTestProtocolManagerMust(t *testing.T, fastSync bool, blocks int, generat
// testTxPool is a fake, helper transaction pool for testing purposes
type testTxPool struct {
pool []*types.Transaction // Collection of all transactions
added chan<- []*types.Transaction // Notification channel for new transactions
pool []*data.Transaction // Collection of all transactions
added chan<- []*data.Transaction // Notification channel for new transactions
lock sync.RWMutex // Protects the transaction pool
}
// AddTransactions appends a batch of transactions to the pool, and notifies any
// listeners if the addition channel is non nil
func (p *testTxPool) AddTransactions(txs []*types.Transaction) {
func (p *testTxPool) AddTransactions(txs []*data.Transaction) {
p.lock.Lock()
defer p.lock.Unlock()
@ -83,19 +83,19 @@ func (p *testTxPool) AddTransactions(txs []*types.Transaction) {
}
// GetTransactions returns all the transactions known to the pool
func (p *testTxPool) GetTransactions() types.Transactions {
func (p *testTxPool) GetTransactions() data.Transactions {
p.lock.RLock()
defer p.lock.RUnlock()
txs := make([]*types.Transaction, len(p.pool))
txs := make([]*data.Transaction, len(p.pool))
copy(txs, p.pool)
return txs
}
// newTestTransaction create a new dummy transaction.
func newTestTransaction(from *crypto.Key, nonce uint64, datasize int) *types.Transaction {
tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize))
func newTestTransaction(from *crypto.Key, nonce uint64, datasize int) *data.Transaction {
tx := data.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize))
tx, _ = tx.SignECDSA(from.PrivateKey)
return tx

View file

@ -23,7 +23,7 @@ import (
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
@ -129,7 +129,7 @@ func (p *peer) MarkTransaction(hash common.Hash) {
// SendTransactions sends transactions to the peer and includes the hashes
// in its transaction hash set for future reference.
func (p *peer) SendTransactions(txs types.Transactions) error {
func (p *peer) SendTransactions(txs data.Transactions) error {
for _, tx := range txs {
p.knownTxs.Add(tx.Hash())
}
@ -142,7 +142,7 @@ func (p *peer) SendBlockHashes(hashes []common.Hash) error {
}
// SendBlocks sends a batch of blocks to the remote peer.
func (p *peer) SendBlocks(blocks []*types.Block) error {
func (p *peer) SendBlocks(blocks []*data.Block) error {
return p2p.Send(p.rw, BlocksMsg, blocks)
}
@ -170,13 +170,13 @@ func (p *peer) SendNewBlockHashes(hashes []common.Hash, numbers []uint64) error
}
// SendNewBlock propagates an entire block to a remote peer.
func (p *peer) SendNewBlock(block *types.Block, td *big.Int) error {
func (p *peer) SendNewBlock(block *data.Block, td *big.Int) error {
p.knownBlocks.Add(block.Hash())
return p2p.Send(p.rw, NewBlockMsg, []interface{}{block, td})
}
// SendBlockHeaders sends a batch of block headers to the remote peer.
func (p *peer) SendBlockHeaders(headers []*types.Header) error {
func (p *peer) SendBlockHeaders(headers []*data.Header) error {
return p2p.Send(p.rw, BlockHeadersMsg, headers)
}

View file

@ -22,7 +22,7 @@ import (
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/rlp"
)
@ -107,16 +107,16 @@ var errorToString = map[int]string{
type txPool interface {
// AddTransactions should add the given transactions to the pool.
AddTransactions([]*types.Transaction)
AddTransactions([]*data.Transaction)
// GetTransactions should return pending transactions.
// The slice should be modifiable by the caller.
GetTransactions() types.Transactions
GetTransactions() data.Transactions
}
type chainManager interface {
GetBlockHashesFromHash(hash common.Hash, amount uint64) (hashes []common.Hash)
GetBlock(hash common.Hash) (block *types.Block)
GetBlock(hash common.Hash) (block *data.Block)
Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash)
}
@ -194,14 +194,14 @@ func (hn *hashOrNumber) DecodeRLP(s *rlp.Stream) error {
// newBlockData is the network packet for the block propagation message.
type newBlockData struct {
Block *types.Block
Block *data.Block
TD *big.Int
}
// blockBody represents the data content of a single block.
type blockBody struct {
Transactions []*types.Transaction // Transactions contained within a block
Uncles []*types.Header // Uncles contained within a block
Transactions []*data.Transaction // Transactions contained within a block
Uncles []*data.Header // Uncles contained within a block
}
// blockBodiesData is the network packet for block content distribution.

View file

@ -24,7 +24,7 @@ import (
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rlp"
@ -96,7 +96,7 @@ func TestRecvTransactions62(t *testing.T) { testRecvTransactions(t, 62) }
func TestRecvTransactions63(t *testing.T) { testRecvTransactions(t, 63) }
func testRecvTransactions(t *testing.T, protocol int) {
txAdded := make(chan []*types.Transaction)
txAdded := make(chan []*data.Transaction)
pm := newTestProtocolManagerMust(t, false, 0, nil, txAdded)
p, _ := newTestPeer("peer", protocol, pm, true)
defer pm.Stop()
@ -129,7 +129,7 @@ func testSendTransactions(t *testing.T, protocol int) {
// Fill the pool with big transactions.
const txsize = txsyncPackSize / 10
alltxs := make([]*types.Transaction, 100)
alltxs := make([]*data.Transaction, 100)
for nonce := range alltxs {
alltxs[nonce] = newTestTransaction(testAccount, uint64(nonce), txsize)
}
@ -145,7 +145,7 @@ func testSendTransactions(t *testing.T, protocol int) {
seen[tx.Hash()] = false
}
for n := 0; n < len(alltxs) && !t.Failed(); {
var txs []*types.Transaction
var txs []*data.Transaction
msg, err := p.app.ReadMsg()
if err != nil {
t.Errorf("%v: read error: %v", p.Peer, err)

View file

@ -21,7 +21,7 @@ import (
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
@ -39,7 +39,7 @@ const (
type txsync struct {
p *peer
txs []*types.Transaction
txs []*data.Transaction
}
// syncTransactions starts sending all currently pending transactions to the given peer.

View file

@ -24,8 +24,8 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger"
@ -165,7 +165,7 @@ func (self *Miner) PendingState() *state.StateDB {
return self.worker.pendingState()
}
func (self *Miner) PendingBlock() *types.Block {
func (self *Miner) PendingBlock() *data.Block {
return self.worker.pendingBlock()
}

View file

@ -27,8 +27,8 @@ import (
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
@ -71,21 +71,21 @@ type Work struct {
ignoredTransactors *set.Set
lowGasTransactors *set.Set
ownedAccounts *set.Set
lowGasTxs types.Transactions
lowGasTxs data.Transactions
localMinedBlocks *uint64RingBuffer // the most recent block numbers that were mined locally (used to check block inclusion)
Block *types.Block // the new block
Block *data.Block // the new block
header *types.Header
txs []*types.Transaction
receipts []*types.Receipt
header *data.Header
txs []*data.Transaction
receipts []*data.Receipt
createdAt time.Time
}
type Result struct {
Work *Work
Block *types.Block
Block *data.Block
}
// worker is the main object which takes care of applying messages to the new state
@ -111,10 +111,10 @@ type worker struct {
current *Work
uncleMu sync.Mutex
possibleUncles map[common.Hash]*types.Block
possibleUncles map[common.Hash]*data.Block
txQueueMu sync.Mutex
txQueue map[common.Hash]*types.Transaction
txQueue map[common.Hash]*data.Transaction
// atomic status counters
mining int32
@ -132,9 +132,9 @@ func newWorker(coinbase common.Address, eth core.Backend) *worker {
gasPrice: new(big.Int),
chain: eth.BlockChain(),
proc: eth.BlockProcessor(),
possibleUncles: make(map[common.Hash]*types.Block),
possibleUncles: make(map[common.Hash]*data.Block),
coinbase: coinbase,
txQueue: make(map[common.Hash]*types.Transaction),
txQueue: make(map[common.Hash]*data.Transaction),
quit: make(chan struct{}),
fullValidation: false,
}
@ -158,12 +158,12 @@ func (self *worker) pendingState() *state.StateDB {
return self.current.state
}
func (self *worker) pendingBlock() *types.Block {
func (self *worker) pendingBlock() *data.Block {
self.currentMu.Lock()
defer self.currentMu.Unlock()
if atomic.LoadInt32(&self.mining) == 0 {
return types.NewBlock(
return data.NewBlock(
self.current.header,
self.current.txs,
nil,
@ -238,7 +238,7 @@ func (self *worker) update() {
// Apply transaction to the pending state if we're not mining
if atomic.LoadInt32(&self.mining) == 0 {
self.currentMu.Lock()
self.current.commitTransactions(types.Transactions{ev.Tx}, self.gasPrice, self.proc)
self.current.commitTransactions(data.Transactions{ev.Tx}, self.gasPrice, self.proc)
self.currentMu.Unlock()
}
}
@ -272,7 +272,7 @@ func (self *worker) wait() {
work := result.Work
if self.fullValidation {
if _, err := self.chain.InsertChain(types.Blocks{block}); err != nil {
if _, err := self.chain.InsertChain(data.Blocks{block}); err != nil {
glog.V(logger.Error).Infoln("mining err", err)
continue
}
@ -305,7 +305,7 @@ func (self *worker) wait() {
}
// broadcast before waiting for validation
go func(block *types.Block, logs vm.Logs, receipts []*types.Receipt) {
go func(block *data.Block, logs vm.Logs, receipts []*data.Receipt) {
self.mux.Post(core.NewMinedBlockEvent{block})
self.mux.Post(core.ChainEvent{block, block.Hash(), logs})
if stat == core.CanonStatTy {
@ -354,7 +354,7 @@ func (self *worker) push(work *Work) {
}
// makeCurrent creates a new environment for the current cycle.
func (self *worker) makeCurrent(parent *types.Block, header *types.Header) error {
func (self *worker) makeCurrent(parent *data.Block, header *data.Header) error {
state, err := state.New(parent.Root(), self.eth.ChainDb())
if err != nil {
return err
@ -456,7 +456,7 @@ func (self *worker) commitNewWork() {
}
num := parent.Number()
header := &types.Header{
header := &data.Header{
ParentHash: parent.Hash(),
Number: num.Add(num, common.Big1),
Difficulty: core.CalcDifficulty(uint64(tstamp), parent.Time().Uint64(), parent.Number(), parent.Difficulty()),
@ -483,7 +483,7 @@ func (self *worker) commitNewWork() {
//approach 2
transactions := self.eth.TxPool().GetTransactions()
sort.Sort(types.TxByPriceAndNonce{transactions})
sort.Sort(data.TxByPriceAndNonce{transactions})
/* // approach 3
// commit transactions for this run.
@ -517,7 +517,7 @@ func (self *worker) commitNewWork() {
// compute uncles for the new block.
var (
uncles []*types.Header
uncles []*data.Header
badUncles []common.Hash
)
for hash, uncle := range self.possibleUncles {
@ -546,7 +546,7 @@ func (self *worker) commitNewWork() {
}
// create the new block whose nonce will be mined.
work.Block = types.NewBlock(header, work.txs, uncles, work.receipts)
work.Block = data.NewBlock(header, work.txs, uncles, work.receipts)
// We only care about logging if we're actually mining.
if atomic.LoadInt32(&self.mining) == 1 {
@ -556,7 +556,7 @@ func (self *worker) commitNewWork() {
self.push(work)
}
func (self *worker) commitUncle(work *Work, uncle *types.Header) error {
func (self *worker) commitUncle(work *Work, uncle *data.Header) error {
hash := uncle.Hash()
if work.uncles.Has(hash) {
return core.UncleError("Uncle not unique")
@ -571,7 +571,7 @@ func (self *worker) commitUncle(work *Work, uncle *types.Header) error {
return nil
}
func (env *Work) commitTransactions(transactions types.Transactions, gasPrice *big.Int, proc *core.BlockProcessor) {
func (env *Work) commitTransactions(transactions data.Transactions, gasPrice *big.Int, proc *core.BlockProcessor) {
gp := new(core.GasPool).AddGas(env.header.GasLimit)
for _, tx := range transactions {
@ -631,7 +631,7 @@ func (env *Work) commitTransactions(transactions types.Transactions, gasPrice *b
}
}
func (env *Work) commitTransaction(tx *types.Transaction, proc *core.BlockProcessor, gp *core.GasPool) error {
func (env *Work) commitTransaction(tx *data.Transaction, proc *core.BlockProcessor, gp *core.GasPool) error {
snap := env.state.Copy()
receipt, _, err := proc.ApplyTransaction(gp, env.state, env.header, tx, env.header.GasUsed, true)
if err != nil {

View file

@ -20,7 +20,7 @@ import (
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
)
type Block interface {
@ -32,6 +32,6 @@ type Block interface {
}
type ChainManager interface {
GetBlockByNumber(uint64) *types.Block
CurrentBlock() *types.Block
GetBlockByNumber(uint64) *data.Block
CurrentBlock() *data.Block
}

View file

@ -29,7 +29,7 @@ import (
"github.com/ethereum/go-ethereum/common/natspec"
"github.com/ethereum/go-ethereum/common/registrar"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/logger/glog"
@ -153,7 +153,7 @@ func (self *adminApi) DataDir(req *shared.Request) (interface{}, error) {
return self.ethereum.DataDir, nil
}
func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
func hasAllBlocks(chain *core.BlockChain, bs []*data.Block) bool {
for _, b := range bs {
if !chain.HasBlock(b.Hash()) {
return false
@ -176,13 +176,13 @@ func (self *adminApi) ImportChain(req *shared.Request) (interface{}, error) {
stream := rlp.NewStream(fh, 0)
// Run actual the import.
blocks := make(types.Blocks, importBatchSize)
blocks := make(data.Blocks, importBatchSize)
n := 0
for batch := 0; ; batch++ {
i := 0
for ; i < importBatchSize; i++ {
var b types.Block
var b data.Block
if err := stream.Decode(&b); err == io.EOF {
break
} else if err != nil {

View file

@ -24,7 +24,7 @@ import (
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/rpc/shared"
)
@ -906,7 +906,7 @@ func (args *SubmitWorkArgs) UnmarshalJSON(b []byte) (err error) {
}
type tx struct {
tx *types.Transaction
tx *data.Transaction
To string `json:"to"`
From string `json:"from"`
@ -918,7 +918,7 @@ type tx struct {
Hash string `json:"hash"`
}
func newTx(t *types.Transaction) *tx {
func newTx(t *data.Transaction) *tx {
from, _ := t.From()
var to string
if t := t.To(); t != nil {
@ -956,7 +956,7 @@ func (tx *tx) UnmarshalJSON(b []byte) (err error) {
amount = new(big.Int).Set(common.Big0)
gasLimit = new(big.Int).Set(common.Big0)
gasPrice = new(big.Int).Set(common.Big0)
data []byte
extraData []byte
contractCreation = true
)
@ -1005,9 +1005,9 @@ func (tx *tx) UnmarshalJSON(b []byte) (err error) {
if strVal, ok := val.(string); ok {
tx.Data = strVal
if strings.HasPrefix(strVal, "0x") {
data = common.Hex2Bytes(strVal[2:])
extraData = common.Hex2Bytes(strVal[2:])
} else {
data = common.Hex2Bytes(strVal)
extraData = common.Hex2Bytes(strVal)
}
}
}
@ -1031,9 +1031,9 @@ func (tx *tx) UnmarshalJSON(b []byte) (err error) {
}
if contractCreation {
tx.tx = types.NewContractCreation(nonce, amount, gasLimit, gasPrice, data)
tx.tx = data.NewContractCreation(nonce, amount, gasLimit, gasPrice, extraData)
} else {
tx.tx = types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data)
tx.tx = data.NewTransaction(nonce, to, amount, gasLimit, gasPrice, extraData)
}
return nil

View file

@ -25,7 +25,7 @@ import (
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/rpc/shared"
)
@ -71,9 +71,9 @@ func newHexData(input interface{}) *hexdata {
} else {
d.data = input.Bytes()
}
case types.Bloom:
case data.Bloom:
d.data = input.Bytes()
case *types.Bloom:
case *data.Bloom:
if input == nil {
d.isNil = true
} else {
@ -281,7 +281,7 @@ func (b *BlockRes) MarshalJSON() ([]byte, error) {
}
}
func NewBlockRes(block *types.Block, td *big.Int, fullTx bool) *BlockRes {
func NewBlockRes(block *data.Block, td *big.Int, fullTx bool) *BlockRes {
if block == nil {
return nil
}
@ -338,7 +338,7 @@ type TransactionRes struct {
Input *hexdata `json:"input"`
}
func NewTransactionRes(tx *types.Transaction) *TransactionRes {
func NewTransactionRes(tx *data.Transaction) *TransactionRes {
if tx == nil {
return nil
}
@ -377,7 +377,7 @@ type UncleRes struct {
UnixTimestamp *hexnum `json:"timestamp"`
}
func NewUncleRes(h *types.Header) *UncleRes {
func NewUncleRes(h *data.Header) *UncleRes {
if h == nil {
return nil
}
@ -436,7 +436,7 @@ type ReceiptRes struct {
Logs *[]interface{} `json:"logs"`
}
func NewReceiptRes(rec *types.Receipt) *ReceiptRes {
func NewReceiptRes(rec *data.Receipt) *ReceiptRes {
if rec == nil {
return nil
}

View file

@ -31,8 +31,8 @@ import (
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/ethdb"
@ -42,7 +42,7 @@ import (
// Block Test JSON Format
type BlockTest struct {
Genesis *types.Block
Genesis *data.Block
Json *btJSON
preAccounts map[string]btAccount
@ -292,7 +292,7 @@ func (t *BlockTest) TryBlocksInsert(blockchain *core.BlockChain) ([]btBlock, err
}
}
// RLP decoding worked, try to insert into chain:
_, err = blockchain.InsertChain(types.Blocks{cb})
_, err = blockchain.InsertChain(data.Blocks{cb})
if err != nil {
if b.BlockHeader == nil {
continue // OK - block is supposed to be invalid, continue with next block
@ -313,7 +313,7 @@ func (t *BlockTest) TryBlocksInsert(blockchain *core.BlockChain) ([]btBlock, err
return validBlocks, nil
}
func validateHeader(h *btHeader, h2 *types.Header) error {
func validateHeader(h *btHeader, h2 *data.Header) error {
expectedBloom := mustConvertBytes(h.Bloom)
if !bytes.Equal(expectedBloom, h2.Bloom.Bytes()) {
return fmt.Errorf("Bloom: want: %x have: %x", expectedBloom, h2.Bloom.Bytes())
@ -477,16 +477,16 @@ func convertBlockTest(in *btJSON) (out *BlockTest, err error) {
return out, err
}
func mustConvertGenesis(testGenesis btHeader) *types.Block {
func mustConvertGenesis(testGenesis btHeader) *data.Block {
hdr := mustConvertHeader(testGenesis)
hdr.Number = big.NewInt(0)
return types.NewBlockWithHeader(hdr)
return data.NewBlockWithHeader(hdr)
}
func mustConvertHeader(in btHeader) *types.Header {
func mustConvertHeader(in btHeader) *data.Header {
// hex decode these fields
header := &types.Header{
header := &data.Header{
//SeedHash: mustConvertBytes(in.SeedHash),
MixDigest: mustConvertHash(in.MixHash),
Bloom: mustConvertBloom(in.Bloom),
@ -501,13 +501,13 @@ func mustConvertHeader(in btHeader) *types.Header {
GasLimit: mustConvertBigInt(in.GasLimit, 16),
Difficulty: mustConvertBigInt(in.Difficulty, 16),
Time: mustConvertBigInt(in.Timestamp, 16),
Nonce: types.EncodeNonce(mustConvertUint(in.Nonce, 16)),
Nonce: data.EncodeNonce(mustConvertUint(in.Nonce, 16)),
}
return header
}
func mustConvertBlock(testBlock btBlock) (*types.Block, error) {
var b types.Block
func mustConvertBlock(testBlock btBlock) (*data.Block, error) {
var b data.Block
r := bytes.NewReader(mustConvertBytes(testBlock.Rlp))
err := rlp.Decode(r, &b)
return &b, err
@ -541,12 +541,12 @@ func mustConvertAddress(in string) common.Address {
return common.BytesToAddress(out)
}
func mustConvertBloom(in string) types.Bloom {
func mustConvertBloom(in string) data.Bloom {
out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
if err != nil {
panic(fmt.Errorf("invalid hex: %q", in))
}
return types.BytesToBloom(out)
return data.BytesToBloom(out)
}
func mustConvertBigInt(in string, base int) *big.Int {

View file

@ -24,7 +24,7 @@ import (
"runtime"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/rlp"
)
@ -111,7 +111,7 @@ func runTransactionTests(tests map[string]TransactionTest, skipTests []string) e
}
func runTransactionTest(txTest TransactionTest) (err error) {
tx := new(types.Transaction)
tx := new(data.Transaction)
err = rlp.DecodeBytes(mustConvertBytes(txTest.Rlp), tx)
if err != nil {
@ -148,7 +148,7 @@ func runTransactionTest(txTest TransactionTest) (err error) {
return errors.New("Should not happen: verify RLP decoding and field validation")
}
func verifyTxFields(txTest TransactionTest, decodedTx *types.Transaction) (err error) {
func verifyTxFields(txTest TransactionTest, decodedTx *data.Transaction) (err error) {
defer func() {
if recovered := recover(); recovered != nil {
buf := make([]byte, 64<<10)

View file

@ -23,8 +23,8 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
@ -53,7 +53,7 @@ func checkLogs(tlog []Log, logs vm.Logs) error {
}
}
}
genBloom := common.LeftPadBytes(types.LogsBloom(vm.Logs{logs[i]}).Bytes(), 256)
genBloom := common.LeftPadBytes(data.LogsBloom(vm.Logs{logs[i]}).Bytes(), 256)
if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) {
return fmt.Errorf("bloom mismatch")

View file

@ -24,8 +24,8 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rlp"
@ -71,7 +71,7 @@ func (self *Object) Storage() (storage map[string]string) {
// Block interface exposed to QML
type Block struct {
//Transactions string `json:"transactions"`
ref *types.Block
ref *data.Block
Size string `json:"size"`
Number int `json:"number"`
Hash string `json:"hash"`
@ -88,7 +88,7 @@ type Block struct {
}
// Creates a new QML Block from a chain block
func NewBlock(block *types.Block) *Block {
func NewBlock(block *data.Block) *Block {
if block == nil {
return &Block{}
}
@ -140,7 +140,7 @@ func (self *Block) GetTransaction(hash string) *Transaction {
}
type Transaction struct {
ref *types.Transaction
ref *data.Transaction
Value string `json:"value"`
Gas string `json:"gas"`
@ -155,7 +155,7 @@ type Transaction struct {
Confirmations int `json:"confirmations"`
}
func NewTx(tx *types.Transaction) *Transaction {
func NewTx(tx *data.Transaction) *Transaction {
sender, err := tx.From()
if err != nil {
return nil

View file

@ -31,8 +31,8 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/data"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth"
@ -296,7 +296,7 @@ func (self *XEth) UpdateState() (wait chan *big.Int) {
func (self *XEth) Whisper() *Whisper { return self.whisper }
func (self *XEth) getBlockByHeight(height int64) *types.Block {
func (self *XEth) getBlockByHeight(height int64) *data.Block {
var num uint64
switch height {
@ -322,20 +322,20 @@ func (self *XEth) BlockByHash(strHash string) *Block {
return NewBlock(block)
}
func (self *XEth) EthBlockByHash(strHash string) *types.Block {
func (self *XEth) EthBlockByHash(strHash string) *data.Block {
hash := common.HexToHash(strHash)
block := self.backend.BlockChain().GetBlock(hash)
return block
}
func (self *XEth) EthTransactionByHash(hash string) (tx *types.Transaction, blhash common.Hash, blnum *big.Int, txi uint64) {
func (self *XEth) EthTransactionByHash(hash string) (tx *data.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.ChainDb().Get(common.FromHex(hash))
if len(data) != 0 {
dtx := new(types.Transaction)
if err := rlp.DecodeBytes(data, dtx); err != nil {
raw, _ := self.backend.ChainDb().Get(common.FromHex(hash))
if len(raw) != 0 {
dtx := new(data.Transaction)
if err := rlp.DecodeBytes(raw, dtx); err != nil {
glog.V(logger.Error).Infoln(err)
return
}
@ -373,7 +373,7 @@ func (self *XEth) BlockByNumber(num int64) *Block {
return NewBlock(self.getBlockByHeight(num))
}
func (self *XEth) EthBlockByNumber(num int64) *types.Block {
func (self *XEth) EthBlockByNumber(num int64) *data.Block {
return self.getBlockByHeight(num)
}
@ -381,15 +381,15 @@ func (self *XEth) Td(hash common.Hash) *big.Int {
return self.backend.BlockChain().GetTd(hash)
}
func (self *XEth) CurrentBlock() *types.Block {
func (self *XEth) CurrentBlock() *data.Block {
return self.backend.BlockChain().CurrentBlock()
}
func (self *XEth) GetBlockReceipts(bhash common.Hash) types.Receipts {
func (self *XEth) GetBlockReceipts(bhash common.Hash) data.Receipts {
return self.backend.BlockProcessor().GetBlockReceipts(bhash)
}
func (self *XEth) GetTxReceipt(txhash common.Hash) *types.Receipt {
func (self *XEth) GetTxReceipt(txhash common.Hash) *data.Receipt {
return core.GetReceipt(self.backend.ChainDb(), txhash)
}
@ -582,7 +582,7 @@ func (self *XEth) NewTransactionFilter() int {
id := self.filterManager.Add(filter)
self.transactionQueue[id] = &hashQueue{timeout: time.Now()}
filter.TransactionCallback = func(tx *types.Transaction) {
filter.TransactionCallback = func(tx *data.Transaction) {
self.transactionMu.Lock()
defer self.transactionMu.Unlock()
@ -601,7 +601,7 @@ func (self *XEth) NewBlockFilter() int {
id := self.filterManager.Add(filter)
self.blockQueue[id] = &hashQueue{timeout: time.Now()}
filter.BlockCallback = func(block *types.Block, logs vm.Logs) {
filter.BlockCallback = func(block *data.Block, logs vm.Logs) {
self.blockMu.Lock()
defer self.blockMu.Unlock()
@ -808,7 +808,7 @@ func (self *XEth) FromNumber(str string) string {
}
func (self *XEth) PushTx(encodedTx string) (string, error) {
tx := new(types.Transaction)
tx := new(data.Transaction)
err := rlp.DecodeBytes(common.FromHex(encodedTx), tx)
if err != nil {
glog.V(logger.Error).Infoln(err)
@ -938,7 +938,7 @@ func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceS
value = common.Big(valueStr)
gas *big.Int
price *big.Int
data []byte
extraData []byte
contractCreation bool
)
@ -954,7 +954,7 @@ func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceS
price = common.Big(gasPriceStr)
}
data = common.FromHex(codeStr)
extraData = common.FromHex(codeStr)
if len(toStr) == 0 {
contractCreation = true
}
@ -992,11 +992,11 @@ func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceS
state := self.backend.TxPool().State()
nonce = state.GetNonce(from)
}
var tx *types.Transaction
var tx *data.Transaction
if contractCreation {
tx = types.NewContractCreation(nonce, value, gas, price, data)
tx = data.NewContractCreation(nonce, value, gas, price, extraData)
} else {
tx = types.NewTransaction(nonce, to, value, gas, price, data)
tx = data.NewTransaction(nonce, to, value, gas, price, extraData)
}
signed, err := self.sign(tx, from, false)
@ -1017,7 +1017,7 @@ func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceS
return signed.Hash().Hex(), nil
}
func (self *XEth) sign(tx *types.Transaction, from common.Address, didUnlock bool) (*types.Transaction, error) {
func (self *XEth) sign(tx *data.Transaction, from common.Address, didUnlock bool) (*data.Transaction, error) {
hash := tx.SigHash()
sig, err := self.doSign(from, hash, didUnlock)
if err != nil {