forked from mirror/go-ethereum
commit
5a0e751736
@ -0,0 +1,236 @@ |
|||||||
|
package ethchain |
||||||
|
|
||||||
|
import ( |
||||||
|
"bytes" |
||||||
|
"fmt" |
||||||
|
"github.com/ethereum/eth-go/ethutil" |
||||||
|
"math/big" |
||||||
|
) |
||||||
|
|
||||||
|
func (sm *StateManager) MakeStateObject(state *State, tx *Transaction) *StateObject { |
||||||
|
contract := MakeContract(tx, state) |
||||||
|
if contract != nil { |
||||||
|
state.states[string(tx.CreationAddress())] = contract.state |
||||||
|
|
||||||
|
return contract |
||||||
|
} |
||||||
|
|
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
func (sm *StateManager) EvalScript(state *State, script []byte, object *StateObject, tx *Transaction, block *Block) (ret []byte, gas *big.Int, err error) { |
||||||
|
account := state.GetAccount(tx.Sender()) |
||||||
|
|
||||||
|
err = account.ConvertGas(tx.Gas, tx.GasPrice) |
||||||
|
if err != nil { |
||||||
|
ethutil.Config.Log.Debugln(err) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
closure := NewClosure(account, object, script, state, tx.Gas, tx.GasPrice) |
||||||
|
vm := NewVm(state, sm, RuntimeVars{ |
||||||
|
Origin: account.Address(), |
||||||
|
BlockNumber: block.BlockInfo().Number, |
||||||
|
PrevHash: block.PrevHash, |
||||||
|
Coinbase: block.Coinbase, |
||||||
|
Time: block.Time, |
||||||
|
Diff: block.Difficulty, |
||||||
|
Value: tx.Value, |
||||||
|
//Price: tx.GasPrice,
|
||||||
|
}) |
||||||
|
ret, gas, err = closure.Call(vm, tx.Data, nil) |
||||||
|
|
||||||
|
// Update the account (refunds)
|
||||||
|
state.UpdateStateObject(account) |
||||||
|
state.UpdateStateObject(object) |
||||||
|
|
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateManager) ProcessTransaction(tx *Transaction, coinbase *StateObject, state *State, toContract bool) (gas *big.Int, err error) { |
||||||
|
fmt.Printf("state root before update %x\n", state.Root()) |
||||||
|
defer func() { |
||||||
|
if r := recover(); r != nil { |
||||||
|
ethutil.Config.Log.Infoln(r) |
||||||
|
err = fmt.Errorf("%v", r) |
||||||
|
} |
||||||
|
}() |
||||||
|
|
||||||
|
gas = new(big.Int) |
||||||
|
addGas := func(g *big.Int) { gas.Add(gas, g) } |
||||||
|
addGas(GasTx) |
||||||
|
|
||||||
|
// Get the sender
|
||||||
|
sender := state.GetAccount(tx.Sender()) |
||||||
|
|
||||||
|
if sender.Nonce != tx.Nonce { |
||||||
|
err = NonceError(tx.Nonce, sender.Nonce) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
sender.Nonce += 1 |
||||||
|
defer func() { |
||||||
|
//state.UpdateStateObject(sender)
|
||||||
|
// Notify all subscribers
|
||||||
|
self.Ethereum.Reactor().Post("newTx:post", tx) |
||||||
|
}() |
||||||
|
|
||||||
|
txTotalBytes := big.NewInt(int64(len(tx.Data))) |
||||||
|
//fmt.Println("txTotalBytes", txTotalBytes)
|
||||||
|
//txTotalBytes.Div(txTotalBytes, ethutil.Big32)
|
||||||
|
addGas(new(big.Int).Mul(txTotalBytes, GasData)) |
||||||
|
|
||||||
|
rGas := new(big.Int).Set(gas) |
||||||
|
rGas.Mul(gas, tx.GasPrice) |
||||||
|
|
||||||
|
// Make sure there's enough in the sender's account. Having insufficient
|
||||||
|
// funds won't invalidate this transaction but simple ignores it.
|
||||||
|
totAmount := new(big.Int).Add(tx.Value, rGas) |
||||||
|
if sender.Amount.Cmp(totAmount) < 0 { |
||||||
|
state.UpdateStateObject(sender) |
||||||
|
err = fmt.Errorf("[TXPL] Insufficient amount in sender's (%x) account", tx.Sender()) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
coinbase.BuyGas(gas, tx.GasPrice) |
||||||
|
state.UpdateStateObject(coinbase) |
||||||
|
fmt.Printf("1. root %x\n", state.Root()) |
||||||
|
|
||||||
|
// Get the receiver
|
||||||
|
receiver := state.GetAccount(tx.Recipient) |
||||||
|
|
||||||
|
// Send Tx to self
|
||||||
|
if bytes.Compare(tx.Recipient, tx.Sender()) == 0 { |
||||||
|
// Subtract the fee
|
||||||
|
sender.SubAmount(rGas) |
||||||
|
} else { |
||||||
|
// Subtract the amount from the senders account
|
||||||
|
sender.SubAmount(totAmount) |
||||||
|
state.UpdateStateObject(sender) |
||||||
|
fmt.Printf("3. root %x\n", state.Root()) |
||||||
|
|
||||||
|
// Add the amount to receivers account which should conclude this transaction
|
||||||
|
receiver.AddAmount(tx.Value) |
||||||
|
state.UpdateStateObject(receiver) |
||||||
|
fmt.Printf("2. root %x\n", state.Root()) |
||||||
|
} |
||||||
|
|
||||||
|
ethutil.Config.Log.Infof("[TXPL] Processed Tx %x\n", tx.Hash()) |
||||||
|
|
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
func (sm *StateManager) ApplyTransaction(coinbase []byte, state *State, block *Block, tx *Transaction) (totalGasUsed *big.Int, err error) { |
||||||
|
/* |
||||||
|
Applies transactions to the given state and creates new |
||||||
|
state objects where needed. |
||||||
|
|
||||||
|
If said objects needs to be created |
||||||
|
run the initialization script provided by the transaction and |
||||||
|
assume there's a return value. The return value will be set to |
||||||
|
the script section of the state object. |
||||||
|
*/ |
||||||
|
var ( |
||||||
|
addTotalGas = func(gas *big.Int) { totalGasUsed.Add(totalGasUsed, gas) } |
||||||
|
gas = new(big.Int) |
||||||
|
script []byte |
||||||
|
) |
||||||
|
totalGasUsed = big.NewInt(0) |
||||||
|
snapshot := state.Snapshot() |
||||||
|
|
||||||
|
ca := state.GetAccount(coinbase) |
||||||
|
// Apply the transaction to the current state
|
||||||
|
gas, err = sm.ProcessTransaction(tx, ca, state, false) |
||||||
|
addTotalGas(gas) |
||||||
|
fmt.Println("gas used by tx", gas) |
||||||
|
|
||||||
|
if tx.CreatesContract() { |
||||||
|
if err == nil { |
||||||
|
// Create a new state object and the transaction
|
||||||
|
// as it's data provider.
|
||||||
|
contract := sm.MakeStateObject(state, tx) |
||||||
|
if contract != nil { |
||||||
|
fmt.Println(Disassemble(contract.Init())) |
||||||
|
// Evaluate the initialization script
|
||||||
|
// and use the return value as the
|
||||||
|
// script section for the state object.
|
||||||
|
script, gas, err = sm.EvalScript(state, contract.Init(), contract, tx, block) |
||||||
|
fmt.Println("gas used by eval", gas) |
||||||
|
addTotalGas(gas) |
||||||
|
fmt.Println("total =", totalGasUsed) |
||||||
|
|
||||||
|
fmt.Println("script len =", len(script)) |
||||||
|
|
||||||
|
if err != nil { |
||||||
|
err = fmt.Errorf("[STATE] Error during init script run %v", err) |
||||||
|
return |
||||||
|
} |
||||||
|
contract.script = script |
||||||
|
state.UpdateStateObject(contract) |
||||||
|
} else { |
||||||
|
err = fmt.Errorf("[STATE] Unable to create contract") |
||||||
|
} |
||||||
|
} else { |
||||||
|
err = fmt.Errorf("[STATE] contract creation tx: %v for sender %x", err, tx.Sender()) |
||||||
|
} |
||||||
|
} else { |
||||||
|
// Find the state object at the "recipient" address. If
|
||||||
|
// there's an object attempt to run the script.
|
||||||
|
stateObject := state.GetStateObject(tx.Recipient) |
||||||
|
if err == nil && stateObject != nil && len(stateObject.Script()) > 0 { |
||||||
|
_, gas, err = sm.EvalScript(state, stateObject.Script(), stateObject, tx, block) |
||||||
|
addTotalGas(gas) |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
parent := sm.bc.GetBlock(block.PrevHash) |
||||||
|
total := new(big.Int).Add(block.GasUsed, totalGasUsed) |
||||||
|
limit := block.CalcGasLimit(parent) |
||||||
|
if total.Cmp(limit) > 0 { |
||||||
|
state.Revert(snapshot) |
||||||
|
err = GasLimitError(total, limit) |
||||||
|
} |
||||||
|
|
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// Apply transactions uses the transaction passed to it and applies them onto
|
||||||
|
// the current processing state.
|
||||||
|
func (sm *StateManager) ApplyTransactions(coinbase []byte, state *State, block *Block, txs []*Transaction) ([]*Receipt, []*Transaction) { |
||||||
|
// Process each transaction/contract
|
||||||
|
var receipts []*Receipt |
||||||
|
var validTxs []*Transaction |
||||||
|
var ignoredTxs []*Transaction // Transactions which go over the gasLimit
|
||||||
|
|
||||||
|
totalUsedGas := big.NewInt(0) |
||||||
|
|
||||||
|
for _, tx := range txs { |
||||||
|
usedGas, err := sm.ApplyTransaction(coinbase, state, block, tx) |
||||||
|
if err != nil { |
||||||
|
if IsNonceErr(err) { |
||||||
|
continue |
||||||
|
} |
||||||
|
if IsGasLimitErr(err) { |
||||||
|
ignoredTxs = append(ignoredTxs, tx) |
||||||
|
// We need to figure out if we want to do something with thse txes
|
||||||
|
ethutil.Config.Log.Debugln("Gastlimit:", err) |
||||||
|
continue |
||||||
|
} |
||||||
|
|
||||||
|
ethutil.Config.Log.Infoln(err) |
||||||
|
} |
||||||
|
|
||||||
|
accumelative := new(big.Int).Set(totalUsedGas.Add(totalUsedGas, usedGas)) |
||||||
|
receipt := &Receipt{tx, ethutil.CopyBytes(state.Root().([]byte)), accumelative} |
||||||
|
|
||||||
|
receipts = append(receipts, receipt) |
||||||
|
validTxs = append(validTxs, tx) |
||||||
|
} |
||||||
|
|
||||||
|
fmt.Println("################# MADE\n", receipts, "\n############################") |
||||||
|
|
||||||
|
// Update the total gas used for the block (to be mined)
|
||||||
|
block.GasUsed = totalUsedGas |
||||||
|
|
||||||
|
return receipts, validTxs |
||||||
|
} |
@ -0,0 +1,260 @@ |
|||||||
|
package ethchain |
||||||
|
|
||||||
|
import ( |
||||||
|
"fmt" |
||||||
|
"github.com/ethereum/eth-go/ethutil" |
||||||
|
"math/big" |
||||||
|
) |
||||||
|
|
||||||
|
/* |
||||||
|
* The State transitioning model |
||||||
|
* |
||||||
|
* A state transition is a change made when a transaction is applied to the current world state |
||||||
|
* The state transitioning model does all all the necessary work to work out a valid new state root. |
||||||
|
* 1) Nonce handling |
||||||
|
* 2) Pre pay / buy gas of the coinbase (miner) |
||||||
|
* 3) Create a new state object if the recipient is \0*32 |
||||||
|
* 4) Value transfer |
||||||
|
* == If contract creation == |
||||||
|
* 4a) Attempt to run transaction data |
||||||
|
* 4b) If valid, use result as code for the new state object |
||||||
|
* == end == |
||||||
|
* 5) Run Script section |
||||||
|
* 6) Derive new state root |
||||||
|
*/ |
||||||
|
type StateTransition struct { |
||||||
|
coinbase []byte |
||||||
|
tx *Transaction |
||||||
|
gas *big.Int |
||||||
|
state *State |
||||||
|
block *Block |
||||||
|
|
||||||
|
cb, rec, sen *StateObject |
||||||
|
} |
||||||
|
|
||||||
|
func NewStateTransition(coinbase *StateObject, tx *Transaction, state *State, block *Block) *StateTransition { |
||||||
|
return &StateTransition{coinbase.Address(), tx, new(big.Int), state, block, coinbase, nil, nil} |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) Coinbase() *StateObject { |
||||||
|
if self.cb != nil { |
||||||
|
return self.cb |
||||||
|
} |
||||||
|
|
||||||
|
self.cb = self.state.GetAccount(self.coinbase) |
||||||
|
return self.cb |
||||||
|
} |
||||||
|
func (self *StateTransition) Sender() *StateObject { |
||||||
|
if self.sen != nil { |
||||||
|
return self.sen |
||||||
|
} |
||||||
|
|
||||||
|
self.sen = self.state.GetAccount(self.tx.Sender()) |
||||||
|
return self.sen |
||||||
|
} |
||||||
|
func (self *StateTransition) Receiver() *StateObject { |
||||||
|
if self.tx.CreatesContract() { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
if self.rec != nil { |
||||||
|
return self.rec |
||||||
|
} |
||||||
|
|
||||||
|
self.rec = self.state.GetAccount(self.tx.Recipient) |
||||||
|
return self.rec |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) MakeStateObject(state *State, tx *Transaction) *StateObject { |
||||||
|
contract := MakeContract(tx, state) |
||||||
|
if contract != nil { |
||||||
|
state.states[string(tx.CreationAddress())] = contract.state |
||||||
|
|
||||||
|
return contract |
||||||
|
} |
||||||
|
|
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) UseGas(amount *big.Int) error { |
||||||
|
if self.gas.Cmp(amount) < 0 { |
||||||
|
return OutOfGasError() |
||||||
|
} |
||||||
|
self.gas.Sub(self.gas, amount) |
||||||
|
|
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) AddGas(amount *big.Int) { |
||||||
|
self.gas.Add(self.gas, amount) |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) BuyGas() error { |
||||||
|
var err error |
||||||
|
|
||||||
|
sender := self.Sender() |
||||||
|
if sender.Amount.Cmp(self.tx.GasValue()) < 0 { |
||||||
|
return fmt.Errorf("Insufficient funds to pre-pay gas. Req %v, has %v", self.tx.GasValue(), self.tx.Value) |
||||||
|
} |
||||||
|
|
||||||
|
coinbase := self.Coinbase() |
||||||
|
err = coinbase.BuyGas(self.tx.Gas, self.tx.GasPrice) |
||||||
|
if err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
//self.state.UpdateStateObject(coinbase)
|
||||||
|
|
||||||
|
self.AddGas(self.tx.Gas) |
||||||
|
sender.SubAmount(self.tx.GasValue()) |
||||||
|
|
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) RefundGas() { |
||||||
|
coinbase, sender := self.Coinbase(), self.Sender() |
||||||
|
coinbase.RefundGas(self.gas, self.tx.GasPrice) |
||||||
|
|
||||||
|
// Return remaining gas
|
||||||
|
remaining := new(big.Int).Mul(self.gas, self.tx.GasPrice) |
||||||
|
sender.AddAmount(remaining) |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) TransitionState() (err error) { |
||||||
|
//snapshot := st.state.Snapshot()
|
||||||
|
|
||||||
|
/* |
||||||
|
defer func() { |
||||||
|
if r := recover(); r != nil { |
||||||
|
ethutil.Config.Log.Infoln(r) |
||||||
|
err = fmt.Errorf("state transition err %v", r) |
||||||
|
} |
||||||
|
}() |
||||||
|
*/ |
||||||
|
|
||||||
|
var ( |
||||||
|
tx = self.tx |
||||||
|
sender = self.Sender() |
||||||
|
receiver *StateObject |
||||||
|
) |
||||||
|
|
||||||
|
// Make sure this transaction's nonce is correct
|
||||||
|
if sender.Nonce != tx.Nonce { |
||||||
|
return NonceError(tx.Nonce, sender.Nonce) |
||||||
|
} |
||||||
|
|
||||||
|
// Pre-pay gas / Buy gas of the coinbase account
|
||||||
|
if err = self.BuyGas(); err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
|
// XXX Transactions after this point are considered valid.
|
||||||
|
|
||||||
|
defer func() { |
||||||
|
self.RefundGas() |
||||||
|
|
||||||
|
if sender != nil { |
||||||
|
self.state.UpdateStateObject(sender) |
||||||
|
} |
||||||
|
|
||||||
|
if receiver != nil { |
||||||
|
self.state.UpdateStateObject(receiver) |
||||||
|
} |
||||||
|
|
||||||
|
self.state.UpdateStateObject(self.Coinbase()) |
||||||
|
}() |
||||||
|
|
||||||
|
// Increment the nonce for the next transaction
|
||||||
|
sender.Nonce += 1 |
||||||
|
|
||||||
|
// Get the receiver (TODO fix this, if coinbase is the receiver we need to save/retrieve)
|
||||||
|
receiver = self.Receiver() |
||||||
|
|
||||||
|
// Transaction gas
|
||||||
|
if err = self.UseGas(GasTx); err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
|
// Pay data gas
|
||||||
|
dataPrice := big.NewInt(int64(len(tx.Data))) |
||||||
|
dataPrice.Mul(dataPrice, GasData) |
||||||
|
if err = self.UseGas(dataPrice); err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
|
// If the receiver is nil it's a contract (\0*32).
|
||||||
|
if receiver == nil { |
||||||
|
// Create a new state object for the contract
|
||||||
|
receiver = self.MakeStateObject(self.state, tx) |
||||||
|
if receiver == nil { |
||||||
|
return fmt.Errorf("ERR. Unable to create contract with transaction %v", tx) |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
// Transfer value from sender to receiver
|
||||||
|
if err = self.transferValue(sender, receiver); err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
|
// Process the init code and create 'valid' contract
|
||||||
|
if tx.CreatesContract() { |
||||||
|
// Evaluate the initialization script
|
||||||
|
// and use the return value as the
|
||||||
|
// script section for the state object.
|
||||||
|
//script, gas, err = sm.Eval(state, contract.Init(), contract, tx, block)
|
||||||
|
code, err := self.Eval(receiver.Init(), receiver) |
||||||
|
if err != nil { |
||||||
|
return fmt.Errorf("Error during init script run %v", err) |
||||||
|
} |
||||||
|
|
||||||
|
receiver.script = code |
||||||
|
} else { |
||||||
|
if len(receiver.Script()) > 0 { |
||||||
|
_, err := self.Eval(receiver.Script(), receiver) |
||||||
|
if err != nil { |
||||||
|
return fmt.Errorf("Error during code execution %v", err) |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) transferValue(sender, receiver *StateObject) error { |
||||||
|
if sender.Amount.Cmp(self.tx.Value) < 0 { |
||||||
|
return fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.tx.Value, sender.Amount) |
||||||
|
} |
||||||
|
|
||||||
|
if self.tx.Value.Cmp(ethutil.Big0) > 0 { |
||||||
|
// Subtract the amount from the senders account
|
||||||
|
sender.SubAmount(self.tx.Value) |
||||||
|
// Add the amount to receivers account which should conclude this transaction
|
||||||
|
receiver.AddAmount(self.tx.Value) |
||||||
|
|
||||||
|
ethutil.Config.Log.Debugf("%x => %x (%v) %x\n", sender.Address()[:4], receiver.Address()[:4], self.tx.Value, self.tx.Hash()) |
||||||
|
} |
||||||
|
|
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
func (self *StateTransition) Eval(script []byte, context *StateObject) (ret []byte, err error) { |
||||||
|
var ( |
||||||
|
tx = self.tx |
||||||
|
block = self.block |
||||||
|
initiator = self.Sender() |
||||||
|
state = self.state |
||||||
|
) |
||||||
|
|
||||||
|
closure := NewClosure(initiator, context, script, state, self.gas, tx.GasPrice) |
||||||
|
vm := NewVm(state, nil, RuntimeVars{ |
||||||
|
Origin: initiator.Address(), |
||||||
|
BlockNumber: block.BlockInfo().Number, |
||||||
|
PrevHash: block.PrevHash, |
||||||
|
Coinbase: block.Coinbase, |
||||||
|
Time: block.Time, |
||||||
|
Diff: block.Difficulty, |
||||||
|
Value: tx.Value, |
||||||
|
}) |
||||||
|
ret, _, err = closure.Call(vm, tx.Data, nil) |
||||||
|
|
||||||
|
return |
||||||
|
} |
Loading…
Reference in new issue