Begin of moving objects to types package

* Block(s)
* Transaction(s)
This commit is contained in:
obscuren 2014-11-18 16:58:22 +01:00
parent 62cd9946ee
commit a1b6a9ac29
33 changed files with 189 additions and 151 deletions

View File

@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/wire" "github.com/ethereum/go-ethereum/wire"
@ -20,7 +21,7 @@ var poollogger = logger.NewLogger("BPOOL")
type block struct { type block struct {
from *Peer from *Peer
peer *Peer peer *Peer
block *chain.Block block *types.Block
reqAt time.Time reqAt time.Time
requested int requested int
} }
@ -73,7 +74,7 @@ func (self *BlockPool) HasCommonHash(hash []byte) bool {
return self.eth.ChainManager().GetBlock(hash) != nil return self.eth.ChainManager().GetBlock(hash) != nil
} }
func (self *BlockPool) Blocks() (blocks chain.Blocks) { func (self *BlockPool) Blocks() (blocks types.Blocks) {
for _, item := range self.pool { for _, item := range self.pool {
if item.block != nil { if item.block != nil {
blocks = append(blocks, item.block) blocks = append(blocks, item.block)
@ -123,15 +124,15 @@ func (self *BlockPool) AddHash(hash []byte, peer *Peer) {
} }
} }
func (self *BlockPool) Add(b *chain.Block, peer *Peer) { func (self *BlockPool) Add(b *types.Block, peer *Peer) {
self.addBlock(b, peer, false) self.addBlock(b, peer, false)
} }
func (self *BlockPool) AddNew(b *chain.Block, peer *Peer) { func (self *BlockPool) AddNew(b *types.Block, peer *Peer) {
self.addBlock(b, peer, true) self.addBlock(b, peer, true)
} }
func (self *BlockPool) addBlock(b *chain.Block, peer *Peer, newBlock bool) { func (self *BlockPool) addBlock(b *types.Block, peer *Peer, newBlock bool) {
self.mut.Lock() self.mut.Lock()
defer self.mut.Unlock() defer self.mut.Unlock()
@ -283,7 +284,7 @@ out:
break out break out
case <-procTimer.C: case <-procTimer.C:
blocks := self.Blocks() blocks := self.Blocks()
chain.BlockBy(chain.Number).Sort(blocks) types.BlockBy(types.Number).Sort(blocks)
// Find common block // Find common block
for i, block := range blocks { for i, block := range blocks {

View File

@ -9,6 +9,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
@ -69,7 +70,7 @@ type BlockManager struct {
// The last attempted block is mainly used for debugging purposes // The last attempted block is mainly used for debugging purposes
// This does not have to be a valid block and will be set during // This does not have to be a valid block and will be set during
// 'Process' & canonical validation. // 'Process' & canonical validation.
lastAttemptedBlock *Block lastAttemptedBlock *types.Block
events event.Subscription events event.Subscription
} }
@ -117,11 +118,11 @@ func (sm *BlockManager) ChainManager() *ChainManager {
return sm.bc return sm.bc
} }
func (self *BlockManager) ProcessTransactions(coinbase *state.StateObject, state *state.State, block, parent *Block, txs Transactions) (Receipts, Transactions, Transactions, Transactions, error) { func (self *BlockManager) ProcessTransactions(coinbase *state.StateObject, state *state.State, block, parent *types.Block, txs types.Transactions) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
var ( var (
receipts Receipts receipts types.Receipts
handled, unhandled Transactions handled, unhandled types.Transactions
erroneous Transactions erroneous types.Transactions
totalUsedGas = big.NewInt(0) totalUsedGas = big.NewInt(0)
err error err error
) )
@ -159,8 +160,9 @@ done:
txGas.Sub(txGas, st.gas) txGas.Sub(txGas, st.gas)
cumulative := new(big.Int).Set(totalUsedGas.Add(totalUsedGas, txGas)) cumulative := new(big.Int).Set(totalUsedGas.Add(totalUsedGas, txGas))
receipt := &Receipt{ethutil.CopyBytes(state.Root()), cumulative, nil /*bloom*/, state.Logs()} receipt := types.NewReceipt(state.Root(), cumulative)
receipt.Bloom = CreateBloom(Receipts{receipt}) receipt.SetLogs(state.Logs())
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
// Notify all subscribers // Notify all subscribers
go self.eth.EventMux().Post(TxPostEvent{tx}) go self.eth.EventMux().Post(TxPostEvent{tx})
@ -178,7 +180,7 @@ done:
return receipts, handled, unhandled, erroneous, err return receipts, handled, unhandled, erroneous, err
} }
func (sm *BlockManager) Process(block *Block) (td *big.Int, msgs state.Messages, err error) { func (sm *BlockManager) Process(block *types.Block) (td *big.Int, msgs state.Messages, err error) {
// Processing a blocks may never happen simultaneously // Processing a blocks may never happen simultaneously
sm.mutex.Lock() sm.mutex.Lock()
defer sm.mutex.Unlock() defer sm.mutex.Unlock()
@ -195,7 +197,7 @@ func (sm *BlockManager) Process(block *Block) (td *big.Int, msgs state.Messages,
return sm.ProcessWithParent(block, parent) return sm.ProcessWithParent(block, parent)
} }
func (sm *BlockManager) ProcessWithParent(block, parent *Block) (td *big.Int, messages state.Messages, err error) { func (sm *BlockManager) ProcessWithParent(block, parent *types.Block) (td *big.Int, messages state.Messages, err error) {
sm.lastAttemptedBlock = block sm.lastAttemptedBlock = block
state := parent.State().Copy() state := parent.State().Copy()
@ -215,13 +217,13 @@ func (sm *BlockManager) ProcessWithParent(block, parent *Block) (td *big.Int, me
return return
} }
txSha := DeriveSha(block.transactions) txSha := types.DeriveSha(block.Transactions())
if bytes.Compare(txSha, block.TxSha) != 0 { if bytes.Compare(txSha, block.TxSha) != 0 {
err = fmt.Errorf("validating transaction root. received=%x got=%x", block.TxSha, txSha) err = fmt.Errorf("validating transaction root. received=%x got=%x", block.TxSha, txSha)
return return
} }
receiptSha := DeriveSha(receipts) receiptSha := types.DeriveSha(receipts)
if bytes.Compare(receiptSha, block.ReceiptSha) != 0 { if bytes.Compare(receiptSha, block.ReceiptSha) != 0 {
err = fmt.Errorf("validating receipt root. received=%x got=%x", block.ReceiptSha, receiptSha) err = fmt.Errorf("validating receipt root. received=%x got=%x", block.ReceiptSha, receiptSha)
return return
@ -238,8 +240,8 @@ func (sm *BlockManager) ProcessWithParent(block, parent *Block) (td *big.Int, me
return return
} }
block.receipts = receipts // although this isn't necessary it be in the future //block.receipts = receipts // although this isn't necessary it be in the future
rbloom := CreateBloom(receipts) rbloom := types.CreateBloom(receipts)
if bytes.Compare(rbloom, block.LogsBloom) != 0 { if bytes.Compare(rbloom, block.LogsBloom) != 0 {
err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom) err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
return return
@ -272,7 +274,7 @@ func (sm *BlockManager) ProcessWithParent(block, parent *Block) (td *big.Int, me
} }
} }
func (sm *BlockManager) ApplyDiff(state *state.State, parent, block *Block) (receipts Receipts, err error) { func (sm *BlockManager) ApplyDiff(state *state.State, parent, block *types.Block) (receipts types.Receipts, err error) {
coinbase := state.GetOrNewStateObject(block.Coinbase) coinbase := state.GetOrNewStateObject(block.Coinbase)
coinbase.SetGasPool(block.CalcGasLimit(parent)) coinbase.SetGasPool(block.CalcGasLimit(parent))
@ -285,7 +287,7 @@ func (sm *BlockManager) ApplyDiff(state *state.State, parent, block *Block) (rec
return receipts, nil return receipts, nil
} }
func (sm *BlockManager) CalculateTD(block *Block) (*big.Int, bool) { func (sm *BlockManager) CalculateTD(block *types.Block) (*big.Int, bool) {
uncleDiff := new(big.Int) uncleDiff := new(big.Int)
for _, uncle := range block.Uncles { for _, uncle := range block.Uncles {
uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty) uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
@ -311,7 +313,7 @@ func (sm *BlockManager) CalculateTD(block *Block) (*big.Int, bool) {
// Validates the current block. Returns an error if the block was invalid, // Validates the current block. Returns an error if the block was invalid,
// an uncle or anything that isn't on the current block chain. // an uncle or anything that isn't on the current block chain.
// Validation validates easy over difficult (dagger takes longer time = difficult) // Validation validates easy over difficult (dagger takes longer time = difficult)
func (sm *BlockManager) ValidateBlock(block, parent *Block) error { func (sm *BlockManager) ValidateBlock(block, parent *types.Block) error {
expd := CalcDifficulty(block, parent) expd := CalcDifficulty(block, parent)
if expd.Cmp(block.Difficulty) < 0 { if expd.Cmp(block.Difficulty) < 0 {
return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd) return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
@ -337,7 +339,7 @@ func (sm *BlockManager) ValidateBlock(block, parent *Block) error {
return nil return nil
} }
func (sm *BlockManager) AccumelateRewards(state *state.State, block, parent *Block) error { func (sm *BlockManager) AccumelateRewards(state *state.State, block, parent *types.Block) error {
reward := new(big.Int).Set(BlockReward) reward := new(big.Int).Set(BlockReward)
knownUncles := ethutil.Set(parent.Uncles) knownUncles := ethutil.Set(parent.Uncles)
@ -380,7 +382,7 @@ func (sm *BlockManager) AccumelateRewards(state *state.State, block, parent *Blo
return nil return nil
} }
func (sm *BlockManager) GetMessages(block *Block) (messages []*state.Message, err error) { func (sm *BlockManager) GetMessages(block *types.Block) (messages []*state.Message, err error) {
if !sm.bc.HasBlock(block.PrevHash) { if !sm.bc.HasBlock(block.PrevHash) {
return nil, ParentError(block.PrevHash) return nil, ParentError(block.PrevHash)
} }

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
@ -13,7 +14,7 @@ import (
var chainlogger = logger.NewLogger("CHAIN") var chainlogger = logger.NewLogger("CHAIN")
func AddTestNetFunds(block *Block) { func AddTestNetFunds(block *types.Block) {
for _, addr := range []string{ for _, addr := range []string{
"51ba59315b3a95761d0863b05ccc7a7f54703d99", "51ba59315b3a95761d0863b05ccc7a7f54703d99",
"e4157b34ea9615cfbde6b4fda419828124b70c78", "e4157b34ea9615cfbde6b4fda419828124b70c78",
@ -25,13 +26,13 @@ func AddTestNetFunds(block *Block) {
"1a26338f0d905e295fccb71fa9ea849ffa12aaf4", "1a26338f0d905e295fccb71fa9ea849ffa12aaf4",
} { } {
codedAddr := ethutil.Hex2Bytes(addr) codedAddr := ethutil.Hex2Bytes(addr)
account := block.state.GetAccount(codedAddr) account := block.State().GetAccount(codedAddr)
account.SetBalance(ethutil.Big("1606938044258990275541962092341162602522202993782792835301376")) //ethutil.BigPow(2, 200) account.SetBalance(ethutil.Big("1606938044258990275541962092341162602522202993782792835301376")) //ethutil.BigPow(2, 200)
block.state.UpdateStateObject(account) block.State().UpdateStateObject(account)
} }
} }
func CalcDifficulty(block, parent *Block) *big.Int { func CalcDifficulty(block, parent *types.Block) *big.Int {
diff := new(big.Int) diff := new(big.Int)
adjust := new(big.Int).Rsh(parent.Difficulty, 10) adjust := new(big.Int).Rsh(parent.Difficulty, 10)
@ -45,36 +46,41 @@ func CalcDifficulty(block, parent *Block) *big.Int {
} }
type ChainManager struct { type ChainManager struct {
eth EthManager //eth EthManager
genesisBlock *Block processor types.BlockProcessor
genesisBlock *types.Block
// Last known total difficulty // Last known total difficulty
TD *big.Int TD *big.Int
LastBlockNumber uint64 LastBlockNumber uint64
CurrentBlock *Block CurrentBlock *types.Block
LastBlockHash []byte LastBlockHash []byte
workingChain *BlockChain workingChain *BlockChain
} }
func NewChainManager(ethereum EthManager) *ChainManager { func NewChainManager() *ChainManager {
bc := &ChainManager{} bc := &ChainManager{}
bc.genesisBlock = NewBlockFromBytes(ethutil.Encode(Genesis)) bc.genesisBlock = types.NewBlockFromBytes(ethutil.Encode(Genesis))
bc.eth = ethereum //bc.eth = ethereum
bc.setLastBlock() bc.setLastBlock()
return bc return bc
} }
func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
self.processor = proc
}
func (bc *ChainManager) setLastBlock() { func (bc *ChainManager) setLastBlock() {
data, _ := ethutil.Config.Db.Get([]byte("LastBlock")) data, _ := ethutil.Config.Db.Get([]byte("LastBlock"))
if len(data) != 0 { if len(data) != 0 {
// Prep genesis // Prep genesis
AddTestNetFunds(bc.genesisBlock) AddTestNetFunds(bc.genesisBlock)
block := NewBlockFromBytes(data) block := types.NewBlockFromBytes(data)
bc.CurrentBlock = block bc.CurrentBlock = block
bc.LastBlockHash = block.Hash() bc.LastBlockHash = block.Hash()
bc.LastBlockNumber = block.Number.Uint64() bc.LastBlockNumber = block.Number.Uint64()
@ -89,7 +95,7 @@ func (bc *ChainManager) setLastBlock() {
} }
// Block creation & chain handling // Block creation & chain handling
func (bc *ChainManager) NewBlock(coinbase []byte) *Block { func (bc *ChainManager) NewBlock(coinbase []byte) *types.Block {
var root interface{} var root interface{}
hash := ZeroHash256 hash := ZeroHash256
@ -98,7 +104,7 @@ func (bc *ChainManager) NewBlock(coinbase []byte) *Block {
hash = bc.LastBlockHash hash = bc.LastBlockHash
} }
block := CreateBlock( block := types.CreateBlock(
root, root,
hash, hash,
coinbase, coinbase,
@ -122,7 +128,7 @@ func (bc *ChainManager) NewBlock(coinbase []byte) *Block {
func (bc *ChainManager) Reset() { func (bc *ChainManager) Reset() {
AddTestNetFunds(bc.genesisBlock) AddTestNetFunds(bc.genesisBlock)
bc.genesisBlock.state.Trie.Sync() bc.genesisBlock.Trie().Sync()
// Prepare the genesis block // Prepare the genesis block
bc.add(bc.genesisBlock) bc.add(bc.genesisBlock)
bc.CurrentBlock = bc.genesisBlock bc.CurrentBlock = bc.genesisBlock
@ -134,7 +140,7 @@ func (bc *ChainManager) Reset() {
} }
// Add a block to the chain and record addition information // Add a block to the chain and record addition information
func (bc *ChainManager) add(block *Block) { func (bc *ChainManager) add(block *types.Block) {
bc.writeBlockInfo(block) bc.writeBlockInfo(block)
bc.CurrentBlock = block bc.CurrentBlock = block
@ -148,7 +154,7 @@ func (bc *ChainManager) add(block *Block) {
} }
// Accessors // Accessors
func (bc *ChainManager) Genesis() *Block { func (bc *ChainManager) Genesis() *types.Block {
return bc.genesisBlock return bc.genesisBlock
} }
@ -179,7 +185,7 @@ func (self *ChainManager) GetChainHashesFromHash(hash []byte, max uint64) (chain
return return
} }
func (self *ChainManager) GetBlock(hash []byte) *Block { func (self *ChainManager) GetBlock(hash []byte) *types.Block {
data, _ := ethutil.Config.Db.Get(hash) data, _ := ethutil.Config.Db.Get(hash)
if len(data) == 0 { if len(data) == 0 {
if self.workingChain != nil { if self.workingChain != nil {
@ -194,10 +200,10 @@ func (self *ChainManager) GetBlock(hash []byte) *Block {
return nil return nil
} }
return NewBlockFromBytes(data) return types.NewBlockFromBytes(data)
} }
func (self *ChainManager) GetBlockByNumber(num uint64) *Block { func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
block := self.CurrentBlock block := self.CurrentBlock
for ; block != nil; block = self.GetBlock(block.PrevHash) { for ; block != nil; block = self.GetBlock(block.PrevHash) {
if block.Number.Uint64() == num { if block.Number.Uint64() == num {
@ -217,7 +223,7 @@ func (bc *ChainManager) SetTotalDifficulty(td *big.Int) {
bc.TD = td bc.TD = td
} }
func (self *ChainManager) CalcTotalDiff(block *Block) (*big.Int, error) { func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
parent := self.GetBlock(block.PrevHash) parent := self.GetBlock(block.PrevHash)
if parent == nil { if parent == nil {
return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.PrevHash) return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.PrevHash)
@ -237,8 +243,8 @@ func (self *ChainManager) CalcTotalDiff(block *Block) (*big.Int, error) {
return td, nil return td, nil
} }
func (bc *ChainManager) BlockInfo(block *Block) BlockInfo { func (bc *ChainManager) BlockInfo(block *types.Block) types.BlockInfo {
bi := BlockInfo{} bi := types.BlockInfo{}
data, _ := ethutil.Config.Db.Get(append(block.Hash(), []byte("Info")...)) data, _ := ethutil.Config.Db.Get(append(block.Hash(), []byte("Info")...))
bi.RlpDecode(data) bi.RlpDecode(data)
@ -246,9 +252,9 @@ func (bc *ChainManager) BlockInfo(block *Block) BlockInfo {
} }
// Unexported method for writing extra non-essential block info to the db // Unexported method for writing extra non-essential block info to the db
func (bc *ChainManager) writeBlockInfo(block *Block) { func (bc *ChainManager) writeBlockInfo(block *types.Block) {
bc.LastBlockNumber++ bc.LastBlockNumber++
bi := BlockInfo{Number: bc.LastBlockNumber, Hash: block.Hash(), Parent: block.PrevHash, TD: bc.TD} bi := types.BlockInfo{Number: bc.LastBlockNumber, Hash: block.Hash(), Parent: block.PrevHash, TD: bc.TD}
// For now we use the block hash with the words "info" appended as key // For now we use the block hash with the words "info" appended as key
ethutil.Config.Db.Put(append(block.Hash(), []byte("Info")...), bi.RlpEncode()) ethutil.Config.Db.Put(append(block.Hash(), []byte("Info")...), bi.RlpEncode())
@ -271,8 +277,8 @@ func (self *ChainManager) InsertChain(chain *BlockChain) {
self.add(link.block) self.add(link.block)
self.SetTotalDifficulty(link.td) self.SetTotalDifficulty(link.td)
self.eth.EventMux().Post(NewBlockEvent{link.block}) //self.eth.EventMux().Post(NewBlockEvent{link.block})
self.eth.EventMux().Post(link.messages) //self.eth.EventMux().Post(link.messages)
} }
b, e := chain.Front(), chain.Back() b, e := chain.Front(), chain.Back()
@ -299,7 +305,7 @@ func (self *ChainManager) TestChain(chain *BlockChain) (td *big.Int, err error)
} }
var messages state.Messages var messages state.Messages
td, messages, err = self.eth.BlockManager().ProcessWithParent(block, parent) td, messages, err = self.processor.ProcessWithParent(block, parent) //self.eth.BlockManager().ProcessWithParent(block, parent)
if err != nil { if err != nil {
chainlogger.Infoln(err) chainlogger.Infoln(err)
chainlogger.Debugf("Block #%v failed (%x...)\n", block.Number, block.Hash()[0:4]) chainlogger.Debugf("Block #%v failed (%x...)\n", block.Number, block.Hash()[0:4])
@ -323,7 +329,7 @@ func (self *ChainManager) TestChain(chain *BlockChain) (td *big.Int, err error)
} }
type link struct { type link struct {
block *Block block *types.Block
messages state.Messages messages state.Messages
td *big.Int td *big.Int
} }
@ -332,7 +338,7 @@ type BlockChain struct {
*list.List *list.List
} }
func NewChain(blocks Blocks) *BlockChain { func NewChain(blocks types.Blocks) *BlockChain {
chain := &BlockChain{list.New()} chain := &BlockChain{list.New()}
for _, block := range blocks { for _, block := range blocks {
@ -353,10 +359,10 @@ func (self *BlockChain) RlpEncode() []byte {
type ChainIterator struct { type ChainIterator struct {
cm *ChainManager cm *ChainManager
block *Block // current block in the iterator block *types.Block // current block in the iterator
} }
func (self *ChainIterator) Prev() *Block { func (self *ChainIterator) Prev() *types.Block {
self.block = self.cm.GetBlock(self.block.PrevHash) self.block = self.cm.GetBlock(self.block.PrevHash)
return self.block return self.block
} }

View File

@ -6,6 +6,7 @@ import (
"math/rand" "math/rand"
"time" "time"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
@ -15,7 +16,7 @@ import (
var powlogger = logger.NewLogger("POW") var powlogger = logger.NewLogger("POW")
type PoW interface { type PoW interface {
Search(block *Block, stop <-chan struct{}) []byte Search(block *types.Block, stop <-chan struct{}) []byte
Verify(hash []byte, diff *big.Int, nonce []byte) bool Verify(hash []byte, diff *big.Int, nonce []byte) bool
GetHashrate() int64 GetHashrate() int64
Turbo(bool) Turbo(bool)
@ -35,7 +36,7 @@ func (pow *EasyPow) Turbo(on bool) {
pow.turbo = on pow.turbo = on
} }
func (pow *EasyPow) Search(block *Block, stop <-chan struct{}) []byte { func (pow *EasyPow) Search(block *types.Block, stop <-chan struct{}) []byte {
r := rand.New(rand.NewSource(time.Now().UnixNano())) r := rand.New(rand.NewSource(time.Now().UnixNano()))
hash := block.HashNoNonce() hash := block.HashNoNonce()
diff := block.Difficulty diff := block.Difficulty

View File

@ -1,10 +1,12 @@
package chain package chain
import "github.com/ethereum/go-ethereum/chain/types"
// TxPreEvent is posted when a transaction enters the transaction pool. // TxPreEvent is posted when a transaction enters the transaction pool.
type TxPreEvent struct{ Tx *Transaction } type TxPreEvent struct{ Tx *types.Transaction }
// TxPostEvent is posted when a transaction has been processed. // TxPostEvent is posted when a transaction has been processed.
type TxPostEvent struct{ Tx *Transaction } type TxPostEvent struct{ Tx *types.Transaction }
// NewBlockEvent is posted when a block has been imported. // NewBlockEvent is posted when a block has been imported.
type NewBlockEvent struct{ Block *Block } type NewBlockEvent struct{ Block *types.Block }

View File

@ -5,6 +5,7 @@ import (
"math" "math"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
) )
@ -24,7 +25,7 @@ type Filter struct {
Altered []AccountChange Altered []AccountChange
BlockCallback func(*Block) BlockCallback func(*types.Block)
MessageCallback func(state.Messages) MessageCallback func(state.Messages)
} }
@ -171,11 +172,11 @@ func (self *Filter) FilterMessages(msgs []*state.Message) []*state.Message {
return messages return messages
} }
func (self *Filter) bloomFilter(block *Block) bool { func (self *Filter) bloomFilter(block *types.Block) bool {
var fromIncluded, toIncluded bool var fromIncluded, toIncluded bool
if len(self.from) > 0 { if len(self.from) > 0 {
for _, from := range self.from { for _, from := range self.from {
if BloomLookup(block.LogsBloom, from) { if types.BloomLookup(block.LogsBloom, from) {
fromIncluded = true fromIncluded = true
break break
} }
@ -186,7 +187,7 @@ func (self *Filter) bloomFilter(block *Block) bool {
if len(self.to) > 0 { if len(self.to) > 0 {
for _, to := range self.to { for _, to := range self.to {
if BloomLookup(block.LogsBloom, ethutil.U256(new(big.Int).Add(ethutil.Big1, ethutil.BigD(to))).Bytes()) { if types.BloomLookup(block.LogsBloom, ethutil.U256(new(big.Int).Add(ethutil.Big1, ethutil.BigD(to))).Bytes()) {
toIncluded = true toIncluded = true
break break
} }

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/vm" "github.com/ethereum/go-ethereum/vm"
) )
@ -26,17 +27,17 @@ import (
*/ */
type StateTransition struct { type StateTransition struct {
coinbase, receiver []byte coinbase, receiver []byte
tx *Transaction tx *types.Transaction
gas, gasPrice *big.Int gas, gasPrice *big.Int
value *big.Int value *big.Int
data []byte data []byte
state *state.State state *state.State
block *Block block *types.Block
cb, rec, sen *state.StateObject cb, rec, sen *state.StateObject
} }
func NewStateTransition(coinbase *state.StateObject, tx *Transaction, state *state.State, block *Block) *StateTransition { func NewStateTransition(coinbase *state.StateObject, tx *types.Transaction, state *state.State, block *types.Block) *StateTransition {
return &StateTransition{coinbase.Address(), tx.Recipient, tx, new(big.Int), new(big.Int).Set(tx.GasPrice), tx.Value, tx.Data, state, block, coinbase, nil, nil} return &StateTransition{coinbase.Address(), tx.Recipient, tx, new(big.Int), new(big.Int).Set(tx.GasPrice), tx.Value, tx.Data, state, block, coinbase, nil, nil}
} }
@ -203,7 +204,7 @@ func (self *StateTransition) TransitionState() (err error) {
}) })
// Process the init code and create 'valid' contract // Process the init code and create 'valid' contract
if IsContractAddr(self.receiver) { if types.IsContractAddr(self.receiver) {
// Evaluate the initialization script // Evaluate the initialization script
// and use the return value as the // and use the return value as the
// script section for the state object. // script section for the state object.
@ -280,7 +281,7 @@ func (self *StateTransition) Eval(msg *state.Message, script []byte, context *st
} }
// Converts an transaction in to a state object // Converts an transaction in to a state object
func MakeContract(tx *Transaction, state *state.State) *state.StateObject { func MakeContract(tx *types.Transaction, state *state.State) *state.StateObject {
addr := tx.CreationAddress(state) addr := tx.CreationAddress(state)
contract := state.GetOrNewStateObject(addr) contract := state.GetOrNewStateObject(addr)

View File

@ -7,6 +7,7 @@ import (
"math/big" "math/big"
"sync" "sync"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/wire" "github.com/ethereum/go-ethereum/wire"
@ -16,7 +17,7 @@ var txplogger = logger.NewLogger("TXP")
const txPoolQueueSize = 50 const txPoolQueueSize = 50
type TxPoolHook chan *Transaction type TxPoolHook chan *types.Transaction
type TxMsgTy byte type TxMsgTy byte
const ( const (
@ -26,21 +27,21 @@ const (
var MinGasPrice = big.NewInt(10000000000000) var MinGasPrice = big.NewInt(10000000000000)
type TxMsg struct { type TxMsg struct {
Tx *Transaction Tx *types.Transaction
Type TxMsgTy Type TxMsgTy
} }
func EachTx(pool *list.List, it func(*Transaction, *list.Element) bool) { func EachTx(pool *list.List, it func(*types.Transaction, *list.Element) bool) {
for e := pool.Front(); e != nil; e = e.Next() { for e := pool.Front(); e != nil; e = e.Next() {
if it(e.Value.(*Transaction), e) { if it(e.Value.(*types.Transaction), e) {
break break
} }
} }
} }
func FindTx(pool *list.List, finder func(*Transaction, *list.Element) bool) *Transaction { func FindTx(pool *list.List, finder func(*types.Transaction, *list.Element) bool) *types.Transaction {
for e := pool.Front(); e != nil; e = e.Next() { for e := pool.Front(); e != nil; e = e.Next() {
if tx, ok := e.Value.(*Transaction); ok { if tx, ok := e.Value.(*types.Transaction); ok {
if finder(tx, e) { if finder(tx, e) {
return tx return tx
} }
@ -51,7 +52,7 @@ func FindTx(pool *list.List, finder func(*Transaction, *list.Element) bool) *Tra
} }
type TxProcessor interface { type TxProcessor interface {
ProcessTransaction(tx *Transaction) ProcessTransaction(tx *types.Transaction)
} }
// The tx pool a thread safe transaction pool handler. In order to // The tx pool a thread safe transaction pool handler. In order to
@ -65,7 +66,7 @@ type TxPool struct {
mutex sync.Mutex mutex sync.Mutex
// Queueing channel for reading and writing incoming // Queueing channel for reading and writing incoming
// transactions to // transactions to
queueChan chan *Transaction queueChan chan *types.Transaction
// Quiting channel // Quiting channel
quit chan bool quit chan bool
// The actual pool // The actual pool
@ -79,14 +80,14 @@ type TxPool struct {
func NewTxPool(ethereum EthManager) *TxPool { func NewTxPool(ethereum EthManager) *TxPool {
return &TxPool{ return &TxPool{
pool: list.New(), pool: list.New(),
queueChan: make(chan *Transaction, txPoolQueueSize), queueChan: make(chan *types.Transaction, txPoolQueueSize),
quit: make(chan bool), quit: make(chan bool),
Ethereum: ethereum, Ethereum: ethereum,
} }
} }
// Blocking function. Don't use directly. Use QueueTransaction instead // Blocking function. Don't use directly. Use QueueTransaction instead
func (pool *TxPool) addTransaction(tx *Transaction) { func (pool *TxPool) addTransaction(tx *types.Transaction) {
pool.mutex.Lock() pool.mutex.Lock()
defer pool.mutex.Unlock() defer pool.mutex.Unlock()
@ -96,7 +97,7 @@ func (pool *TxPool) addTransaction(tx *Transaction) {
pool.Ethereum.Broadcast(wire.MsgTxTy, []interface{}{tx.RlpData()}) pool.Ethereum.Broadcast(wire.MsgTxTy, []interface{}{tx.RlpData()})
} }
func (pool *TxPool) ValidateTransaction(tx *Transaction) error { func (pool *TxPool) ValidateTransaction(tx *types.Transaction) error {
// Get the last block so we can retrieve the sender and receiver from // Get the last block so we can retrieve the sender and receiver from
// the merkle trie // the merkle trie
block := pool.Ethereum.ChainManager().CurrentBlock block := pool.Ethereum.ChainManager().CurrentBlock
@ -142,7 +143,7 @@ out:
select { select {
case tx := <-pool.queueChan: case tx := <-pool.queueChan:
hash := tx.Hash() hash := tx.Hash()
foundTx := FindTx(pool.pool, func(tx *Transaction, e *list.Element) bool { foundTx := FindTx(pool.pool, func(tx *types.Transaction, e *list.Element) bool {
return bytes.Compare(tx.Hash(), hash) == 0 return bytes.Compare(tx.Hash(), hash) == 0
}) })
@ -172,18 +173,18 @@ out:
} }
} }
func (pool *TxPool) QueueTransaction(tx *Transaction) { func (pool *TxPool) QueueTransaction(tx *types.Transaction) {
pool.queueChan <- tx pool.queueChan <- tx
} }
func (pool *TxPool) CurrentTransactions() []*Transaction { func (pool *TxPool) CurrentTransactions() []*types.Transaction {
pool.mutex.Lock() pool.mutex.Lock()
defer pool.mutex.Unlock() defer pool.mutex.Unlock()
txList := make([]*Transaction, pool.pool.Len()) txList := make([]*types.Transaction, pool.pool.Len())
i := 0 i := 0
for e := pool.pool.Front(); e != nil; e = e.Next() { for e := pool.pool.Front(); e != nil; e = e.Next() {
tx := e.Value.(*Transaction) tx := e.Value.(*types.Transaction)
txList[i] = tx txList[i] = tx
@ -198,7 +199,7 @@ func (pool *TxPool) RemoveInvalid(state *state.State) {
defer pool.mutex.Unlock() defer pool.mutex.Unlock()
for e := pool.pool.Front(); e != nil; e = e.Next() { for e := pool.pool.Front(); e != nil; e = e.Next() {
tx := e.Value.(*Transaction) tx := e.Value.(*types.Transaction)
sender := state.GetAccount(tx.Sender()) sender := state.GetAccount(tx.Sender())
err := pool.ValidateTransaction(tx) err := pool.ValidateTransaction(tx)
if err != nil || sender.Nonce >= tx.Nonce { if err != nil || sender.Nonce >= tx.Nonce {
@ -207,12 +208,12 @@ func (pool *TxPool) RemoveInvalid(state *state.State) {
} }
} }
func (self *TxPool) RemoveSet(txs Transactions) { func (self *TxPool) RemoveSet(txs types.Transactions) {
self.mutex.Lock() self.mutex.Lock()
defer self.mutex.Unlock() defer self.mutex.Unlock()
for _, tx := range txs { for _, tx := range txs {
EachTx(self.pool, func(t *Transaction, element *list.Element) bool { EachTx(self.pool, func(t *types.Transaction, element *list.Element) bool {
if t == tx { if t == tx {
self.pool.Remove(element) self.pool.Remove(element)
return true // To stop the loop return true // To stop the loop
@ -222,7 +223,7 @@ func (self *TxPool) RemoveSet(txs Transactions) {
} }
} }
func (pool *TxPool) Flush() []*Transaction { func (pool *TxPool) Flush() []*types.Transaction {
txList := pool.CurrentTransactions() txList := pool.CurrentTransactions()
// Recreate a new list all together // Recreate a new list all together

View File

@ -1 +0,0 @@
package chain

View File

@ -1,4 +1,4 @@
package chain package types
import ( import (
"bytes" "bytes"
@ -156,7 +156,7 @@ func (block *Block) State() *state.State {
return block.state return block.state
} }
func (block *Block) Transactions() []*Transaction { func (block *Block) Transactions() Transactions {
return block.transactions return block.transactions
} }

View File

@ -1,4 +1,4 @@
package chain package types
import ( import (
"math/big" "math/big"

View File

@ -1,7 +1,8 @@
package chain package types
import ( import (
"testing" "testing"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
) )

10
chain/types/common.go Normal file
View File

@ -0,0 +1,10 @@
package types
import (
"math/big"
"github.com/ethereum/go-ethereum/state"
)
type BlockProcessor interface {
ProcessWithParent(*Block, *Block) (*big.Int, state.Messages, error)
}

View File

@ -1,4 +1,4 @@
package chain package types
import ( import (
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"

View File

@ -1,4 +1,4 @@
package chain package types
import ( import (
"bytes" "bytes"
@ -16,6 +16,10 @@ type Receipt struct {
logs state.Logs logs state.Logs
} }
func NewReceipt(root []byte, cumalativeGasUsed *big.Int) *Receipt {
return &Receipt{PostState: ethutil.CopyBytes(root), CumulativeGasUsed: cumalativeGasUsed}
}
func NewRecieptFromValue(val *ethutil.Value) *Receipt { func NewRecieptFromValue(val *ethutil.Value) *Receipt {
r := &Receipt{} r := &Receipt{}
r.RlpValueDecode(val) r.RlpValueDecode(val)
@ -23,6 +27,10 @@ func NewRecieptFromValue(val *ethutil.Value) *Receipt {
return r return r
} }
func (self *Receipt) SetLogs(logs state.Logs) {
self.logs = logs
}
func (self *Receipt) RlpValueDecode(decoder *ethutil.Value) { func (self *Receipt) RlpValueDecode(decoder *ethutil.Value) {
self.PostState = decoder.Get(0).Bytes() self.PostState = decoder.Get(0).Bytes()
self.CumulativeGasUsed = decoder.Get(1).BigInt() self.CumulativeGasUsed = decoder.Get(1).BigInt()

View File

@ -1,4 +1,4 @@
package chain package types
import ( import (
"fmt" "fmt"

View File

@ -0,0 +1 @@
package types

View File

@ -3,17 +3,18 @@ package chain
import ( import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/vm" "github.com/ethereum/go-ethereum/vm"
) )
type VMEnv struct { type VMEnv struct {
state *state.State state *state.State
block *Block block *types.Block
tx *Transaction tx *types.Transaction
} }
func NewEnv(state *state.State, tx *Transaction, block *Block) *VMEnv { func NewEnv(state *state.State, tx *types.Transaction, block *types.Block) *VMEnv {
return &VMEnv{ return &VMEnv{
state: state, state: state,
block: block, block: block,

View File

@ -21,8 +21,7 @@ import (
"encoding/json" "encoding/json"
"os" "os"
"strconv" "strconv"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
@ -106,7 +105,7 @@ func (self *Gui) DumpState(hash, path string) {
if len(hash) == 0 { if len(hash) == 0 {
stateDump = self.eth.BlockManager().CurrentState().Dump() stateDump = self.eth.BlockManager().CurrentState().Dump()
} else { } else {
var block *chain.Block var block *types.Block
if hash[0] == '#' { if hash[0] == '#' {
i, _ := strconv.Atoi(hash[1:]) i, _ := strconv.Atoi(hash[1:])
block = self.eth.ChainManager().GetBlockByNumber(uint64(i)) block = self.eth.ChainManager().GetBlockByNumber(uint64(i))

View File

@ -21,6 +21,7 @@ import (
"encoding/json" "encoding/json"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/javascript" "github.com/ethereum/go-ethereum/javascript"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
@ -36,7 +37,7 @@ type AppContainer interface {
Window() *qml.Window Window() *qml.Window
Engine() *qml.Engine Engine() *qml.Engine
NewBlock(*chain.Block) NewBlock(*types.Block)
NewWatcher(chan bool) NewWatcher(chan bool)
Messages(state.Messages, string) Messages(state.Messages, string)
Post(string, int) Post(string, int)

View File

@ -32,6 +32,7 @@ import (
"github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
@ -290,7 +291,7 @@ func (self *Gui) loadMergedMiningOptions() {
} }
} }
func (gui *Gui) insertTransaction(window string, tx *chain.Transaction) { func (gui *Gui) insertTransaction(window string, tx *types.Transaction) {
pipe := xeth.New(gui.eth) pipe := xeth.New(gui.eth)
nameReg := pipe.World().Config().Get("NameReg") nameReg := pipe.World().Config().Get("NameReg")
addr := gui.address() addr := gui.address()
@ -340,7 +341,7 @@ func (gui *Gui) insertTransaction(window string, tx *chain.Transaction) {
func (gui *Gui) readPreviousTransactions() { func (gui *Gui) readPreviousTransactions() {
it := gui.txDb.NewIterator() it := gui.txDb.NewIterator()
for it.Next() { for it.Next() {
tx := chain.NewTransactionFromBytes(it.Value()) tx := types.NewTransactionFromBytes(it.Value())
gui.insertTransaction("post", tx) gui.insertTransaction("post", tx)
@ -348,7 +349,7 @@ func (gui *Gui) readPreviousTransactions() {
it.Release() it.Release()
} }
func (gui *Gui) processBlock(block *chain.Block, initial bool) { func (gui *Gui) processBlock(block *types.Block, initial bool) {
name := strings.Trim(gui.pipe.World().Config().Get("NameReg").Storage(block.Coinbase).Str(), "\x00") name := strings.Trim(gui.pipe.World().Config().Get("NameReg").Storage(block.Coinbase).Str(), "\x00")
b := xeth.NewJSBlock(block) b := xeth.NewJSBlock(block)
b.Name = name b.Name = name

View File

@ -26,8 +26,7 @@ import (
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/javascript" "github.com/ethereum/go-ethereum/javascript"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
@ -138,7 +137,7 @@ func (app *HtmlApplication) Window() *qml.Window {
return app.win return app.win
} }
func (app *HtmlApplication) NewBlock(block *chain.Block) { func (app *HtmlApplication) NewBlock(block *types.Block) {
b := &xeth.JSBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Bytes2Hex(block.Hash())} b := &xeth.JSBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Bytes2Hex(block.Hash())}
app.webView.Call("onNewBlockCb", b) app.webView.Call("onNewBlockCb", b)
} }

View File

@ -20,8 +20,7 @@ package main
import ( import (
"fmt" "fmt"
"runtime" "runtime"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/xeth" "github.com/ethereum/go-ethereum/xeth"
@ -65,7 +64,7 @@ func (app *QmlApplication) NewWatcher(quitChan chan bool) {
} }
// Events // Events
func (app *QmlApplication) NewBlock(block *chain.Block) { func (app *QmlApplication) NewBlock(block *types.Block) {
pblock := &xeth.JSBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Bytes2Hex(block.Hash())} pblock := &xeth.JSBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Bytes2Hex(block.Hash())}
app.win.Call("onNewBlockCb", pblock) app.win.Call("onNewBlockCb", pblock)
} }

View File

@ -26,6 +26,7 @@ import (
"github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/javascript" "github.com/ethereum/go-ethereum/javascript"
@ -126,7 +127,7 @@ func (self *UiLib) PastPeers() *ethutil.List {
} }
func (self *UiLib) ImportTx(rlpTx string) { func (self *UiLib) ImportTx(rlpTx string) {
tx := chain.NewTransactionFromBytes(ethutil.Hex2Bytes(rlpTx)) tx := types.NewTransactionFromBytes(ethutil.Hex2Bytes(rlpTx))
self.eth.TxPool().QueueTransaction(tx) self.eth.TxPool().QueueTransaction(tx)
} }
@ -228,7 +229,7 @@ func (self *UiLib) NewFilter(object map[string]interface{}) (id int) {
func (self *UiLib) NewFilterString(typ string) (id int) { func (self *UiLib) NewFilterString(typ string) (id int) {
filter := chain.NewFilter(self.eth) filter := chain.NewFilter(self.eth)
filter.BlockCallback = func(block *chain.Block) { filter.BlockCallback = func(block *types.Block) {
if self.win != nil && self.win.Root() != nil { if self.win != nil && self.win.Root() != nil {
self.win.Root().Call("invokeFilterCallback", "{}", id) self.win.Root().Call("invokeFilterCallback", "{}", id)
} else { } else {

View File

@ -2,21 +2,20 @@ package utils
import ( import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/vm" "github.com/ethereum/go-ethereum/vm"
) )
type VMEnv struct { type VMEnv struct {
state *state.State state *state.State
block *chain.Block block *types.Block
transactor []byte transactor []byte
value *big.Int value *big.Int
} }
func NewEnv(state *state.State, block *chain.Block, transactor []byte, value *big.Int) *VMEnv { func NewEnv(state *state.State, block *types.Block, transactor []byte, value *big.Int) *VMEnv {
return &VMEnv{ return &VMEnv{
state: state, state: state,
block: block, block: block,

View File

@ -129,8 +129,9 @@ func New(db ethutil.Database, clientIdentity wire.ClientIdentity, keyManager *cr
ethereum.blockPool = NewBlockPool(ethereum) ethereum.blockPool = NewBlockPool(ethereum)
ethereum.txPool = chain.NewTxPool(ethereum) ethereum.txPool = chain.NewTxPool(ethereum)
ethereum.blockChain = chain.NewChainManager(ethereum) ethereum.blockChain = chain.NewChainManager()
ethereum.blockManager = chain.NewBlockManager(ethereum) ethereum.blockManager = chain.NewBlockManager(ethereum)
ethereum.blockChain.SetProcessor(ethereum.blockManager)
// Start the tx pool // Start the tx pool
ethereum.txPool.Start() ethereum.txPool.Start()

View File

@ -9,6 +9,7 @@ import (
"github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
@ -130,7 +131,7 @@ func (self *JSRE) dump(call otto.FunctionCall) otto.Value {
var state *state.State var state *state.State
if len(call.ArgumentList) > 0 { if len(call.ArgumentList) > 0 {
var block *chain.Block var block *types.Block
if call.Argument(0).IsNumber() { if call.Argument(0).IsNumber() {
num, _ := call.Argument(0).ToInteger() num, _ := call.Argument(0).ToInteger()
block = self.ethereum.ChainManager().GetBlockByNumber(uint64(num)) block = self.ethereum.ChainManager().GetBlockByNumber(uint64(num))

View File

@ -31,6 +31,7 @@ import (
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/wire" "github.com/ethereum/go-ethereum/wire"
@ -44,7 +45,7 @@ type LocalTx struct {
Value string `json:"value"` Value string `json:"value"`
} }
func (self *LocalTx) Sign(key []byte) *chain.Transaction { func (self *LocalTx) Sign(key []byte) *types.Transaction {
return nil return nil
} }
@ -54,7 +55,7 @@ type Miner struct {
eth *eth.Ethereum eth *eth.Ethereum
events event.Subscription events event.Subscription
uncles chain.Blocks uncles types.Blocks
localTxs map[int]*LocalTx localTxs map[int]*LocalTx
localTxId int localTxId int
@ -212,7 +213,7 @@ func (self *Miner) mine() {
nonce := self.pow.Search(block, self.powQuitCh) nonce := self.pow.Search(block, self.powQuitCh)
if nonce != nil { if nonce != nil {
block.Nonce = nonce block.Nonce = nonce
lchain := chain.NewChain(chain.Blocks{block}) lchain := chain.NewChain(types.Blocks{block})
_, err := chainMan.TestChain(lchain) _, err := chainMan.TestChain(lchain)
if err != nil { if err != nil {
minerlogger.Infoln(err) minerlogger.Infoln(err)
@ -229,15 +230,15 @@ func (self *Miner) mine() {
} }
} }
func (self *Miner) finiliseTxs() chain.Transactions { func (self *Miner) finiliseTxs() types.Transactions {
// Sort the transactions by nonce in case of odd network propagation // Sort the transactions by nonce in case of odd network propagation
var txs chain.Transactions var txs types.Transactions
state := self.eth.BlockManager().TransState() state := self.eth.BlockManager().TransState()
// XXX This has to change. Coinbase is, for new, same as key. // XXX This has to change. Coinbase is, for new, same as key.
key := self.eth.KeyManager() key := self.eth.KeyManager()
for _, ltx := range self.localTxs { for _, ltx := range self.localTxs {
tx := chain.NewTransactionMessage(ltx.To, ethutil.Big(ltx.Value), ethutil.Big(ltx.Gas), ethutil.Big(ltx.GasPrice), ltx.Data) tx := types.NewTransactionMessage(ltx.To, ethutil.Big(ltx.Value), ethutil.Big(ltx.Gas), ethutil.Big(ltx.GasPrice), ltx.Data)
tx.Nonce = state.GetNonce(self.Coinbase) tx.Nonce = state.GetNonce(self.Coinbase)
state.SetNonce(self.Coinbase, tx.Nonce+1) state.SetNonce(self.Coinbase, tx.Nonce+1)
@ -247,7 +248,7 @@ func (self *Miner) finiliseTxs() chain.Transactions {
} }
txs = append(txs, self.eth.TxPool().CurrentTransactions()...) txs = append(txs, self.eth.TxPool().CurrentTransactions()...)
sort.Sort(chain.TxByNonce{txs}) sort.Sort(types.TxByNonce{txs})
return txs return txs
} }

11
peer.go
View File

@ -11,8 +11,7 @@ import (
"strings" "strings"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/wire" "github.com/ethereum/go-ethereum/wire"
@ -155,7 +154,7 @@ type Peer struct {
pingTime time.Duration pingTime time.Duration
pingStartTime time.Time pingStartTime time.Time
lastRequestedBlock *chain.Block lastRequestedBlock *types.Block
protocolCaps *ethutil.Value protocolCaps *ethutil.Value
} }
@ -429,7 +428,7 @@ func (p *Peer) HandleInbound() {
// in the TxPool where it will undergo validation and // in the TxPool where it will undergo validation and
// processing when a new block is found // processing when a new block is found
for i := 0; i < msg.Data.Len(); i++ { for i := 0; i < msg.Data.Len(); i++ {
tx := chain.NewTransactionFromValue(msg.Data.Get(i)) tx := types.NewTransactionFromValue(msg.Data.Get(i))
p.ethereum.TxPool().QueueTransaction(tx) p.ethereum.TxPool().QueueTransaction(tx)
} }
case wire.MsgGetPeersTy: case wire.MsgGetPeersTy:
@ -535,7 +534,7 @@ func (p *Peer) HandleInbound() {
it := msg.Data.NewIterator() it := msg.Data.NewIterator()
for it.Next() { for it.Next() {
block := chain.NewBlockFromRlpValue(it.Value()) block := types.NewBlockFromRlpValue(it.Value())
blockPool.Add(block, p) blockPool.Add(block, p)
p.lastBlockReceived = time.Now() p.lastBlockReceived = time.Now()
@ -543,7 +542,7 @@ func (p *Peer) HandleInbound() {
case wire.MsgNewBlockTy: case wire.MsgNewBlockTy:
var ( var (
blockPool = p.ethereum.blockPool blockPool = p.ethereum.blockPool
block = chain.NewBlockFromRlpValue(msg.Data.Get(0)) block = types.NewBlockFromRlpValue(msg.Data.Get(0))
td = msg.Data.Get(1).BigInt() td = msg.Data.Get(1).BigInt()
) )

View File

@ -6,6 +6,7 @@ import (
"sync/atomic" "sync/atomic"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
@ -209,7 +210,7 @@ func (self *JSXEth) Transact(key, toStr, valueStr, gasStr, gasPriceStr, codeStr
gas = ethutil.Big(gasStr) gas = ethutil.Big(gasStr)
gasPrice = ethutil.Big(gasPriceStr) gasPrice = ethutil.Big(gasPriceStr)
data []byte data []byte
tx *chain.Transaction tx *types.Transaction
) )
if ethutil.IsHex(codeStr) { if ethutil.IsHex(codeStr) {
@ -219,9 +220,9 @@ func (self *JSXEth) Transact(key, toStr, valueStr, gasStr, gasPriceStr, codeStr
} }
if contractCreation { if contractCreation {
tx = chain.NewContractCreationTx(value, gas, gasPrice, data) tx = types.NewContractCreationTx(value, gas, gasPrice, data)
} else { } else {
tx = chain.NewTransactionMessage(hash, value, gas, gasPrice, data) tx = types.NewTransactionMessage(hash, value, gas, gasPrice, data)
} }
acc := self.obj.BlockManager().TransState().GetOrNewStateObject(keyPair.Address()) acc := self.obj.BlockManager().TransState().GetOrNewStateObject(keyPair.Address())
@ -240,7 +241,7 @@ func (self *JSXEth) Transact(key, toStr, valueStr, gasStr, gasPriceStr, codeStr
} }
func (self *JSXEth) PushTx(txStr string) (*JSReceipt, error) { func (self *JSXEth) PushTx(txStr string) (*JSReceipt, error) {
tx := chain.NewTransactionFromBytes(ethutil.Hex2Bytes(txStr)) tx := types.NewTransactionFromBytes(ethutil.Hex2Bytes(txStr))
self.obj.TxPool().QueueTransaction(tx) self.obj.TxPool().QueueTransaction(tx)
return NewJSReciept(tx.CreatesContract(), tx.CreationAddress(self.World().State()), tx.Hash(), tx.Sender()), nil return NewJSReciept(tx.CreatesContract(), tx.CreationAddress(self.World().State()), tx.Hash(), tx.Sender()), nil
} }

View File

@ -6,6 +6,7 @@ import (
"strings" "strings"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
@ -14,7 +15,7 @@ import (
// Block interface exposed to QML // Block interface exposed to QML
type JSBlock struct { type JSBlock struct {
//Transactions string `json:"transactions"` //Transactions string `json:"transactions"`
ref *chain.Block ref *types.Block
Size string `json:"size"` Size string `json:"size"`
Number int `json:"number"` Number int `json:"number"`
Hash string `json:"hash"` Hash string `json:"hash"`
@ -31,7 +32,7 @@ type JSBlock struct {
} }
// Creates a new QML Block from a chain block // Creates a new QML Block from a chain block
func NewJSBlock(block *chain.Block) *JSBlock { func NewJSBlock(block *types.Block) *JSBlock {
if block == nil { if block == nil {
return &JSBlock{} return &JSBlock{}
} }
@ -79,7 +80,7 @@ func (self *JSBlock) GetTransaction(hash string) *JSTransaction {
} }
type JSTransaction struct { type JSTransaction struct {
ref *chain.Transaction ref *types.Transaction
Value string `json:"value"` Value string `json:"value"`
Gas string `json:"gas"` Gas string `json:"gas"`
@ -94,7 +95,7 @@ type JSTransaction struct {
Confirmations int `json:"confirmations"` Confirmations int `json:"confirmations"`
} }
func NewJSTx(tx *chain.Transaction, state *state.State) *JSTransaction { func NewJSTx(tx *types.Transaction, state *state.State) *JSTransaction {
hash := ethutil.Bytes2Hex(tx.Hash()) hash := ethutil.Bytes2Hex(tx.Hash())
receiver := ethutil.Bytes2Hex(tx.Recipient) receiver := ethutil.Bytes2Hex(tx.Recipient)
if receiver == "0000000000000000000000000000000000000000" { if receiver == "0000000000000000000000000000000000000000" {

View File

@ -9,6 +9,7 @@ import (
"strings" "strings"
"github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
@ -72,7 +73,7 @@ func (self *XEth) ExecuteObject(object *Object, data []byte, value, gas, price *
return ret, err return ret, err
} }
func (self *XEth) Block(hash []byte) *chain.Block { func (self *XEth) Block(hash []byte) *types.Block {
return self.blockChain.GetBlock(hash) return self.blockChain.GetBlock(hash)
} }
@ -115,7 +116,7 @@ func (self *XEth) Transact(key *crypto.KeyPair, rec []byte, value, gas, price *e
contractCreation = true contractCreation = true
} }
var tx *chain.Transaction var tx *types.Transaction
// Compile and assemble the given data // Compile and assemble the given data
if contractCreation { if contractCreation {
script, err := ethutil.Compile(string(data), false) script, err := ethutil.Compile(string(data), false)
@ -123,7 +124,7 @@ func (self *XEth) Transact(key *crypto.KeyPair, rec []byte, value, gas, price *e
return nil, err return nil, err
} }
tx = chain.NewContractCreationTx(value.BigInt(), gas.BigInt(), price.BigInt(), script) tx = types.NewContractCreationTx(value.BigInt(), gas.BigInt(), price.BigInt(), script)
} else { } else {
data := ethutil.StringToByteFunc(string(data), func(s string) (ret []byte) { data := ethutil.StringToByteFunc(string(data), func(s string) (ret []byte) {
slice := strings.Split(s, "\n") slice := strings.Split(s, "\n")
@ -134,7 +135,7 @@ func (self *XEth) Transact(key *crypto.KeyPair, rec []byte, value, gas, price *e
return return
}) })
tx = chain.NewTransactionMessage(hash, value.BigInt(), gas.BigInt(), price.BigInt(), data) tx = types.NewTransactionMessage(hash, value.BigInt(), gas.BigInt(), price.BigInt(), data)
} }
acc := self.blockManager.TransState().GetOrNewStateObject(key.Address()) acc := self.blockManager.TransState().GetOrNewStateObject(key.Address())
@ -155,7 +156,7 @@ func (self *XEth) Transact(key *crypto.KeyPair, rec []byte, value, gas, price *e
return tx.Hash(), nil return tx.Hash(), nil
} }
func (self *XEth) PushTx(tx *chain.Transaction) ([]byte, error) { func (self *XEth) PushTx(tx *types.Transaction) ([]byte, error) {
self.obj.TxPool().QueueTransaction(tx) self.obj.TxPool().QueueTransaction(tx)
if tx.Recipient == nil { if tx.Recipient == nil {
addr := tx.CreationAddress(self.World().State()) addr := tx.CreationAddress(self.World().State())

View File

@ -2,20 +2,19 @@ package xeth
import ( import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/chain/types"
"github.com/ethereum/go-ethereum/chain"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/vm" "github.com/ethereum/go-ethereum/vm"
) )
type VMEnv struct { type VMEnv struct {
state *state.State state *state.State
block *chain.Block block *types.Block
value *big.Int value *big.Int
sender []byte sender []byte
} }
func NewEnv(state *state.State, block *chain.Block, value *big.Int, sender []byte) *VMEnv { func NewEnv(state *state.State, block *types.Block, value *big.Int, sender []byte) *VMEnv {
return &VMEnv{ return &VMEnv{
state: state, state: state,
block: block, block: block,