state_transition.go 6.1 KB
Newer Older
O
obscuren 已提交
1
package core
2 3 4

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

O
obscuren 已提交
7
	"github.com/ethereum/go-ethereum/common"
O
obscuren 已提交
8 9
	"github.com/ethereum/go-ethereum/core/state"
	"github.com/ethereum/go-ethereum/core/vm"
O
obscuren 已提交
10 11
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
12
	"github.com/ethereum/go-ethereum/params"
13 14
)

O
obscuren 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/*
 * 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
 */
31
type StateTransition struct {
O
obscuren 已提交
32
	coinbase      common.Address
33 34 35 36 37 38
	msg           Message
	gas, gasPrice *big.Int
	initialGas    *big.Int
	value         *big.Int
	data          []byte
	state         *state.StateDB
39

O
obscuren 已提交
40
	cb, rec, sen *state.StateObject
41

42
	env vm.Environment
43 44
}

45
// Message represents a message sent to a contract.
46
type Message interface {
47 48
	From() (common.Address, error)
	To() *common.Address
49 50 51 52 53 54 55

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

	Nonce() uint64
	Data() []byte
56
}
O
obscuren 已提交
57

O
obscuren 已提交
58
func MessageCreatesContract(msg Message) bool {
59
	return msg.To() == nil
O
obscuren 已提交
60 61
}

F
Felix Lange 已提交
62 63 64
// IntrinsicGas computes the 'intrisic gas' for a message
// with the given data.
func IntrinsicGas(data []byte) *big.Int {
O
obscuren 已提交
65
	igas := new(big.Int).Set(params.TxGas)
F
Felix Lange 已提交
66 67 68 69 70 71
	if len(data) > 0 {
		var nz int64
		for _, byt := range data {
			if byt != 0 {
				nz++
			}
O
obscuren 已提交
72
		}
F
Felix Lange 已提交
73 74 75 76 77 78
		m := big.NewInt(nz)
		m.Mul(m, params.TxDataNonZeroGas)
		igas.Add(igas, m)
		m.SetInt64(int64(len(data)) - nz)
		m.Mul(m, params.TxDataZeroGas)
		igas.Add(igas, m)
O
obscuren 已提交
79 80 81 82
	}
	return igas
}

83 84 85 86
func ApplyMessage(env vm.Environment, msg Message, coinbase *state.StateObject) ([]byte, *big.Int, error) {
	return NewStateTransition(env, msg, coinbase).transitionState()
}

87 88 89 90 91 92
func NewStateTransition(env vm.Environment, msg Message, coinbase *state.StateObject) *StateTransition {
	return &StateTransition{
		coinbase:   coinbase.Address(),
		env:        env,
		msg:        msg,
		gas:        new(big.Int),
93
		gasPrice:   msg.GasPrice(),
94 95 96 97 98
		initialGas: new(big.Int),
		value:      msg.Value(),
		data:       msg.Data(),
		state:      env.State(),
		cb:         coinbase,
99
	}
100 101
}

O
obscuren 已提交
102
func (self *StateTransition) Coinbase() *state.StateObject {
O
obscuren 已提交
103
	return self.state.GetOrNewStateObject(self.coinbase)
104
}
105 106 107 108 109 110
func (self *StateTransition) From() (*state.StateObject, error) {
	f, err := self.msg.From()
	if err != nil {
		return nil, err
	}
	return self.state.GetOrNewStateObject(f), nil
111
}
112
func (self *StateTransition) To() *state.StateObject {
113
	if self.msg == nil {
114 115
		return nil
	}
116 117 118 119 120
	to := self.msg.To()
	if to == nil {
		return nil // contract creation
	}
	return self.state.GetOrNewStateObject(*to)
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
}

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 {
137 138
	mgas := self.msg.Gas()
	mgval := new(big.Int).Mul(mgas, self.gasPrice)
139

140 141 142 143
	sender, err := self.From()
	if err != nil {
		return err
	}
144 145
	if sender.Balance().Cmp(mgval) < 0 {
		return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], mgval, sender.Balance())
146
	}
147
	if err = self.Coinbase().SubGas(mgas, self.gasPrice); err != nil {
148 149
		return err
	}
150 151 152
	self.AddGas(mgas)
	self.initialGas.Set(mgas)
	sender.SubBalance(mgval)
153 154 155
	return nil
}

O
obscuren 已提交
156
func (self *StateTransition) preCheck() (err error) {
157 158 159 160 161
	msg := self.msg
	sender, err := self.From()
	if err != nil {
		return err
	}
O
obscuren 已提交
162 163

	// Make sure this transaction's nonce is correct
164 165
	if sender.Nonce() != msg.Nonce() {
		return NonceError(msg.Nonce(), sender.Nonce())
O
obscuren 已提交
166 167 168 169
	}

	// Pre-pay gas / Buy gas of the coinbase account
	if err = self.BuyGas(); err != nil {
O
obscuren 已提交
170 171 172
		if state.IsGasLimitErr(err) {
			return err
		}
O
obscuren 已提交
173
		return InvalidTxError(err)
O
obscuren 已提交
174 175 176 177 178
	}

	return nil
}

179
func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, err error) {
O
obscuren 已提交
180 181 182 183
	if err = self.preCheck(); err != nil {
		return
	}

184 185
	msg := self.msg
	sender, _ := self.From() // err checked in preCheck
186

O
obscuren 已提交
187
	// Pay intrinsic gas
188
	if err = self.UseGas(IntrinsicGas(self.data)); err != nil {
189
		return nil, nil, InvalidTxError(err)
190 191
	}

192
	vmenv := self.env
O
obscuren 已提交
193
	var ref vm.ContextRef
O
obscuren 已提交
194
	if MessageCreatesContract(msg) {
195
		ret, err, ref = vmenv.Create(sender, self.data, self.gas, self.gasPrice, self.value)
196 197
		if err == nil {
			dataGas := big.NewInt(int64(len(ret)))
198
			dataGas.Mul(dataGas, params.CreateDataGas)
O
obscuren 已提交
199
			if err := self.UseGas(dataGas); err == nil {
200
				ref.SetCode(ret)
201
			} else {
202
				ret = nil // does not affect consensus but useful for StateTests validations
O
obscuren 已提交
203
				glog.V(logger.Core).Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
204 205
			}
		}
O
obscuren 已提交
206
	} else {
O
obscuren 已提交
207
		// Increment the nonce for the next transaction
O
obscuren 已提交
208
		self.state.SetNonce(sender.Address(), sender.Nonce()+1)
209
		ret, err = vmenv.Call(sender, self.To().Address(), self.data, self.gas, self.gasPrice, self.value)
O
obscuren 已提交
210
	}
211

O
obscuren 已提交
212
	if err != nil && IsValueTransferErr(err) {
213
		return nil, nil, InvalidTxError(err)
214 215
	}

216
	if vm.Debug {
217
		vm.StdErrFormat(vmenv.StructLogs())
218 219
	}

220 221
	self.refundGas()
	self.state.AddBalance(self.coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice))
O
obscuren 已提交
222

223
	return ret, self.gasUsed(), err
O
obscuren 已提交
224
}
O
obscuren 已提交
225

226
func (self *StateTransition) refundGas() {
227 228
	coinbase := self.Coinbase()
	sender, _ := self.From() // err already checked
229
	// Return remaining gas
230
	remaining := new(big.Int).Mul(self.gas, self.gasPrice)
O
obscuren 已提交
231
	sender.AddBalance(remaining)
232

233
	uhalf := remaining.Div(self.gasUsed(), common.Big2)
O
obscuren 已提交
234 235
	refund := common.BigMin(uhalf, self.state.Refunds())
	self.gas.Add(self.gas, refund)
236
	self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
O
obscuren 已提交
237

238
	coinbase.AddGas(self.gas, self.gasPrice)
O
obscuren 已提交
239 240
}

241
func (self *StateTransition) gasUsed() *big.Int {
O
obscuren 已提交
242 243
	return new(big.Int).Sub(self.initialGas, self.gas)
}