From af8f5f0b69f1c359991d12c7708804fe8dd1f944 Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 31 Oct 2014 14:43:14 +0100 Subject: ethstate => state --- chain/block.go | 10 +- chain/bloom9.go | 4 +- chain/filter.go | 12 +- chain/state_manager.go | 24 +-- chain/state_transition.go | 26 +-- chain/transaction.go | 8 +- chain/transaction_pool.go | 4 +- chain/vm_env.go | 28 ++-- cmd/mist/debugger.go | 20 +-- cmd/mist/ext_app.go | 8 +- cmd/mist/html_container.go | 4 +- cmd/mist/qml_container.go | 4 +- cmd/mist/ui_lib.go | 4 +- cmd/utils/vm_env.go | 28 ++-- ethereum.go | 6 +- ethstate/.ethtest | 0 ethstate/dump.go | 47 ------ ethstate/errors.go | 23 --- ethstate/log.go | 38 ----- ethstate/manifest.go | 55 ------- ethstate/state.go | 321 ------------------------------------ ethstate/state_object.go | 339 --------------------------------------- ethstate/state_test.go | 36 ----- javascript/javascript_runtime.go | 4 +- javascript/types.go | 4 +- state/dump.go | 47 ++++++ state/errors.go | 23 +++ state/log.go | 38 +++++ state/manifest.go | 55 +++++++ state/state.go | 321 ++++++++++++++++++++++++++++++++++++ state/state_object.go | 339 +++++++++++++++++++++++++++++++++++++++ state/state_test.go | 36 +++++ vm/closure.go | 12 +- vm/debugger.go | 6 +- vm/environment.go | 6 +- vm/execution.go | 6 +- vm/vm_debug.go | 34 ++-- xeth/hexface.go | 4 +- xeth/js_types.go | 6 +- xeth/object.go | 4 +- xeth/pipe.go | 6 +- xeth/vm_env.go | 28 ++-- xeth/world.go | 10 +- 43 files changed, 1019 insertions(+), 1019 deletions(-) delete mode 100644 ethstate/.ethtest delete mode 100644 ethstate/dump.go delete mode 100644 ethstate/errors.go delete mode 100644 ethstate/log.go delete mode 100644 ethstate/manifest.go delete mode 100644 ethstate/state.go delete mode 100644 ethstate/state_object.go delete mode 100644 ethstate/state_test.go create mode 100644 state/dump.go create mode 100644 state/errors.go create mode 100644 state/log.go create mode 100644 state/manifest.go create mode 100644 state/state.go create mode 100644 state/state_object.go create mode 100644 state/state_test.go diff --git a/chain/block.go b/chain/block.go index abad6f3d2..7e39aa2c9 100644 --- a/chain/block.go +++ b/chain/block.go @@ -8,9 +8,9 @@ import ( "time" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethtrie" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) type BlockInfo struct { @@ -77,7 +77,7 @@ type Block struct { Coinbase []byte // Block Trie state //state *ethutil.Trie - state *ethstate.State + state *state.State // Difficulty for the current block Difficulty *big.Int // Creation time @@ -137,7 +137,7 @@ func CreateBlock(root interface{}, } block.SetUncles([]*Block{}) - block.state = ethstate.New(ethtrie.New(ethutil.Config.Db, root)) + block.state = state.New(ethtrie.New(ethutil.Config.Db, root)) return block } @@ -152,7 +152,7 @@ func (block *Block) HashNoNonce() []byte { return crypto.Sha3(ethutil.Encode(block.miningHeader())) } -func (block *Block) State() *ethstate.State { +func (block *Block) State() *state.State { return block.state } @@ -294,7 +294,7 @@ func (self *Block) setHeader(header *ethutil.Value) { self.PrevHash = header.Get(0).Bytes() self.UncleSha = header.Get(1).Bytes() self.Coinbase = header.Get(2).Bytes() - self.state = ethstate.New(ethtrie.New(ethutil.Config.Db, header.Get(3).Val)) + self.state = state.New(ethtrie.New(ethutil.Config.Db, header.Get(3).Val)) self.TxSha = header.Get(4).Bytes() self.ReceiptSha = header.Get(5).Bytes() self.LogsBloom = header.Get(6).Bytes() diff --git a/chain/bloom9.go b/chain/bloom9.go index 60cafdb4b..ced31cc30 100644 --- a/chain/bloom9.go +++ b/chain/bloom9.go @@ -3,8 +3,8 @@ package chain import ( "math/big" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) func CreateBloom(block *Block) []byte { @@ -17,7 +17,7 @@ func CreateBloom(block *Block) []byte { return bin.Bytes() } -func LogsBloom(logs ethstate.Logs) *big.Int { +func LogsBloom(logs state.Logs) *big.Int { bin := new(big.Int) for _, log := range logs { data := [][]byte{log.Address} diff --git a/chain/filter.go b/chain/filter.go index 2aecb4f58..0265a60fa 100644 --- a/chain/filter.go +++ b/chain/filter.go @@ -4,7 +4,7 @@ import ( "bytes" "math" - "github.com/ethereum/go-ethereum/ethstate" + "github.com/ethereum/go-ethereum/state" ) type AccountChange struct { @@ -23,7 +23,7 @@ type Filter struct { Altered []AccountChange BlockCallback func(*Block) - MessageCallback func(ethstate.Messages) + MessageCallback func(state.Messages) } // Create a new filter which uses a bloom filter on blocks to figure out whether a particular block @@ -72,7 +72,7 @@ func (self *Filter) SetSkip(skip int) { } // Run filters messages with the current parameters set -func (self *Filter) Find() []*ethstate.Message { +func (self *Filter) Find() []*state.Message { var earliestBlockNo uint64 = uint64(self.earliest) if self.earliest == -1 { earliestBlockNo = self.eth.ChainManager().CurrentBlock.Number.Uint64() @@ -83,7 +83,7 @@ func (self *Filter) Find() []*ethstate.Message { } var ( - messages []*ethstate.Message + messages []*state.Message block = self.eth.ChainManager().GetBlockByNumber(latestBlockNo) quit bool ) @@ -128,8 +128,8 @@ func includes(addresses [][]byte, a []byte) (found bool) { return } -func (self *Filter) FilterMessages(msgs []*ethstate.Message) []*ethstate.Message { - var messages []*ethstate.Message +func (self *Filter) FilterMessages(msgs []*state.Message) []*state.Message { + var messages []*state.Message // Filter the messages for interesting stuff for _, message := range msgs { diff --git a/chain/state_manager.go b/chain/state_manager.go index 8266726f5..b6bfbc22f 100644 --- a/chain/state_manager.go +++ b/chain/state_manager.go @@ -10,11 +10,11 @@ import ( "time" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethwire" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" + "github.com/ethereum/go-ethereum/state" ) var statelogger = logger.NewLogger("BLOCK") @@ -61,10 +61,10 @@ type StateManager struct { // Transiently state. The trans state isn't ever saved, validated and // it could be used for setting account nonces without effecting // the main states. - transState *ethstate.State + transState *state.State // Mining state. The mining state is used purely and solely by the mining // operation. - miningState *ethstate.State + miningState *state.State // The last attempted block is mainly used for debugging purposes // This does not have to be a valid block and will be set during @@ -112,19 +112,19 @@ func (self *StateManager) updateThread() { } } -func (sm *StateManager) CurrentState() *ethstate.State { +func (sm *StateManager) CurrentState() *state.State { return sm.eth.ChainManager().CurrentBlock.State() } -func (sm *StateManager) TransState() *ethstate.State { +func (sm *StateManager) TransState() *state.State { return sm.transState } -func (sm *StateManager) MiningState() *ethstate.State { +func (sm *StateManager) MiningState() *state.State { return sm.miningState } -func (sm *StateManager) NewMiningState() *ethstate.State { +func (sm *StateManager) NewMiningState() *state.State { sm.miningState = sm.eth.ChainManager().CurrentBlock.State().Copy() return sm.miningState @@ -134,7 +134,7 @@ func (sm *StateManager) ChainManager() *ChainManager { return sm.bc } -func (self *StateManager) ProcessTransactions(coinbase *ethstate.StateObject, state *ethstate.State, block, parent *Block, txs Transactions) (Receipts, Transactions, Transactions, Transactions, error) { +func (self *StateManager) ProcessTransactions(coinbase *state.StateObject, state *state.State, block, parent *Block, txs Transactions) (Receipts, Transactions, Transactions, Transactions, error) { var ( receipts Receipts handled, unhandled Transactions @@ -296,7 +296,7 @@ func (sm *StateManager) Process(block *Block) (err error) { return nil } -func (sm *StateManager) ApplyDiff(state *ethstate.State, parent, block *Block) (receipts Receipts, err error) { +func (sm *StateManager) ApplyDiff(state *state.State, parent, block *Block) (receipts Receipts, err error) { coinbase := state.GetOrNewStateObject(block.Coinbase) coinbase.SetGasPool(block.CalcGasLimit(parent)) @@ -372,7 +372,7 @@ func (sm *StateManager) ValidateBlock(block *Block) error { return nil } -func (sm *StateManager) AccumelateRewards(state *ethstate.State, block, parent *Block) error { +func (sm *StateManager) AccumelateRewards(state *state.State, block, parent *Block) error { reward := new(big.Int).Set(BlockReward) knownUncles := ethutil.Set(parent.Uncles) @@ -416,7 +416,7 @@ func (sm *StateManager) AccumelateRewards(state *ethstate.State, block, parent * } // Manifest will handle both creating notifications and generating bloom bin data -func (sm *StateManager) createBloomFilter(state *ethstate.State) *BloomFilter { +func (sm *StateManager) createBloomFilter(state *state.State) *BloomFilter { bloomf := NewBloomFilter(nil) for _, msg := range state.Manifest().Messages { @@ -429,7 +429,7 @@ func (sm *StateManager) createBloomFilter(state *ethstate.State) *BloomFilter { return bloomf } -func (sm *StateManager) GetMessages(block *Block) (messages []*ethstate.Message, err error) { +func (sm *StateManager) GetMessages(block *Block) (messages []*state.Message, err error) { if !sm.bc.HasBlock(block.PrevHash) { return nil, ParentError(block.PrevHash) } diff --git a/chain/state_transition.go b/chain/state_transition.go index 4c62633c5..41bdadedb 100644 --- a/chain/state_transition.go +++ b/chain/state_transition.go @@ -4,8 +4,8 @@ import ( "fmt" "math/big" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" ) @@ -31,17 +31,17 @@ type StateTransition struct { gas, gasPrice *big.Int value *big.Int data []byte - state *ethstate.State + state *state.State block *Block - cb, rec, sen *ethstate.StateObject + cb, rec, sen *state.StateObject } -func NewStateTransition(coinbase *ethstate.StateObject, tx *Transaction, state *ethstate.State, block *Block) *StateTransition { +func NewStateTransition(coinbase *state.StateObject, tx *Transaction, state *state.State, block *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} } -func (self *StateTransition) Coinbase() *ethstate.StateObject { +func (self *StateTransition) Coinbase() *state.StateObject { if self.cb != nil { return self.cb } @@ -49,7 +49,7 @@ func (self *StateTransition) Coinbase() *ethstate.StateObject { self.cb = self.state.GetOrNewStateObject(self.coinbase) return self.cb } -func (self *StateTransition) Sender() *ethstate.StateObject { +func (self *StateTransition) Sender() *state.StateObject { if self.sen != nil { return self.sen } @@ -58,7 +58,7 @@ func (self *StateTransition) Sender() *ethstate.StateObject { return self.sen } -func (self *StateTransition) Receiver() *ethstate.StateObject { +func (self *StateTransition) Receiver() *state.StateObject { if self.tx != nil && self.tx.CreatesContract() { return nil } @@ -143,7 +143,7 @@ func (self *StateTransition) TransitionState() (err error) { var ( tx = self.tx sender = self.Sender() - receiver *ethstate.StateObject + receiver *state.StateObject ) defer self.RefundGas() @@ -167,7 +167,7 @@ func (self *StateTransition) TransitionState() (err error) { return fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, sender.Balance) } - var snapshot *ethstate.State + var snapshot *state.State // If the receiver is nil it's a contract (\0*32). if tx.CreatesContract() { // Subtract the (irreversible) amount from the senders account @@ -195,7 +195,7 @@ func (self *StateTransition) TransitionState() (err error) { snapshot = self.state.Copy() } - msg := self.state.Manifest().AddMessage(ðstate.Message{ + msg := self.state.Manifest().AddMessage(&state.Message{ To: receiver.Address(), From: sender.Address(), Input: self.tx.Data, Origin: sender.Address(), @@ -232,14 +232,14 @@ func (self *StateTransition) TransitionState() (err error) { } else { // Add default LOG. Default = big(sender.addr) + 1 addr := ethutil.BigD(receiver.Address()) - self.state.AddLog(ethstate.Log{sender.Address(), [][]byte{ethutil.U256(addr.Add(addr, ethutil.Big1)).Bytes()}, nil}) + self.state.AddLog(state.Log{sender.Address(), [][]byte{ethutil.U256(addr.Add(addr, ethutil.Big1)).Bytes()}, nil}) } } return } -func (self *StateTransition) Eval(msg *ethstate.Message, script []byte, context *ethstate.StateObject) (ret []byte, err error) { +func (self *StateTransition) Eval(msg *state.Message, script []byte, context *state.StateObject) (ret []byte, err error) { var ( transactor = self.Sender() state = self.state @@ -254,7 +254,7 @@ func (self *StateTransition) Eval(msg *ethstate.Message, script []byte, context } // Converts an transaction in to a state object -func MakeContract(tx *Transaction, state *ethstate.State) *ethstate.StateObject { +func MakeContract(tx *Transaction, state *state.State) *state.StateObject { addr := tx.CreationAddress(state) contract := state.GetOrNewStateObject(addr) diff --git a/chain/transaction.go b/chain/transaction.go index 416ffbc6c..d393f0384 100644 --- a/chain/transaction.go +++ b/chain/transaction.go @@ -6,8 +6,8 @@ import ( "math/big" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" "github.com/obscuren/secp256k1-go" ) @@ -78,7 +78,7 @@ func (tx *Transaction) IsContract() bool { return tx.CreatesContract() } -func (tx *Transaction) CreationAddress(state *ethstate.State) []byte { +func (tx *Transaction) CreationAddress(state *state.State) []byte { // Generate a new address addr := crypto.Sha3(ethutil.NewValue([]interface{}{tx.Sender(), tx.Nonce}).Encode())[12:] //for i := uint64(0); state.GetStateObject(addr) != nil; i++ { @@ -205,7 +205,7 @@ type Receipt struct { PostState []byte CumulativeGasUsed *big.Int Bloom []byte - logs ethstate.Logs + logs state.Logs } func NewRecieptFromValue(val *ethutil.Value) *Receipt { @@ -222,7 +222,7 @@ func (self *Receipt) RlpValueDecode(decoder *ethutil.Value) { it := decoder.Get(3).NewIterator() for it.Next() { - self.logs = append(self.logs, ethstate.NewLogFromValue(it.Value())) + self.logs = append(self.logs, state.NewLogFromValue(it.Value())) } } diff --git a/chain/transaction_pool.go b/chain/transaction_pool.go index 21d501dfc..3e3787eed 100644 --- a/chain/transaction_pool.go +++ b/chain/transaction_pool.go @@ -7,9 +7,9 @@ import ( "math/big" "sync" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethwire" "github.com/ethereum/go-ethereum/logger" + "github.com/ethereum/go-ethereum/state" ) var txplogger = logger.NewLogger("TXP") @@ -193,7 +193,7 @@ func (pool *TxPool) CurrentTransactions() []*Transaction { return txList } -func (pool *TxPool) RemoveInvalid(state *ethstate.State) { +func (pool *TxPool) RemoveInvalid(state *state.State) { pool.mutex.Lock() defer pool.mutex.Unlock() diff --git a/chain/vm_env.go b/chain/vm_env.go index d42351713..53092bd10 100644 --- a/chain/vm_env.go +++ b/chain/vm_env.go @@ -3,17 +3,17 @@ package chain import ( "math/big" - "github.com/ethereum/go-ethereum/ethstate" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" ) type VMEnv struct { - state *ethstate.State + state *state.State block *Block tx *Transaction } -func NewEnv(state *ethstate.State, tx *Transaction, block *Block) *VMEnv { +func NewEnv(state *state.State, tx *Transaction, block *Block) *VMEnv { return &VMEnv{ state: state, block: block, @@ -21,17 +21,17 @@ func NewEnv(state *ethstate.State, tx *Transaction, block *Block) *VMEnv { } } -func (self *VMEnv) Origin() []byte { return self.tx.Sender() } -func (self *VMEnv) BlockNumber() *big.Int { return self.block.Number } -func (self *VMEnv) PrevHash() []byte { return self.block.PrevHash } -func (self *VMEnv) Coinbase() []byte { return self.block.Coinbase } -func (self *VMEnv) Time() int64 { return self.block.Time } -func (self *VMEnv) Difficulty() *big.Int { return self.block.Difficulty } -func (self *VMEnv) BlockHash() []byte { return self.block.Hash() } -func (self *VMEnv) Value() *big.Int { return self.tx.Value } -func (self *VMEnv) State() *ethstate.State { return self.state } -func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit } -func (self *VMEnv) AddLog(log ethstate.Log) { +func (self *VMEnv) Origin() []byte { return self.tx.Sender() } +func (self *VMEnv) BlockNumber() *big.Int { return self.block.Number } +func (self *VMEnv) PrevHash() []byte { return self.block.PrevHash } +func (self *VMEnv) Coinbase() []byte { return self.block.Coinbase } +func (self *VMEnv) Time() int64 { return self.block.Time } +func (self *VMEnv) Difficulty() *big.Int { return self.block.Difficulty } +func (self *VMEnv) BlockHash() []byte { return self.block.Hash() } +func (self *VMEnv) Value() *big.Int { return self.tx.Value } +func (self *VMEnv) State() *state.State { return self.state } +func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit } +func (self *VMEnv) AddLog(log state.Log) { self.state.AddLog(log) } func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error { diff --git a/cmd/mist/debugger.go b/cmd/mist/debugger.go index fadc241ff..3fd48eec6 100644 --- a/cmd/mist/debugger.go +++ b/cmd/mist/debugger.go @@ -26,8 +26,8 @@ import ( "github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/cmd/utils" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" "gopkg.in/qml.v1" ) @@ -40,7 +40,7 @@ type DebuggerWindow struct { vm *vm.DebugVm Db *Debugger - state *ethstate.State + state *state.State } func NewDebuggerWindow(lib *UiLib) *DebuggerWindow { @@ -141,17 +141,17 @@ func (self *DebuggerWindow) Debug(valueStr, gasStr, gasPriceStr, scriptStr, data keyPair = self.lib.eth.KeyManager().KeyPair() ) - state := self.lib.eth.StateManager().TransState() + statedb := self.lib.eth.StateManager().TransState() account := self.lib.eth.StateManager().TransState().GetAccount(keyPair.Address()) - contract := ethstate.NewStateObject([]byte{0}) + contract := statedb.NewStateObject([]byte{0}) contract.SetBalance(value) self.SetAsm(script) block := self.lib.eth.ChainManager().CurrentBlock - callerClosure := vm.NewClosure(ðstate.Message{}, account, contract, script, gas, gasPrice) - env := utils.NewEnv(state, block, account.Address(), value) + callerClosure := vm.NewClosure(&state.Message{}, account, contract, script, gas, gasPrice) + env := utils.NewEnv(statedb, block, account.Address(), value) evm := vm.NewDebugVm(env) evm.Dbg = self.Db @@ -172,7 +172,7 @@ func (self *DebuggerWindow) Debug(valueStr, gasStr, gasPriceStr, scriptStr, data } } - state.Reset() + statedb.Reset() if !self.Db.interrupt { self.Db.done = true @@ -267,13 +267,13 @@ type storeVal struct { Key, Value string } -func (self *Debugger) BreakHook(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *ethstate.StateObject) bool { +func (self *Debugger) BreakHook(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *state.StateObject) bool { self.main.Logln("break on instr:", pc) return self.halting(pc, op, mem, stack, stateObject) } -func (self *Debugger) StepHook(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *ethstate.StateObject) bool { +func (self *Debugger) StepHook(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *state.StateObject) bool { return self.halting(pc, op, mem, stack, stateObject) } @@ -285,7 +285,7 @@ func (self *Debugger) BreakPoints() []int64 { return self.breakPoints } -func (d *Debugger) halting(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *ethstate.StateObject) bool { +func (d *Debugger) halting(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *state.StateObject) bool { d.win.Root().Call("setInstruction", pc) d.win.Root().Call("clearMem") d.win.Root().Call("clearStack") diff --git a/cmd/mist/ext_app.go b/cmd/mist/ext_app.go index 4a3ab1d2c..d004f98c5 100644 --- a/cmd/mist/ext_app.go +++ b/cmd/mist/ext_app.go @@ -21,9 +21,9 @@ import ( "encoding/json" "github.com/ethereum/go-ethereum/chain" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/javascript" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/ui/qt" "github.com/ethereum/go-ethereum/xeth" "gopkg.in/qml.v1" @@ -38,7 +38,7 @@ type AppContainer interface { NewBlock(*chain.Block) NewWatcher(chan bool) - Messages(ethstate.Messages, string) + Messages(state.Messages, string) Post(string, int) } @@ -80,7 +80,7 @@ func (app *ExtApplication) run() { // Subscribe to events mux := app.lib.eth.EventMux() - app.events = mux.Subscribe(chain.NewBlockEvent{}, ethstate.Messages(nil)) + app.events = mux.Subscribe(chain.NewBlockEvent{}, state.Messages(nil)) // Call the main loop go app.mainLoop() @@ -109,7 +109,7 @@ func (app *ExtApplication) mainLoop() { case chain.NewBlockEvent: app.container.NewBlock(ev.Block) - case ethstate.Messages: + case state.Messages: for id, filter := range app.filters { msgs := filter.FilterMessages(ev) if len(msgs) > 0 { diff --git a/cmd/mist/html_container.go b/cmd/mist/html_container.go index 082d65f67..35e351b02 100644 --- a/cmd/mist/html_container.go +++ b/cmd/mist/html_container.go @@ -28,9 +28,9 @@ import ( "path/filepath" "github.com/ethereum/go-ethereum/chain" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/javascript" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/xeth" "github.com/howeyc/fsnotify" "gopkg.in/qml.v1" @@ -143,7 +143,7 @@ func (app *HtmlApplication) NewBlock(block *chain.Block) { app.webView.Call("onNewBlockCb", b) } -func (self *HtmlApplication) Messages(messages ethstate.Messages, id string) { +func (self *HtmlApplication) Messages(messages state.Messages, id string) { var msgs []javascript.JSMessage for _, m := range messages { msgs = append(msgs, javascript.NewJSMessage(m)) diff --git a/cmd/mist/qml_container.go b/cmd/mist/qml_container.go index 4f6ca0b7f..60013ec2b 100644 --- a/cmd/mist/qml_container.go +++ b/cmd/mist/qml_container.go @@ -22,8 +22,8 @@ import ( "runtime" "github.com/ethereum/go-ethereum/chain" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/xeth" "gopkg.in/qml.v1" ) @@ -70,7 +70,7 @@ func (app *QmlApplication) NewBlock(block *chain.Block) { app.win.Call("onNewBlockCb", pblock) } -func (self *QmlApplication) Messages(msgs ethstate.Messages, id string) { +func (self *QmlApplication) Messages(msgs state.Messages, id string) { fmt.Println("IMPLEMENT QML APPLICATION MESSAGES METHOD") } diff --git a/cmd/mist/ui_lib.go b/cmd/mist/ui_lib.go index 9d2554cf4..db299f18d 100644 --- a/cmd/mist/ui_lib.go +++ b/cmd/mist/ui_lib.go @@ -27,9 +27,9 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/javascript" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/ui/qt" "github.com/ethereum/go-ethereum/xeth" "gopkg.in/qml.v1" @@ -213,7 +213,7 @@ func (self *UiLib) StartDebugger() { func (self *UiLib) NewFilter(object map[string]interface{}) (id int) { filter := qt.NewFilterFromMap(object, self.eth) - filter.MessageCallback = func(messages ethstate.Messages) { + filter.MessageCallback = func(messages state.Messages) { self.win.Root().Call("invokeFilterCallback", xeth.ToJSMessages(messages), id) } id = self.eth.InstallFilter(filter) diff --git a/cmd/utils/vm_env.go b/cmd/utils/vm_env.go index 0a7b589ee..b06611cdd 100644 --- a/cmd/utils/vm_env.go +++ b/cmd/utils/vm_env.go @@ -4,19 +4,19 @@ import ( "math/big" "github.com/ethereum/go-ethereum/chain" - "github.com/ethereum/go-ethereum/ethstate" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" ) type VMEnv struct { - state *ethstate.State + state *state.State block *chain.Block transactor []byte value *big.Int } -func NewEnv(state *ethstate.State, block *chain.Block, transactor []byte, value *big.Int) *VMEnv { +func NewEnv(state *state.State, block *chain.Block, transactor []byte, value *big.Int) *VMEnv { return &VMEnv{ state: state, block: block, @@ -25,17 +25,17 @@ func NewEnv(state *ethstate.State, block *chain.Block, transactor []byte, value } } -func (self *VMEnv) Origin() []byte { return self.transactor } -func (self *VMEnv) BlockNumber() *big.Int { return self.block.Number } -func (self *VMEnv) PrevHash() []byte { return self.block.PrevHash } -func (self *VMEnv) Coinbase() []byte { return self.block.Coinbase } -func (self *VMEnv) Time() int64 { return self.block.Time } -func (self *VMEnv) Difficulty() *big.Int { return self.block.Difficulty } -func (self *VMEnv) BlockHash() []byte { return self.block.Hash() } -func (self *VMEnv) Value() *big.Int { return self.value } -func (self *VMEnv) State() *ethstate.State { return self.state } -func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit } -func (self *VMEnv) AddLog(ethstate.Log) {} +func (self *VMEnv) Origin() []byte { return self.transactor } +func (self *VMEnv) BlockNumber() *big.Int { return self.block.Number } +func (self *VMEnv) PrevHash() []byte { return self.block.PrevHash } +func (self *VMEnv) Coinbase() []byte { return self.block.Coinbase } +func (self *VMEnv) Time() int64 { return self.block.Time } +func (self *VMEnv) Difficulty() *big.Int { return self.block.Difficulty } +func (self *VMEnv) BlockHash() []byte { return self.block.Hash() } +func (self *VMEnv) Value() *big.Int { return self.value } +func (self *VMEnv) State() *state.State { return self.state } +func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit } +func (self *VMEnv) AddLog(state.Log) {} func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error { return vm.Transfer(from, to, amount) } diff --git a/ethereum.go b/ethereum.go index 9b456ad7c..d6f664349 100644 --- a/ethereum.go +++ b/ethereum.go @@ -16,12 +16,12 @@ import ( "github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethwire" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/rpc" + "github.com/ethereum/go-ethereum/state" ) const ( @@ -615,7 +615,7 @@ func (self *Ethereum) GetFilter(id int) *chain.Filter { func (self *Ethereum) filterLoop() { // Subscribe to events - events := self.eventMux.Subscribe(chain.NewBlockEvent{}, ethstate.Messages(nil)) + events := self.eventMux.Subscribe(chain.NewBlockEvent{}, state.Messages(nil)) for event := range events.Chan() { switch event := event.(type) { case chain.NewBlockEvent: @@ -627,7 +627,7 @@ func (self *Ethereum) filterLoop() { } self.filterMu.RUnlock() - case ethstate.Messages: + case state.Messages: self.filterMu.RLock() for _, filter := range self.filters { if filter.MessageCallback != nil { diff --git a/ethstate/.ethtest b/ethstate/.ethtest deleted file mode 100644 index e69de29bb..000000000 diff --git a/ethstate/dump.go b/ethstate/dump.go deleted file mode 100644 index fd92ac4df..000000000 --- a/ethstate/dump.go +++ /dev/null @@ -1,47 +0,0 @@ -package ethstate - -import ( - "encoding/json" - "fmt" - - "github.com/ethereum/go-ethereum/ethutil" -) - -type Account struct { - Balance string `json:"balance"` - Nonce uint64 `json:"nonce"` - CodeHash string `json:"codeHash"` - Storage map[string]string `json:"storage"` -} - -type World struct { - Root string `json:"root"` - Accounts map[string]Account `json:"accounts"` -} - -func (self *State) Dump() []byte { - world := World{ - Root: ethutil.Bytes2Hex(self.Trie.Root.([]byte)), - Accounts: make(map[string]Account), - } - - self.Trie.NewIterator().Each(func(key string, value *ethutil.Value) { - stateObject := NewStateObjectFromBytes([]byte(key), value.Bytes()) - - account := Account{Balance: stateObject.balance.String(), Nonce: stateObject.Nonce, CodeHash: ethutil.Bytes2Hex(stateObject.codeHash)} - account.Storage = make(map[string]string) - - stateObject.EachStorage(func(key string, value *ethutil.Value) { - value.Decode() - account.Storage[ethutil.Bytes2Hex([]byte(key))] = ethutil.Bytes2Hex(value.Bytes()) - }) - world.Accounts[ethutil.Bytes2Hex([]byte(key))] = account - }) - - json, err := json.MarshalIndent(world, "", " ") - if err != nil { - fmt.Println("dump err", err) - } - - return json -} diff --git a/ethstate/errors.go b/ethstate/errors.go deleted file mode 100644 index d5d7db86b..000000000 --- a/ethstate/errors.go +++ /dev/null @@ -1,23 +0,0 @@ -package ethstate - -import ( - "fmt" - "math/big" -) - -type GasLimitErr struct { - Message string - Is, Max *big.Int -} - -func IsGasLimitErr(err error) bool { - _, ok := err.(*GasLimitErr) - - return ok -} -func (err *GasLimitErr) Error() string { - return err.Message -} -func GasLimitError(is, max *big.Int) *GasLimitErr { - return &GasLimitErr{Message: fmt.Sprintf("GasLimit error. Max %s, transaction would take it to %s", max, is), Is: is, Max: max} -} diff --git a/ethstate/log.go b/ethstate/log.go deleted file mode 100644 index a2e9ca041..000000000 --- a/ethstate/log.go +++ /dev/null @@ -1,38 +0,0 @@ -package ethstate - -import "github.com/ethereum/go-ethereum/ethutil" - -type Log struct { - Address []byte - Topics [][]byte - Data []byte -} - -func NewLogFromValue(decoder *ethutil.Value) Log { - log := Log{ - Address: decoder.Get(0).Bytes(), - Data: decoder.Get(2).Bytes(), - } - - it := decoder.Get(1).NewIterator() - for it.Next() { - log.Topics = append(log.Topics, it.Value().Bytes()) - } - - return log -} - -func (self Log) RlpData() interface{} { - return []interface{}{self.Address, ethutil.ByteSliceToInterface(self.Topics), self.Data} -} - -type Logs []Log - -func (self Logs) RlpData() interface{} { - data := make([]interface{}, len(self)) - for i, log := range self { - data[i] = log.RlpData() - } - - return data -} diff --git a/ethstate/manifest.go b/ethstate/manifest.go deleted file mode 100644 index 945de22ab..000000000 --- a/ethstate/manifest.go +++ /dev/null @@ -1,55 +0,0 @@ -package ethstate - -import ( - "fmt" - "math/big" -) - -// Object manifest -// -// The object manifest is used to keep changes to the state so we can keep track of the changes -// that occurred during a state transitioning phase. -type Manifest struct { - Messages Messages -} - -func NewManifest() *Manifest { - m := &Manifest{} - m.Reset() - - return m -} - -func (m *Manifest) Reset() { - m.Messages = nil -} - -func (self *Manifest) AddMessage(msg *Message) *Message { - self.Messages = append(self.Messages, msg) - - return msg -} - -type Messages []*Message -type Message struct { - To, From []byte - Input []byte - Output []byte - Path int - Origin []byte - Timestamp int64 - Coinbase []byte - Block []byte - Number *big.Int - Value *big.Int - - ChangedAddresses [][]byte -} - -func (self *Message) AddStorageChange(addr []byte) { - self.ChangedAddresses = append(self.ChangedAddresses, addr) -} - -func (self *Message) String() string { - return fmt.Sprintf("Message{to: %x from: %x input: %x output: %x origin: %x coinbase: %x block: %x number: %v timestamp: %d path: %d value: %v", self.To, self.From, self.Input, self.Output, self.Origin, self.Coinbase, self.Block, self.Number, self.Timestamp, self.Path, self.Value) -} diff --git a/ethstate/state.go b/ethstate/state.go deleted file mode 100644 index 9025194e5..000000000 --- a/ethstate/state.go +++ /dev/null @@ -1,321 +0,0 @@ -package ethstate - -import ( - "math/big" - - "github.com/ethereum/go-ethereum/ethtrie" - "github.com/ethereum/go-ethereum/ethutil" - "github.com/ethereum/go-ethereum/logger" -) - -var statelogger = logger.NewLogger("STATE") - -// States within the ethereum protocol are used to store anything -// within the merkle trie. States take care of caching and storing -// nested states. It's the general query interface to retrieve: -// * Contracts -// * Accounts -type State struct { - // The trie for this structure - Trie *ethtrie.Trie - - stateObjects map[string]*StateObject - - manifest *Manifest - - refund map[string]*big.Int - - logs Logs -} - -// Create a new state from a given trie -func New(trie *ethtrie.Trie) *State { - return &State{Trie: trie, stateObjects: make(map[string]*StateObject), manifest: NewManifest(), refund: make(map[string]*big.Int)} -} - -func (self *State) EmptyLogs() { - self.logs = nil -} - -func (self *State) AddLog(log Log) { - self.logs = append(self.logs, log) -} - -func (self *State) Logs() Logs { - return self.logs -} - -// Retrieve the balance from the given address or 0 if object not found -func (self *State) GetBalance(addr []byte) *big.Int { - stateObject := self.GetStateObject(addr) - if stateObject != nil { - return stateObject.balance - } - - return ethutil.Big0 -} - -func (self *State) Refund(addr []byte, gas, price *big.Int) { - amount := new(big.Int).Mul(gas, price) - - if self.refund[string(addr)] == nil { - self.refund[string(addr)] = new(big.Int) - } - - self.refund[string(addr)] = new(big.Int).Add(self.refund[string(addr)], amount) -} - -func (self *State) AddBalance(addr []byte, amount *big.Int) { - stateObject := self.GetStateObject(addr) - if stateObject != nil { - stateObject.AddBalance(amount) - } -} - -func (self *State) GetNonce(addr []byte) uint64 { - stateObject := self.GetStateObject(addr) - if stateObject != nil { - return stateObject.Nonce - } - - return 0 -} - -func (self *State) SetNonce(addr []byte, nonce uint64) { - stateObject := self.GetStateObject(addr) - if stateObject != nil { - stateObject.Nonce = nonce - } -} - -func (self *State) GetCode(addr []byte) []byte { - stateObject := self.GetStateObject(addr) - if stateObject != nil { - return stateObject.Code - } - - return nil -} - -func (self *State) GetState(a, b []byte) []byte { - stateObject := self.GetStateObject(a) - if stateObject != nil { - return stateObject.GetState(b).Bytes() - } - - return nil -} - -func (self *State) SetState(addr, key []byte, value interface{}) { - stateObject := self.GetStateObject(addr) - if stateObject != nil { - stateObject.SetState(key, ethutil.NewValue(value)) - } -} - -func (self *State) Delete(addr []byte) bool { - stateObject := self.GetStateObject(addr) - if stateObject != nil { - stateObject.MarkForDeletion() - - return true - } - - return false -} - -// -// Setting, updating & deleting state object methods -// - -// Update the given state object and apply it to state trie -func (self *State) UpdateStateObject(stateObject *StateObject) { - addr := stateObject.Address() - - if len(stateObject.CodeHash()) > 0 { - ethutil.Config.Db.Put(stateObject.CodeHash(), stateObject.Code) - } - - self.Trie.Update(string(addr), string(stateObject.RlpEncode())) -} - -// Delete the given state object and delete it from the state trie -func (self *State) DeleteStateObject(stateObject *StateObject) { - self.Trie.Delete(string(stateObject.Address())) - - delete(self.stateObjects, string(stateObject.Address())) -} - -// Retrieve a state object given my the address. Nil if not found -func (self *State) GetStateObject(addr []byte) *StateObject { - addr = ethutil.Address(addr) - - stateObject := self.stateObjects[string(addr)] - if stateObject != nil { - return stateObject - } - - data := self.Trie.Get(string(addr)) - if len(data) == 0 { - return nil - } - - stateObject = NewStateObjectFromBytes(addr, []byte(data)) - self.SetStateObject(stateObject) - - return stateObject -} - -func (self *State) SetStateObject(object *StateObject) { - self.stateObjects[string(object.address)] = object -} - -// Retrieve a state object or create a new state object if nil -func (self *State) GetOrNewStateObject(addr []byte) *StateObject { - stateObject := self.GetStateObject(addr) - if stateObject == nil { - stateObject = self.NewStateObject(addr) - } - - return stateObject -} - -// Create a state object whether it exist in the trie or not -func (self *State) NewStateObject(addr []byte) *StateObject { - addr = ethutil.Address(addr) - - statelogger.Debugf("(+) %x\n", addr) - - stateObject := NewStateObject(addr) - self.stateObjects[string(addr)] = stateObject - - return stateObject -} - -// Deprecated -func (self *State) GetAccount(addr []byte) *StateObject { - return self.GetOrNewStateObject(addr) -} - -// -// Setting, copying of the state methods -// - -func (s *State) Cmp(other *State) bool { - return s.Trie.Cmp(other.Trie) -} - -func (self *State) Copy() *State { - if self.Trie != nil { - state := New(self.Trie.Copy()) - for k, stateObject := range self.stateObjects { - state.stateObjects[k] = stateObject.Copy() - } - - for addr, refund := range self.refund { - state.refund[addr] = refund - } - - logs := make(Logs, len(self.logs)) - copy(logs, self.logs) - state.logs = logs - - return state - } - - return nil -} - -func (self *State) Set(state *State) { - if state == nil { - panic("Tried setting 'state' to nil through 'Set'") - } - - self.Trie = state.Trie - self.stateObjects = state.stateObjects - self.refund = state.refund - self.logs = state.logs -} - -func (s *State) Root() interface{} { - return s.Trie.Root -} - -// Resets the trie and all siblings -func (s *State) Reset() { - s.Trie.Undo() - - // Reset all nested states - for _, stateObject := range s.stateObjects { - if stateObject.State == nil { - continue - } - - //stateObject.state.Reset() - stateObject.Reset() - } - - s.Empty() -} - -// Syncs the trie and all siblings -func (s *State) Sync() { - // Sync all nested states - for _, stateObject := range s.stateObjects { - if stateObject.State == nil { - continue - } - - stateObject.State.Sync() - } - - s.Trie.Sync() - - s.Empty() -} - -func (self *State) Empty() { - self.stateObjects = make(map[string]*StateObject) - self.refund = make(map[string]*big.Int) -} - -func (self *State) Update() { - var deleted bool - - // Refund any gas that's left - for addr, amount := range self.refund { - self.GetStateObject([]byte(addr)).AddBalance(amount) - } - - for _, stateObject := range self.stateObjects { - if stateObject.remove { - self.DeleteStateObject(stateObject) - deleted = true - } else { - stateObject.Sync() - - self.UpdateStateObject(stateObject) - } - } - - // FIXME trie delete is broken - if deleted { - valid, t2 := ethtrie.ParanoiaCheck(self.Trie) - if !valid { - statelogger.Infof("Warn: PARANOIA: Different state root during copy %x vs %x\n", self.Trie.Root, t2.Root) - - self.Trie = t2 - } - } -} - -func (self *State) Manifest() *Manifest { - return self.manifest -} - -// Debug stuff -func (self *State) CreateOutputForDiff() { - for _, stateObject := range self.stateObjects { - stateObject.CreateOutputForDiff() - } -} diff --git a/ethstate/state_object.go b/ethstate/state_object.go deleted file mode 100644 index d28a2b80d..000000000 --- a/ethstate/state_object.go +++ /dev/null @@ -1,339 +0,0 @@ -package ethstate - -import ( - "fmt" - "math/big" - - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethtrie" - "github.com/ethereum/go-ethereum/ethutil" -) - -type Code []byte - -func (self Code) String() string { - return string(self) //strings.Join(Disassemble(self), " ") -} - -type Storage map[string]*ethutil.Value - -func (self Storage) Copy() Storage { - cpy := make(Storage) - for key, value := range self { - // XXX Do we need a 'value' copy or is this sufficient? - cpy[key] = value - } - - return cpy -} - -type StateObject struct { - // Address of the object - address []byte - // Shared attributes - balance *big.Int - codeHash []byte - Nonce uint64 - // Contract related attributes - State *State - Code Code - InitCode Code - - storage Storage - - // Total gas pool is the total amount of gas currently - // left if this object is the coinbase. Gas is directly - // purchased of the coinbase. - gasPool *big.Int - - // Mark for deletion - // When an object is marked for deletion it will be delete from the trie - // during the "update" phase of the state transition - remove bool -} - -func (self *StateObject) Reset() { - self.storage = make(Storage) - self.State.Reset() -} - -func NewStateObject(addr []byte) *StateObject { - // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter. - address := ethutil.Address(addr) - - object := &StateObject{address: address, balance: new(big.Int), gasPool: new(big.Int)} - object.State = New(ethtrie.New(ethutil.Config.Db, "")) - object.storage = make(Storage) - object.gasPool = new(big.Int) - - return object -} - -func NewContract(address []byte, balance *big.Int, root []byte) *StateObject { - contract := NewStateObject(address) - contract.balance = balance - contract.State = New(ethtrie.New(ethutil.Config.Db, string(root))) - - return contract -} - -func NewStateObjectFromBytes(address, data []byte) *StateObject { - object := &StateObject{address: address} - object.RlpDecode(data) - - return object -} - -func (self *StateObject) MarkForDeletion() { - self.remove = true - statelogger.DebugDetailf("%x: #%d %v (deletion)\n", self.Address(), self.Nonce, self.balance) -} - -func (c *StateObject) GetAddr(addr []byte) *ethutil.Value { - return ethutil.NewValueFromBytes([]byte(c.State.Trie.Get(string(addr)))) -} - -func (c *StateObject) SetAddr(addr []byte, value interface{}) { - c.State.Trie.Update(string(addr), string(ethutil.NewValue(value).Encode())) -} - -func (self *StateObject) GetStorage(key *big.Int) *ethutil.Value { - return self.GetState(key.Bytes()) -} -func (self *StateObject) SetStorage(key *big.Int, value *ethutil.Value) { - self.SetState(key.Bytes(), value) -} - -func (self *StateObject) Storage() map[string]*ethutil.Value { - return self.storage -} - -func (self *StateObject) GetState(k []byte) *ethutil.Value { - key := ethutil.LeftPadBytes(k, 32) - - value := self.storage[string(key)] - if value == nil { - value = self.GetAddr(key) - - if !value.IsNil() { - self.storage[string(key)] = value - } - } - - return value -} - -func (self *StateObject) SetState(k []byte, value *ethutil.Value) { - key := ethutil.LeftPadBytes(k, 32) - self.storage[string(key)] = value.Copy() -} - -// Iterate over each storage address and yield callback -func (self *StateObject) EachStorage(cb ethtrie.EachCallback) { - // First loop over the uncommit/cached values in storage - for key, value := range self.storage { - // XXX Most iterators Fns as it stands require encoded values - encoded := ethutil.NewValue(value.Encode()) - cb(key, encoded) - } - - it := self.State.Trie.NewIterator() - it.Each(func(key string, value *ethutil.Value) { - // If it's cached don't call the callback. - if self.storage[key] == nil { - cb(key, value) - } - }) -} - -func (self *StateObject) Sync() { - for key, value := range self.storage { - if value.Len() == 0 { // value.BigInt().Cmp(ethutil.Big0) == 0 { - //data := self.getStorage([]byte(key)) - //fmt.Printf("deleting %x %x 0x%x\n", self.Address(), []byte(key), data) - self.State.Trie.Delete(string(key)) - continue - } - - self.SetAddr([]byte(key), value) - } - - valid, t2 := ethtrie.ParanoiaCheck(self.State.Trie) - if !valid { - statelogger.Infof("Warn: PARANOIA: Different state storage root during copy %x vs %x\n", self.State.Trie.Root, t2.Root) - - self.State.Trie = t2 - } -} - -func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value { - if int64(len(c.Code)-1) < pc.Int64() { - return ethutil.NewValue(0) - } - - return ethutil.NewValueFromBytes([]byte{c.Code[pc.Int64()]}) -} - -func (c *StateObject) AddBalance(amount *big.Int) { - c.SetBalance(new(big.Int).Add(c.balance, amount)) - - statelogger.Debugf("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce, c.balance, amount) -} -func (c *StateObject) AddAmount(amount *big.Int) { c.AddBalance(amount) } - -func (c *StateObject) SubBalance(amount *big.Int) { - c.SetBalance(new(big.Int).Sub(c.balance, amount)) - - statelogger.Debugf("%x: #%d %v (- %v)\n", c.Address(), c.Nonce, c.balance, amount) -} -func (c *StateObject) SubAmount(amount *big.Int) { c.SubBalance(amount) } - -func (c *StateObject) SetBalance(amount *big.Int) { - c.balance = amount -} - -func (self *StateObject) Balance() *big.Int { return self.balance } - -// -// Gas setters and getters -// - -// Return the gas back to the origin. Used by the Virtual machine or Closures -func (c *StateObject) ReturnGas(gas, price *big.Int) {} -func (c *StateObject) ConvertGas(gas, price *big.Int) error { - total := new(big.Int).Mul(gas, price) - if total.Cmp(c.balance) > 0 { - return fmt.Errorf("insufficient amount: %v, %v", c.balance, total) - } - - c.SubAmount(total) - - return nil -} - -func (self *StateObject) SetGasPool(gasLimit *big.Int) { - self.gasPool = new(big.Int).Set(gasLimit) - - statelogger.DebugDetailf("%x: fuel (+ %v)", self.Address(), self.gasPool) -} - -func (self *StateObject) BuyGas(gas, price *big.Int) error { - if self.gasPool.Cmp(gas) < 0 { - return GasLimitError(self.gasPool, gas) - } - - rGas := new(big.Int).Set(gas) - rGas.Mul(rGas, price) - - self.AddAmount(rGas) - - return nil -} - -func (self *StateObject) RefundGas(gas, price *big.Int) { - self.gasPool.Add(self.gasPool, gas) - - rGas := new(big.Int).Set(gas) - rGas.Mul(rGas, price) - - self.balance.Sub(self.balance, rGas) -} - -func (self *StateObject) Copy() *StateObject { - stateObject := NewStateObject(self.Address()) - stateObject.balance.Set(self.balance) - stateObject.codeHash = ethutil.CopyBytes(self.codeHash) - stateObject.Nonce = self.Nonce - if self.State != nil { - stateObject.State = self.State.Copy() - } - stateObject.Code = ethutil.CopyBytes(self.Code) - stateObject.InitCode = ethutil.CopyBytes(self.InitCode) - stateObject.storage = self.storage.Copy() - stateObject.gasPool.Set(self.gasPool) - stateObject.remove = self.remove - - return stateObject -} - -func (self *StateObject) Set(stateObject *StateObject) { - *self = *stateObject -} - -// -// Attribute accessors -// - -func (c *StateObject) N() *big.Int { - return big.NewInt(int64(c.Nonce)) -} - -// Returns the address of the contract/account -func (c *StateObject) Address() []byte { - return c.address -} - -// Returns the initialization Code -func (c *StateObject) Init() Code { - return c.InitCode -} - -// To satisfy ClosureRef -func (self *StateObject) Object() *StateObject { - return self -} - -// Debug stuff -func (self *StateObject) CreateOutputForDiff() { - fmt.Printf("%x %x %x %x\n", self.Address(), self.State.Root(), self.balance.Bytes(), self.Nonce) - self.EachStorage(func(addr string, value *ethutil.Value) { - fmt.Printf("%x %x\n", addr, value.Bytes()) - }) -} - -// -// Encoding -// - -// State object encoding methods -func (c *StateObject) RlpEncode() []byte { - var root interface{} - if c.State != nil { - root = c.State.Trie.Root - } else { - root = "" - } - - return ethutil.Encode([]interface{}{c.Nonce, c.balance, root, c.CodeHash()}) -} - -func (c *StateObject) CodeHash() ethutil.Bytes { - var codeHash []byte - if len(c.Code) > 0 { - codeHash = crypto.Sha3(c.Code) - } - - return codeHash -} - -func (c *StateObject) RlpDecode(data []byte) { - decoder := ethutil.NewValueFromBytes(data) - - c.Nonce = decoder.Get(0).Uint() - c.balance = decoder.Get(1).BigInt() - c.State = New(ethtrie.New(ethutil.Config.Db, decoder.Get(2).Interface())) - c.storage = make(map[string]*ethutil.Value) - c.gasPool = new(big.Int) - - c.codeHash = decoder.Get(3).Bytes() - - c.Code, _ = ethutil.Config.Db.Get(c.codeHash) -} - -// Storage change object. Used by the manifest for notifying changes to -// the sub channels. -type StorageState struct { - StateAddress []byte - Address []byte - Value *big.Int -} diff --git a/ethstate/state_test.go b/ethstate/state_test.go deleted file mode 100644 index 2454fce84..000000000 --- a/ethstate/state_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package ethstate - -import ( - "testing" - - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethtrie" - "github.com/ethereum/go-ethereum/ethutil" -) - -var ZeroHash256 = make([]byte, 32) - -func TestSnapshot(t *testing.T) { - db, _ := ethdb.NewMemDatabase() - ethutil.ReadConfig(".ethtest", "/tmp/ethtest", "") - ethutil.Config.Db = db - - state := New(ethtrie.New(db, "")) - - stateObject := state.GetOrNewStateObject([]byte("aa")) - - stateObject.SetStorage(ethutil.Big("0"), ethutil.NewValue(42)) - - snapshot := state.Copy() - - stateObject = state.GetStateObject([]byte("aa")) - stateObject.SetStorage(ethutil.Big("0"), ethutil.NewValue(43)) - - state.Set(snapshot) - - stateObject = state.GetStateObject([]byte("aa")) - res := stateObject.GetStorage(ethutil.Big("0")) - if !res.Cmp(ethutil.NewValue(42)) { - t.Error("Expected storage 0 to be 42", res) - } -} diff --git a/javascript/javascript_runtime.go b/javascript/javascript_runtime.go index 5885e5c6e..ea3cb6071 100644 --- a/javascript/javascript_runtime.go +++ b/javascript/javascript_runtime.go @@ -10,10 +10,10 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/cmd/utils" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/xeth" "github.com/obscuren/otto" ) @@ -127,7 +127,7 @@ func (self *JSRE) initStdFuncs() { */ func (self *JSRE) dump(call otto.FunctionCall) otto.Value { - var state *ethstate.State + var state *state.State if len(call.ArgumentList) > 0 { var block *chain.Block diff --git a/javascript/types.go b/javascript/types.go index a98c48905..d5acaecce 100644 --- a/javascript/types.go +++ b/javascript/types.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/ui" "github.com/ethereum/go-ethereum/xeth" "github.com/obscuren/otto" @@ -51,7 +51,7 @@ type JSMessage struct { Number int32 `json:"number"` } -func NewJSMessage(message *ethstate.Message) JSMessage { +func NewJSMessage(message *state.Message) JSMessage { return JSMessage{ To: ethutil.Bytes2Hex(message.To), From: ethutil.Bytes2Hex(message.From), diff --git a/state/dump.go b/state/dump.go new file mode 100644 index 000000000..de356f476 --- /dev/null +++ b/state/dump.go @@ -0,0 +1,47 @@ +package state + +import ( + "encoding/json" + "fmt" + + "github.com/ethereum/go-ethereum/ethutil" +) + +type Account struct { + Balance string `json:"balance"` + Nonce uint64 `json:"nonce"` + CodeHash string `json:"codeHash"` + Storage map[string]string `json:"storage"` +} + +type World struct { + Root string `json:"root"` + Accounts map[string]Account `json:"accounts"` +} + +func (self *State) Dump() []byte { + world := World{ + Root: ethutil.Bytes2Hex(self.Trie.Root.([]byte)), + Accounts: make(map[string]Account), + } + + self.Trie.NewIterator().Each(func(key string, value *ethutil.Value) { + stateObject := NewStateObjectFromBytes([]byte(key), value.Bytes()) + + account := Account{Balance: stateObject.balance.String(), Nonce: stateObject.Nonce, CodeHash: ethutil.Bytes2Hex(stateObject.codeHash)} + account.Storage = make(map[string]string) + + stateObject.EachStorage(func(key string, value *ethutil.Value) { + value.Decode() + account.Storage[ethutil.Bytes2Hex([]byte(key))] = ethutil.Bytes2Hex(value.Bytes()) + }) + world.Accounts[ethutil.Bytes2Hex([]byte(key))] = account + }) + + json, err := json.MarshalIndent(world, "", " ") + if err != nil { + fmt.Println("dump err", err) + } + + return json +} diff --git a/state/errors.go b/state/errors.go new file mode 100644 index 000000000..5a847d38b --- /dev/null +++ b/state/errors.go @@ -0,0 +1,23 @@ +package state + +import ( + "fmt" + "math/big" +) + +type GasLimitErr struct { + Message string + Is, Max *big.Int +} + +func IsGasLimitErr(err error) bool { + _, ok := err.(*GasLimitErr) + + return ok +} +func (err *GasLimitErr) Error() string { + return err.Message +} +func GasLimitError(is, max *big.Int) *GasLimitErr { + return &GasLimitErr{Message: fmt.Sprintf("GasLimit error. Max %s, transaction would take it to %s", max, is), Is: is, Max: max} +} diff --git a/state/log.go b/state/log.go new file mode 100644 index 000000000..73039d7ce --- /dev/null +++ b/state/log.go @@ -0,0 +1,38 @@ +package state + +import "github.com/ethereum/go-ethereum/ethutil" + +type Log struct { + Address []byte + Topics [][]byte + Data []byte +} + +func NewLogFromValue(decoder *ethutil.Value) Log { + log := Log{ + Address: decoder.Get(0).Bytes(), + Data: decoder.Get(2).Bytes(), + } + + it := decoder.Get(1).NewIterator() + for it.Next() { + log.Topics = append(log.Topics, it.Value().Bytes()) + } + + return log +} + +func (self Log) RlpData() interface{} { + return []interface{}{self.Address, ethutil.ByteSliceToInterface(self.Topics), self.Data} +} + +type Logs []Log + +func (self Logs) RlpData() interface{} { + data := make([]interface{}, len(self)) + for i, log := range self { + data[i] = log.RlpData() + } + + return data +} diff --git a/state/manifest.go b/state/manifest.go new file mode 100644 index 000000000..21cd04a1a --- /dev/null +++ b/state/manifest.go @@ -0,0 +1,55 @@ +package state + +import ( + "fmt" + "math/big" +) + +// Object manifest +// +// The object manifest is used to keep changes to the state so we can keep track of the changes +// that occurred during a state transitioning phase. +type Manifest struct { + Messages Messages +} + +func NewManifest() *Manifest { + m := &Manifest{} + m.Reset() + + return m +} + +func (m *Manifest) Reset() { + m.Messages = nil +} + +func (self *Manifest) AddMessage(msg *Message) *Message { + self.Messages = append(self.Messages, msg) + + return msg +} + +type Messages []*Message +type Message struct { + To, From []byte + Input []byte + Output []byte + Path int + Origin []byte + Timestamp int64 + Coinbase []byte + Block []byte + Number *big.Int + Value *big.Int + + ChangedAddresses [][]byte +} + +func (self *Message) AddStorageChange(addr []byte) { + self.ChangedAddresses = append(self.ChangedAddresses, addr) +} + +func (self *Message) String() string { + return fmt.Sprintf("Message{to: %x from: %x input: %x output: %x origin: %x coinbase: %x block: %x number: %v timestamp: %d path: %d value: %v", self.To, self.From, self.Input, self.Output, self.Origin, self.Coinbase, self.Block, self.Number, self.Timestamp, self.Path, self.Value) +} diff --git a/state/state.go b/state/state.go new file mode 100644 index 000000000..298cf9680 --- /dev/null +++ b/state/state.go @@ -0,0 +1,321 @@ +package state + +import ( + "math/big" + + "github.com/ethereum/go-ethereum/ethtrie" + "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/logger" +) + +var statelogger = logger.NewLogger("STATE") + +// States within the ethereum protocol are used to store anything +// within the merkle trie. States take care of caching and storing +// nested states. It's the general query interface to retrieve: +// * Contracts +// * Accounts +type State struct { + // The trie for this structure + Trie *ethtrie.Trie + + stateObjects map[string]*StateObject + + manifest *Manifest + + refund map[string]*big.Int + + logs Logs +} + +// Create a new state from a given trie +func New(trie *ethtrie.Trie) *State { + return &State{Trie: trie, stateObjects: make(map[string]*StateObject), manifest: NewManifest(), refund: make(map[string]*big.Int)} +} + +func (self *State) EmptyLogs() { + self.logs = nil +} + +func (self *State) AddLog(log Log) { + self.logs = append(self.logs, log) +} + +func (self *State) Logs() Logs { + return self.logs +} + +// Retrieve the balance from the given address or 0 if object not found +func (self *State) GetBalance(addr []byte) *big.Int { + stateObject := self.GetStateObject(addr) + if stateObject != nil { + return stateObject.balance + } + + return ethutil.Big0 +} + +func (self *State) Refund(addr []byte, gas, price *big.Int) { + amount := new(big.Int).Mul(gas, price) + + if self.refund[string(addr)] == nil { + self.refund[string(addr)] = new(big.Int) + } + + self.refund[string(addr)] = new(big.Int).Add(self.refund[string(addr)], amount) +} + +func (self *State) AddBalance(addr []byte, amount *big.Int) { + stateObject := self.GetStateObject(addr) + if stateObject != nil { + stateObject.AddBalance(amount) + } +} + +func (self *State) GetNonce(addr []byte) uint64 { + stateObject := self.GetStateObject(addr) + if stateObject != nil { + return stateObject.Nonce + } + + return 0 +} + +func (self *State) SetNonce(addr []byte, nonce uint64) { + stateObject := self.GetStateObject(addr) + if stateObject != nil { + stateObject.Nonce = nonce + } +} + +func (self *State) GetCode(addr []byte) []byte { + stateObject := self.GetStateObject(addr) + if stateObject != nil { + return stateObject.Code + } + + return nil +} + +func (self *State) GetState(a, b []byte) []byte { + stateObject := self.GetStateObject(a) + if stateObject != nil { + return stateObject.GetState(b).Bytes() + } + + return nil +} + +func (self *State) SetState(addr, key []byte, value interface{}) { + stateObject := self.GetStateObject(addr) + if stateObject != nil { + stateObject.SetState(key, ethutil.NewValue(value)) + } +} + +func (self *State) Delete(addr []byte) bool { + stateObject := self.GetStateObject(addr) + if stateObject != nil { + stateObject.MarkForDeletion() + + return true + } + + return false +} + +// +// Setting, updating & deleting state object methods +// + +// Update the given state object and apply it to state trie +func (self *State) UpdateStateObject(stateObject *StateObject) { + addr := stateObject.Address() + + if len(stateObject.CodeHash()) > 0 { + ethutil.Config.Db.Put(stateObject.CodeHash(), stateObject.Code) + } + + self.Trie.Update(string(addr), string(stateObject.RlpEncode())) +} + +// Delete the given state object and delete it from the state trie +func (self *State) DeleteStateObject(stateObject *StateObject) { + self.Trie.Delete(string(stateObject.Address())) + + delete(self.stateObjects, string(stateObject.Address())) +} + +// Retrieve a state object given my the address. Nil if not found +func (self *State) GetStateObject(addr []byte) *StateObject { + addr = ethutil.Address(addr) + + stateObject := self.stateObjects[string(addr)] + if stateObject != nil { + return stateObject + } + + data := self.Trie.Get(string(addr)) + if len(data) == 0 { + return nil + } + + stateObject = NewStateObjectFromBytes(addr, []byte(data)) + self.SetStateObject(stateObject) + + return stateObject +} + +func (self *State) SetStateObject(object *StateObject) { + self.stateObjects[string(object.address)] = object +} + +// Retrieve a state object or create a new state object if nil +func (self *State) GetOrNewStateObject(addr []byte) *StateObject { + stateObject := self.GetStateObject(addr) + if stateObject == nil { + stateObject = self.NewStateObject(addr) + } + + return stateObject +} + +// Create a state object whether it exist in the trie or not +func (self *State) NewStateObject(addr []byte) *StateObject { + addr = ethutil.Address(addr) + + statelogger.Debugf("(+) %x\n", addr) + + stateObject := NewStateObject(addr) + self.stateObjects[string(addr)] = stateObject + + return stateObject +} + +// Deprecated +func (self *State) GetAccount(addr []byte) *StateObject { + return self.GetOrNewStateObject(addr) +} + +// +// Setting, copying of the state methods +// + +func (s *State) Cmp(other *State) bool { + return s.Trie.Cmp(other.Trie) +} + +func (self *State) Copy() *State { + if self.Trie != nil { + state := New(self.Trie.Copy()) + for k, stateObject := range self.stateObjects { + state.stateObjects[k] = stateObject.Copy() + } + + for addr, refund := range self.refund { + state.refund[addr] = refund + } + + logs := make(Logs, len(self.logs)) + copy(logs, self.logs) + state.logs = logs + + return state + } + + return nil +} + +func (self *State) Set(state *State) { + if state == nil { + panic("Tried setting 'state' to nil through 'Set'") + } + + self.Trie = state.Trie + self.stateObjects = state.stateObjects + self.refund = state.refund + self.logs = state.logs +} + +func (s *State) Root() interface{} { + return s.Trie.Root +} + +// Resets the trie and all siblings +func (s *State) Reset() { + s.Trie.Undo() + + // Reset all nested states + for _, stateObject := range s.stateObjects { + if stateObject.State == nil { + continue + } + + //stateObject.state.Reset() + stateObject.Reset() + } + + s.Empty() +} + +// Syncs the trie and all siblings +func (s *State) Sync() { + // Sync all nested states + for _, stateObject := range s.stateObjects { + if stateObject.State == nil { + continue + } + + stateObject.State.Sync() + } + + s.Trie.Sync() + + s.Empty() +} + +func (self *State) Empty() { + self.stateObjects = make(map[string]*StateObject) + self.refund = make(map[string]*big.Int) +} + +func (self *State) Update() { + var deleted bool + + // Refund any gas that's left + for addr, amount := range self.refund { + self.GetStateObject([]byte(addr)).AddBalance(amount) + } + + for _, stateObject := range self.stateObjects { + if stateObject.remove { + self.DeleteStateObject(stateObject) + deleted = true + } else { + stateObject.Sync() + + self.UpdateStateObject(stateObject) + } + } + + // FIXME trie delete is broken + if deleted { + valid, t2 := ethtrie.ParanoiaCheck(self.Trie) + if !valid { + statelogger.Infof("Warn: PARANOIA: Different state root during copy %x vs %x\n", self.Trie.Root, t2.Root) + + self.Trie = t2 + } + } +} + +func (self *State) Manifest() *Manifest { + return self.manifest +} + +// Debug stuff +func (self *State) CreateOutputForDiff() { + for _, stateObject := range self.stateObjects { + stateObject.CreateOutputForDiff() + } +} diff --git a/state/state_object.go b/state/state_object.go new file mode 100644 index 000000000..fb568e543 --- /dev/null +++ b/state/state_object.go @@ -0,0 +1,339 @@ +package state + +import ( + "fmt" + "math/big" + + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethtrie" + "github.com/ethereum/go-ethereum/ethutil" +) + +type Code []byte + +func (self Code) String() string { + return string(self) //strings.Join(Disassemble(self), " ") +} + +type Storage map[string]*ethutil.Value + +func (self Storage) Copy() Storage { + cpy := make(Storage) + for key, value := range self { + // XXX Do we need a 'value' copy or is this sufficient? + cpy[key] = value + } + + return cpy +} + +type StateObject struct { + // Address of the object + address []byte + // Shared attributes + balance *big.Int + codeHash []byte + Nonce uint64 + // Contract related attributes + State *State + Code Code + InitCode Code + + storage Storage + + // Total gas pool is the total amount of gas currently + // left if this object is the coinbase. Gas is directly + // purchased of the coinbase. + gasPool *big.Int + + // Mark for deletion + // When an object is marked for deletion it will be delete from the trie + // during the "update" phase of the state transition + remove bool +} + +func (self *StateObject) Reset() { + self.storage = make(Storage) + self.State.Reset() +} + +func NewStateObject(addr []byte) *StateObject { + // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter. + address := ethutil.Address(addr) + + object := &StateObject{address: address, balance: new(big.Int), gasPool: new(big.Int)} + object.State = New(ethtrie.New(ethutil.Config.Db, "")) + object.storage = make(Storage) + object.gasPool = new(big.Int) + + return object +} + +func NewContract(address []byte, balance *big.Int, root []byte) *StateObject { + contract := NewStateObject(address) + contract.balance = balance + contract.State = New(ethtrie.New(ethutil.Config.Db, string(root))) + + return contract +} + +func NewStateObjectFromBytes(address, data []byte) *StateObject { + object := &StateObject{address: address} + object.RlpDecode(data) + + return object +} + +func (self *StateObject) MarkForDeletion() { + self.remove = true + statelogger.DebugDetailf("%x: #%d %v (deletion)\n", self.Address(), self.Nonce, self.balance) +} + +func (c *StateObject) GetAddr(addr []byte) *ethutil.Value { + return ethutil.NewValueFromBytes([]byte(c.State.Trie.Get(string(addr)))) +} + +func (c *StateObject) SetAddr(addr []byte, value interface{}) { + c.State.Trie.Update(string(addr), string(ethutil.NewValue(value).Encode())) +} + +func (self *StateObject) GetStorage(key *big.Int) *ethutil.Value { + return self.GetState(key.Bytes()) +} +func (self *StateObject) SetStorage(key *big.Int, value *ethutil.Value) { + self.SetState(key.Bytes(), value) +} + +func (self *StateObject) Storage() map[string]*ethutil.Value { + return self.storage +} + +func (self *StateObject) GetState(k []byte) *ethutil.Value { + key := ethutil.LeftPadBytes(k, 32) + + value := self.storage[string(key)] + if value == nil { + value = self.GetAddr(key) + + if !value.IsNil() { + self.storage[string(key)] = value + } + } + + return value +} + +func (self *StateObject) SetState(k []byte, value *ethutil.Value) { + key := ethutil.LeftPadBytes(k, 32) + self.storage[string(key)] = value.Copy() +} + +// Iterate over each storage address and yield callback +func (self *StateObject) EachStorage(cb ethtrie.EachCallback) { + // First loop over the uncommit/cached values in storage + for key, value := range self.storage { + // XXX Most iterators Fns as it stands require encoded values + encoded := ethutil.NewValue(value.Encode()) + cb(key, encoded) + } + + it := self.State.Trie.NewIterator() + it.Each(func(key string, value *ethutil.Value) { + // If it's cached don't call the callback. + if self.storage[key] == nil { + cb(key, value) + } + }) +} + +func (self *StateObject) Sync() { + for key, value := range self.storage { + if value.Len() == 0 { // value.BigInt().Cmp(ethutil.Big0) == 0 { + //data := self.getStorage([]byte(key)) + //fmt.Printf("deleting %x %x 0x%x\n", self.Address(), []byte(key), data) + self.State.Trie.Delete(string(key)) + continue + } + + self.SetAddr([]byte(key), value) + } + + valid, t2 := ethtrie.ParanoiaCheck(self.State.Trie) + if !valid { + statelogger.Infof("Warn: PARANOIA: Different state storage root during copy %x vs %x\n", self.State.Trie.Root, t2.Root) + + self.State.Trie = t2 + } +} + +func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value { + if int64(len(c.Code)-1) < pc.Int64() { + return ethutil.NewValue(0) + } + + return ethutil.NewValueFromBytes([]byte{c.Code[pc.Int64()]}) +} + +func (c *StateObject) AddBalance(amount *big.Int) { + c.SetBalance(new(big.Int).Add(c.balance, amount)) + + statelogger.Debugf("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce, c.balance, amount) +} +func (c *StateObject) AddAmount(amount *big.Int) { c.AddBalance(amount) } + +func (c *StateObject) SubBalance(amount *big.Int) { + c.SetBalance(new(big.Int).Sub(c.balance, amount)) + + statelogger.Debugf("%x: #%d %v (- %v)\n", c.Address(), c.Nonce, c.balance, amount) +} +func (c *StateObject) SubAmount(amount *big.Int) { c.SubBalance(amount) } + +func (c *StateObject) SetBalance(amount *big.Int) { + c.balance = amount +} + +func (self *StateObject) Balance() *big.Int { return self.balance } + +// +// Gas setters and getters +// + +// Return the gas back to the origin. Used by the Virtual machine or Closures +func (c *StateObject) ReturnGas(gas, price *big.Int) {} +func (c *StateObject) ConvertGas(gas, price *big.Int) error { + total := new(big.Int).Mul(gas, price) + if total.Cmp(c.balance) > 0 { + return fmt.Errorf("insufficient amount: %v, %v", c.balance, total) + } + + c.SubAmount(total) + + return nil +} + +func (self *StateObject) SetGasPool(gasLimit *big.Int) { + self.gasPool = new(big.Int).Set(gasLimit) + + statelogger.DebugDetailf("%x: fuel (+ %v)", self.Address(), self.gasPool) +} + +func (self *StateObject) BuyGas(gas, price *big.Int) error { + if self.gasPool.Cmp(gas) < 0 { + return GasLimitError(self.gasPool, gas) + } + + rGas := new(big.Int).Set(gas) + rGas.Mul(rGas, price) + + self.AddAmount(rGas) + + return nil +} + +func (self *StateObject) RefundGas(gas, price *big.Int) { + self.gasPool.Add(self.gasPool, gas) + + rGas := new(big.Int).Set(gas) + rGas.Mul(rGas, price) + + self.balance.Sub(self.balance, rGas) +} + +func (self *StateObject) Copy() *StateObject { + stateObject := NewStateObject(self.Address()) + stateObject.balance.Set(self.balance) + stateObject.codeHash = ethutil.CopyBytes(self.codeHash) + stateObject.Nonce = self.Nonce + if self.State != nil { + stateObject.State = self.State.Copy() + } + stateObject.Code = ethutil.CopyBytes(self.Code) + stateObject.InitCode = ethutil.CopyBytes(self.InitCode) + stateObject.storage = self.storage.Copy() + stateObject.gasPool.Set(self.gasPool) + stateObject.remove = self.remove + + return stateObject +} + +func (self *StateObject) Set(stateObject *StateObject) { + *self = *stateObject +} + +// +// Attribute accessors +// + +func (c *StateObject) N() *big.Int { + return big.NewInt(int64(c.Nonce)) +} + +// Returns the address of the contract/account +func (c *StateObject) Address() []byte { + return c.address +} + +// Returns the initialization Code +func (c *StateObject) Init() Code { + return c.InitCode +} + +// To satisfy ClosureRef +func (self *StateObject) Object() *StateObject { + return self +} + +// Debug stuff +func (self *StateObject) CreateOutputForDiff() { + fmt.Printf("%x %x %x %x\n", self.Address(), self.State.Root(), self.balance.Bytes(), self.Nonce) + self.EachStorage(func(addr string, value *ethutil.Value) { + fmt.Printf("%x %x\n", addr, value.Bytes()) + }) +} + +// +// Encoding +// + +// State object encoding methods +func (c *StateObject) RlpEncode() []byte { + var root interface{} + if c.State != nil { + root = c.State.Trie.Root + } else { + root = "" + } + + return ethutil.Encode([]interface{}{c.Nonce, c.balance, root, c.CodeHash()}) +} + +func (c *StateObject) CodeHash() ethutil.Bytes { + var codeHash []byte + if len(c.Code) > 0 { + codeHash = crypto.Sha3(c.Code) + } + + return codeHash +} + +func (c *StateObject) RlpDecode(data []byte) { + decoder := ethutil.NewValueFromBytes(data) + + c.Nonce = decoder.Get(0).Uint() + c.balance = decoder.Get(1).BigInt() + c.State = New(ethtrie.New(ethutil.Config.Db, decoder.Get(2).Interface())) + c.storage = make(map[string]*ethutil.Value) + c.gasPool = new(big.Int) + + c.codeHash = decoder.Get(3).Bytes() + + c.Code, _ = ethutil.Config.Db.Get(c.codeHash) +} + +// Storage change object. Used by the manifest for notifying changes to +// the sub channels. +type StorageState struct { + StateAddress []byte + Address []byte + Value *big.Int +} diff --git a/state/state_test.go b/state/state_test.go new file mode 100644 index 000000000..42f434ef0 --- /dev/null +++ b/state/state_test.go @@ -0,0 +1,36 @@ +package state + +import ( + "testing" + + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/ethtrie" + "github.com/ethereum/go-ethereum/ethutil" +) + +var ZeroHash256 = make([]byte, 32) + +func TestSnapshot(t *testing.T) { + db, _ := ethdb.NewMemDatabase() + ethutil.ReadConfig(".ethtest", "/tmp/ethtest", "") + ethutil.Config.Db = db + + state := New(ethtrie.New(db, "")) + + stateObject := state.GetOrNewStateObject([]byte("aa")) + + stateObject.SetStorage(ethutil.Big("0"), ethutil.NewValue(42)) + + snapshot := state.Copy() + + stateObject = state.GetStateObject([]byte("aa")) + stateObject.SetStorage(ethutil.Big("0"), ethutil.NewValue(43)) + + state.Set(snapshot) + + stateObject = state.GetStateObject([]byte("aa")) + res := stateObject.GetStorage(ethutil.Big("0")) + if !res.Cmp(ethutil.NewValue(42)) { + t.Error("Expected storage 0 to be 42", res) + } +} diff --git a/vm/closure.go b/vm/closure.go index b556bc03d..8e54e9ce6 100644 --- a/vm/closure.go +++ b/vm/closure.go @@ -5,14 +5,14 @@ package vm import ( "math/big" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) type ClosureRef interface { ReturnGas(*big.Int, *big.Int) Address() []byte - Object() *ethstate.StateObject + Object() *state.StateObject GetStorage(*big.Int) *ethutil.Value SetStorage(*big.Int, *ethutil.Value) } @@ -20,9 +20,9 @@ type ClosureRef interface { // Basic inline closure object which implement the 'closure' interface type Closure struct { caller ClosureRef - object *ethstate.StateObject + object *state.StateObject Code []byte - message *ethstate.Message + message *state.Message exe *Execution Gas, UsedGas, Price *big.Int @@ -31,7 +31,7 @@ type Closure struct { } // Create a new closure for the given data items -func NewClosure(msg *ethstate.Message, caller ClosureRef, object *ethstate.StateObject, code []byte, gas, price *big.Int) *Closure { +func NewClosure(msg *state.Message, caller ClosureRef, object *state.StateObject, code []byte, gas, price *big.Int) *Closure { c := &Closure{message: msg, caller: caller, object: object, Code: code, Args: nil} // Gas should be a pointer so it can safely be reduced through the run @@ -131,7 +131,7 @@ func (c *Closure) ReturnGas(gas, price *big.Int) { c.UsedGas.Sub(c.UsedGas, gas) } -func (c *Closure) Object() *ethstate.StateObject { +func (c *Closure) Object() *state.StateObject { return c.object } diff --git a/vm/debugger.go b/vm/debugger.go index b0d0e545d..9b08634c6 100644 --- a/vm/debugger.go +++ b/vm/debugger.go @@ -1,10 +1,10 @@ package vm -import "github.com/ethereum/go-ethereum/ethstate" +import "github.com/ethereum/go-ethereum/state" type Debugger interface { - BreakHook(step int, op OpCode, mem *Memory, stack *Stack, object *ethstate.StateObject) bool - StepHook(step int, op OpCode, mem *Memory, stack *Stack, object *ethstate.StateObject) bool + BreakHook(step int, op OpCode, mem *Memory, stack *Stack, object *state.StateObject) bool + StepHook(step int, op OpCode, mem *Memory, stack *Stack, object *state.StateObject) bool BreakPoints() []int64 SetCode(byteCode []byte) } diff --git a/vm/environment.go b/vm/environment.go index deb46b77f..dea86c66c 100644 --- a/vm/environment.go +++ b/vm/environment.go @@ -4,12 +4,12 @@ import ( "errors" "math/big" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) type Environment interface { - State() *ethstate.State + State() *state.State Origin() []byte BlockNumber() *big.Int @@ -20,7 +20,7 @@ type Environment interface { BlockHash() []byte GasLimit() *big.Int Transfer(from, to Account, amount *big.Int) error - AddLog(ethstate.Log) + AddLog(state.Log) } type Object interface { diff --git a/vm/execution.go b/vm/execution.go index 8da0469de..401157808 100644 --- a/vm/execution.go +++ b/vm/execution.go @@ -4,15 +4,15 @@ import ( "fmt" "math/big" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) type Execution struct { vm VirtualMachine address, input []byte Gas, price, value *big.Int - object *ethstate.StateObject + object *state.StateObject SkipTransfer bool } @@ -41,7 +41,7 @@ func (self *Execution) exec(code, caddr []byte, caller ClosureRef) (ret []byte, } }() - msg := env.State().Manifest().AddMessage(ðstate.Message{ + msg := env.State().Manifest().AddMessage(&state.Message{ To: self.address, From: caller.Address(), Input: self.input, Origin: env.Origin(), diff --git a/vm/vm_debug.go b/vm/vm_debug.go index 1cf243e16..0942636d6 100644 --- a/vm/vm_debug.go +++ b/vm/vm_debug.go @@ -5,8 +5,8 @@ import ( "math/big" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) type DebugVm struct { @@ -49,7 +49,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { pc = big.NewInt(0) step = 0 prevStep = 0 - state = self.env.State() + statedb = self.env.State() require = func(m int) { if stack.Len() < m { panic(fmt.Sprintf("%04v (%v) stack err size = %d, required = %d", pc, op, stack.Len(), m)) @@ -115,7 +115,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { if self.logTy == LogTyDiff { switch op { case STOP, RETURN, SUICIDE: - state.GetStateObject(closure.Address()).EachStorage(func(key string, value *ethutil.Value) { + statedb.GetStateObject(closure.Address()).EachStorage(func(key string, value *ethutil.Value) { value.Decode() fmt.Printf("%x %x\n", new(big.Int).SetBytes([]byte(key)).Bytes(), value.Bytes()) }) @@ -184,7 +184,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { // 0 => non 0 mult = ethutil.Big3 } else if val.BigInt().Cmp(ethutil.Big0) != 0 && len(y.Bytes()) == 0 { - state.Refund(closure.caller.Address(), GasSStoreRefund, closure.Price) + statedb.Refund(closure.caller.Address(), GasSStoreRefund, closure.Price) mult = ethutil.Big0 } else { @@ -532,7 +532,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { case BALANCE: addr := stack.Pop().Bytes() - balance := state.GetBalance(addr) + balance := statedb.GetBalance(addr) stack.Push(balance) @@ -599,7 +599,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { if op == EXTCODESIZE { addr := stack.Pop().Bytes() - code = state.GetCode(addr) + code = statedb.GetCode(addr) } else { code = closure.Code } @@ -613,7 +613,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { if op == EXTCODECOPY { addr := stack.Pop().Bytes() - code = state.GetCode(addr) + code = statedb.GetCode(addr) } else { code = closure.Code } @@ -711,7 +711,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { for i := 0; i < n; i++ { topics[i] = stack.Pop().Bytes() } - self.env.AddLog(ethstate.Log{closure.Address(), topics, data}) + self.env.AddLog(state.Log{closure.Address(), topics, data}) case MLOAD: offset := stack.Pop() val := ethutil.BigD(mem.Get(offset.Int64(), 32)) @@ -733,13 +733,13 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" => [%v] 0x%x", off, val) case SLOAD: loc := stack.Pop() - val := ethutil.BigD(state.GetState(closure.Address(), loc.Bytes())) + val := ethutil.BigD(statedb.GetState(closure.Address(), loc.Bytes())) stack.Push(val) self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes()) case SSTORE: val, loc := stack.Popn() - state.SetState(closure.Address(), loc.Bytes(), val) + statedb.SetState(closure.Address(), loc.Bytes(), val) // Debug sessions are allowed to run without message if closure.message != nil { @@ -784,9 +784,9 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { ) // Generate a new address - n := state.GetNonce(closure.Address()) + n := statedb.GetNonce(closure.Address()) addr := crypto.CreateAddress(closure.Address(), n) - state.SetNonce(closure.Address(), n+1) + statedb.SetNonce(closure.Address(), n+1) self.Printf(" (*) %x", addr).Endl() @@ -861,10 +861,10 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { return closure.Return(ret), nil case SUICIDE: - receiver := state.GetOrNewStateObject(stack.Pop().Bytes()) + receiver := statedb.GetOrNewStateObject(stack.Pop().Bytes()) - receiver.AddAmount(state.GetBalance(closure.Address())) - state.Delete(closure.Address()) + receiver.AddAmount(statedb.GetBalance(closure.Address())) + statedb.Delete(closure.Address()) fallthrough case STOP: // Stop the closure @@ -889,11 +889,11 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { if pc.Cmp(big.NewInt(instrNo)) == 0 { self.Stepping = true - if !self.Dbg.BreakHook(prevStep, op, mem, stack, state.GetStateObject(closure.Address())) { + if !self.Dbg.BreakHook(prevStep, op, mem, stack, statedb.GetStateObject(closure.Address())) { return nil, nil } } else if self.Stepping { - if !self.Dbg.StepHook(prevStep, op, mem, stack, state.GetStateObject(closure.Address())) { + if !self.Dbg.StepHook(prevStep, op, mem, stack, statedb.GetStateObject(closure.Address())) { return nil, nil } } diff --git a/xeth/hexface.go b/xeth/hexface.go index 829f530f4..5c8e7a3c7 100644 --- a/xeth/hexface.go +++ b/xeth/hexface.go @@ -7,8 +7,8 @@ import ( "github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) type JSXEth struct { @@ -254,7 +254,7 @@ func (self *JSXEth) CompileMutan(code string) string { return ethutil.Bytes2Hex(data) } -func ToJSMessages(messages ethstate.Messages) *ethutil.List { +func ToJSMessages(messages state.Messages) *ethutil.List { var msgs []JSMessage for _, m := range messages { msgs = append(msgs, NewJSMessage(m)) diff --git a/xeth/js_types.go b/xeth/js_types.go index 058bfe0dd..9f8f12e7f 100644 --- a/xeth/js_types.go +++ b/xeth/js_types.go @@ -7,8 +7,8 @@ import ( "github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) // Block interface exposed to QML @@ -90,7 +90,7 @@ type JSTransaction struct { Confirmations int `json:"confirmations"` } -func NewJSTx(tx *chain.Transaction, state *ethstate.State) *JSTransaction { +func NewJSTx(tx *chain.Transaction, state *state.State) *JSTransaction { hash := ethutil.Bytes2Hex(tx.Hash()) receiver := ethutil.Bytes2Hex(tx.Recipient) if receiver == "0000000000000000000000000000000000000000" { @@ -212,7 +212,7 @@ type JSMessage struct { Value string `json:"value"` } -func NewJSMessage(message *ethstate.Message) JSMessage { +func NewJSMessage(message *state.Message) JSMessage { return JSMessage{ To: ethutil.Bytes2Hex(message.To), From: ethutil.Bytes2Hex(message.From), diff --git a/xeth/object.go b/xeth/object.go index fe4e84a4a..a4ac41e89 100644 --- a/xeth/object.go +++ b/xeth/object.go @@ -1,12 +1,12 @@ package xeth import ( - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/state" ) type Object struct { - *ethstate.StateObject + *state.StateObject } func (self *Object) StorageString(str string) *ethutil.Value { diff --git a/xeth/pipe.go b/xeth/pipe.go index f2759d660..25a69137d 100644 --- a/xeth/pipe.go +++ b/xeth/pipe.go @@ -10,16 +10,16 @@ import ( "github.com/ethereum/go-ethereum/chain" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethstate" "github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/logger" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" ) var pipelogger = logger.NewLogger("XETH") type VmVars struct { - State *ethstate.State + State *state.State } type XEth struct { @@ -56,7 +56,7 @@ func (self *XEth) Execute(addr []byte, data []byte, value, gas, price *ethutil.V func (self *XEth) ExecuteObject(object *Object, data []byte, value, gas, price *ethutil.Value) ([]byte, error) { var ( - initiator = ethstate.NewStateObject(self.obj.KeyManager().KeyPair().Address()) + initiator = state.NewStateObject(self.obj.KeyManager().KeyPair().Address()) block = self.blockChain.CurrentBlock ) diff --git a/xeth/vm_env.go b/xeth/vm_env.go index 952101f68..2c36444e9 100644 --- a/xeth/vm_env.go +++ b/xeth/vm_env.go @@ -4,18 +4,18 @@ import ( "math/big" "github.com/ethereum/go-ethereum/chain" - "github.com/ethereum/go-ethereum/ethstate" + "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" ) type VMEnv struct { - state *ethstate.State + state *state.State block *chain.Block value *big.Int sender []byte } -func NewEnv(state *ethstate.State, block *chain.Block, value *big.Int, sender []byte) *VMEnv { +func NewEnv(state *state.State, block *chain.Block, value *big.Int, sender []byte) *VMEnv { return &VMEnv{ state: state, block: block, @@ -24,17 +24,17 @@ func NewEnv(state *ethstate.State, block *chain.Block, value *big.Int, sender [] } } -func (self *VMEnv) Origin() []byte { return self.sender } -func (self *VMEnv) BlockNumber() *big.Int { return self.block.Number } -func (self *VMEnv) PrevHash() []byte { return self.block.PrevHash } -func (self *VMEnv) Coinbase() []byte { return self.block.Coinbase } -func (self *VMEnv) Time() int64 { return self.block.Time } -func (self *VMEnv) Difficulty() *big.Int { return self.block.Difficulty } -func (self *VMEnv) BlockHash() []byte { return self.block.Hash() } -func (self *VMEnv) Value() *big.Int { return self.value } -func (self *VMEnv) State() *ethstate.State { return self.state } -func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit } -func (self *VMEnv) AddLog(ethstate.Log) {} +func (self *VMEnv) Origin() []byte { return self.sender } +func (self *VMEnv) BlockNumber() *big.Int { return self.block.Number } +func (self *VMEnv) PrevHash() []byte { return self.block.PrevHash } +func (self *VMEnv) Coinbase() []byte { return self.block.Coinbase } +func (self *VMEnv) Time() int64 { return self.block.Time } +func (self *VMEnv) Difficulty() *big.Int { return self.block.Difficulty } +func (self *VMEnv) BlockHash() []byte { return self.block.Hash() } +func (self *VMEnv) Value() *big.Int { return self.value } +func (self *VMEnv) State() *state.State { return self.state } +func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit } +func (self *VMEnv) AddLog(state.Log) {} func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error { return vm.Transfer(from, to, amount) } diff --git a/xeth/world.go b/xeth/world.go index daeb59e1c..dda2df274 100644 --- a/xeth/world.go +++ b/xeth/world.go @@ -3,7 +3,7 @@ package xeth import ( "container/list" - "github.com/ethereum/go-ethereum/ethstate" + "github.com/ethereum/go-ethereum/state" ) type World struct { @@ -22,7 +22,7 @@ func (self *XEth) World() *World { return self.world } -func (self *World) State() *ethstate.State { +func (self *World) State() *state.State { return self.pipe.stateManager.CurrentState() } @@ -34,16 +34,16 @@ func (self *World) SafeGet(addr []byte) *Object { return &Object{self.safeGet(addr)} } -func (self *World) safeGet(addr []byte) *ethstate.StateObject { +func (self *World) safeGet(addr []byte) *state.StateObject { object := self.State().GetStateObject(addr) if object == nil { - object = ethstate.NewStateObject(addr) + object = state.NewStateObject(addr) } return object } -func (self *World) Coinbase() *ethstate.StateObject { +func (self *World) Coinbase() *state.StateObject { return nil } -- cgit