state_transition.go 5.61 KB
Newer Older
obscuren's avatar
obscuren committed
1
package core
2 3 4

import (
	"fmt"
5 6
	"math/big"

7 8
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethutil"
obscuren's avatar
obscuren committed
9
	"github.com/ethereum/go-ethereum/state"
10
	"github.com/ethereum/go-ethereum/vm"
11 12
)

obscuren's avatar
obscuren committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
 * 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
 */
29
type StateTransition struct {
30 31 32 33 34 35 36
	coinbase      []byte
	msg           Message
	gas, gasPrice *big.Int
	initialGas    *big.Int
	value         *big.Int
	data          []byte
	state         *state.StateDB
37

obscuren's avatar
obscuren committed
38
	cb, rec, sen *state.StateObject
39

40
	env vm.Environment
41 42 43 44 45 46 47 48 49 50 51 52 53 54
}

type Message interface {
	Hash() []byte

	From() []byte
	To() []byte

	GasPrice() *big.Int
	Gas() *big.Int
	Value() *big.Int

	Nonce() uint64
	Data() []byte
55 56
}

57 58 59 60 61
func AddressFromMessage(msg Message) []byte {
	// Generate a new address
	return crypto.Sha3(ethutil.NewValue([]interface{}{msg.From(), msg.Nonce()}).Encode())[12:]
}

obscuren's avatar
obscuren committed
62 63 64 65
func MessageCreatesContract(msg Message) bool {
	return len(msg.To()) == 0
}

obscuren's avatar
obscuren committed
66 67 68 69
func MessageGasValue(msg Message) *big.Int {
	return new(big.Int).Mul(msg.Gas(), msg.GasPrice())
}

70 71 72 73 74 75 76 77 78 79 80 81
func NewStateTransition(env vm.Environment, msg Message, coinbase *state.StateObject) *StateTransition {
	return &StateTransition{
		coinbase:   coinbase.Address(),
		env:        env,
		msg:        msg,
		gas:        new(big.Int),
		gasPrice:   new(big.Int).Set(msg.GasPrice()),
		initialGas: new(big.Int),
		value:      msg.Value(),
		data:       msg.Data(),
		state:      env.State(),
		cb:         coinbase,
82
	}
83 84
}

obscuren's avatar
obscuren committed
85
func (self *StateTransition) Coinbase() *state.StateObject {
obscuren's avatar
obscuren committed
86
	return self.state.GetOrNewStateObject(self.coinbase)
87
}
88
func (self *StateTransition) From() *state.StateObject {
obscuren's avatar
obscuren committed
89
	return self.state.GetOrNewStateObject(self.msg.From())
90
}
91
func (self *StateTransition) To() *state.StateObject {
obscuren's avatar
obscuren committed
92
	if self.msg != nil && MessageCreatesContract(self.msg) {
93 94
		return nil
	}
obscuren's avatar
obscuren committed
95
	return self.state.GetOrNewStateObject(self.msg.To())
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
}

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

114
	sender := self.From()
obscuren's avatar
obscuren committed
115
	if sender.Balance().Cmp(MessageGasValue(self.msg)) < 0 {
116
		return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address()[:4], MessageGasValue(self.msg), sender.Balance())
117 118 119
	}

	coinbase := self.Coinbase()
120
	err = coinbase.BuyGas(self.msg.Gas(), self.msg.GasPrice())
121 122 123 124
	if err != nil {
		return err
	}

125
	self.AddGas(self.msg.Gas())
obscuren's avatar
obscuren committed
126 127
	self.initialGas.Set(self.msg.Gas())
	sender.SubAmount(MessageGasValue(self.msg))
128 129 130 131

	return nil
}

132 133
func (self *StateTransition) preCheck() (err error) {
	var (
134 135
		msg    = self.msg
		sender = self.From()
136 137 138
	)

	// Make sure this transaction's nonce is correct
139 140
	if sender.Nonce != msg.Nonce() {
		return NonceError(msg.Nonce(), sender.Nonce)
141 142 143 144 145 146 147 148 149 150
	}

	// Pre-pay gas / Buy gas of the coinbase account
	if err = self.BuyGas(); err != nil {
		return err
	}

	return nil
}

obscuren's avatar
obscuren committed
151
func (self *StateTransition) TransitionState() (ret []byte, err error) {
152
	statelogger.Debugf("(~) %x\n", self.msg.Hash())
153

154 155 156 157 158
	// XXX Transactions after this point are considered valid.
	if err = self.preCheck(); err != nil {
		return
	}

159
	var (
160 161
		msg    = self.msg
		sender = self.From()
162 163
	)

obscuren's avatar
obscuren committed
164 165
	defer self.RefundGas()

obscuren's avatar
obscuren committed
166 167 168
	// Increment the nonce for the next transaction
	sender.Nonce += 1

169
	// Transaction gas
obscuren's avatar
obscuren committed
170
	if err = self.UseGas(vm.GasTx); err != nil {
171
		return
172 173
	}

174
	// Pay data gas
175 176 177 178 179 180 181 182 183
	var dgas int64
	for _, byt := range self.data {
		if byt != 0 {
			dgas += vm.GasData.Int64()
		} else {
			dgas += 1 // This is 1/5. If GasData changes this fails
		}
	}
	if err = self.UseGas(big.NewInt(dgas)); err != nil {
184
		return
185 186
	}

187
	vmenv := self.env
obscuren's avatar
obscuren committed
188
	var ref vm.ContextRef
obscuren's avatar
obscuren committed
189
	if MessageCreatesContract(msg) {
190 191
		contract := MakeContract(msg, self.state)
		ret, err, ref = vmenv.Create(sender, contract.Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
192 193 194
		if err == nil {
			dataGas := big.NewInt(int64(len(ret)))
			dataGas.Mul(dataGas, vm.GasCreateByte)
obscuren's avatar
obscuren committed
195
			if err := self.UseGas(dataGas); err == nil {
196 197 198
				ref.SetCode(ret)
			}
		}
obscuren's avatar
obscuren committed
199
	} else {
200
		ret, err = vmenv.Call(self.From(), self.To().Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
obscuren's avatar
obscuren committed
201
	}
202

203
	if err != nil {
204
		self.UseGas(self.gas)
205 206 207 208
	}

	return
}
209 210

// Converts an transaction in to a state object
211 212
func MakeContract(msg Message, state *state.StateDB) *state.StateObject {
	addr := AddressFromMessage(msg)
213

214
	contract := state.GetOrNewStateObject(addr)
215
	contract.InitCode = msg.Data()
216

217
	return contract
218
}
obscuren's avatar
obscuren committed
219 220

func (self *StateTransition) RefundGas() {
221 222 223 224 225
	coinbase, sender := self.Coinbase(), self.From()
	// Return remaining gas
	remaining := new(big.Int).Mul(self.gas, self.msg.GasPrice())
	sender.AddAmount(remaining)

obscuren's avatar
obscuren committed
226
	uhalf := new(big.Int).Div(self.GasUsed(), ethutil.Big2)
obscuren's avatar
obscuren committed
227 228
	for addr, ref := range self.state.Refunds() {
		refund := ethutil.BigMin(uhalf, ref)
229
		self.gas.Add(self.gas, refund)
obscuren's avatar
obscuren committed
230
		self.state.AddBalance([]byte(addr), refund.Mul(refund, self.msg.GasPrice()))
obscuren's avatar
obscuren committed
231 232
	}

233
	coinbase.RefundGas(self.gas, self.msg.GasPrice())
obscuren's avatar
obscuren committed
234 235 236 237 238
}

func (self *StateTransition) GasUsed() *big.Int {
	return new(big.Int).Sub(self.initialGas, self.gas)
}