state_transition.go 6.6 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
	"github.com/ethereum/go-ethereum/crypto"
O
obscuren 已提交
11 12
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
13
	"github.com/ethereum/go-ethereum/params"
14 15
)

O
obscuren 已提交
16 17
const tryJit = false

O
obscuren 已提交
18
var ()
O
obscuren 已提交
19

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

O
obscuren 已提交
45
	cb, rec, sen *state.StateObject
46

47
	env vm.Environment
48 49
}

50
// Message represents a message sent to a contract.
51
type Message interface {
52 53
	From() (common.Address, error)
	To() *common.Address
54 55 56 57 58 59 60

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

	Nonce() uint64
	Data() []byte
61
}
O
obscuren 已提交
62 63 64 65 66

func AddressFromMessage(msg Message) common.Address {
	from, _ := msg.From()
	return crypto.CreateAddress(from, msg.Nonce())
}
67

O
obscuren 已提交
68
func MessageCreatesContract(msg Message) bool {
69
	return msg.To() == nil
O
obscuren 已提交
70 71
}

O
obscuren 已提交
72 73 74 75
func MessageGasValue(msg Message) *big.Int {
	return new(big.Int).Mul(msg.Gas(), msg.GasPrice())
}

O
obscuren 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88
func IntrinsicGas(msg Message) *big.Int {
	igas := new(big.Int).Set(params.TxGas)
	for _, byt := range msg.Data() {
		if byt != 0 {
			igas.Add(igas, params.TxDataNonZeroGas)
		} else {
			igas.Add(igas, params.TxDataZeroGas)
		}
	}

	return igas
}

89 90 91 92
func ApplyMessage(env vm.Environment, msg Message, coinbase *state.StateObject) ([]byte, *big.Int, error) {
	return NewStateTransition(env, msg, coinbase).transitionState()
}

93 94 95 96 97 98 99 100 101 102 103 104
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,
105
	}
106 107
}

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

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

145 146 147 148
	sender, err := self.From()
	if err != nil {
		return err
	}
O
obscuren 已提交
149
	if sender.Balance().Cmp(MessageGasValue(self.msg)) < 0 {
O
obscuren 已提交
150
		return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], MessageGasValue(self.msg), sender.Balance())
151 152 153
	}

	coinbase := self.Coinbase()
154
	err = coinbase.BuyGas(self.msg.Gas(), self.msg.GasPrice())
155 156 157 158
	if err != nil {
		return err
	}

159
	self.AddGas(self.msg.Gas())
O
obscuren 已提交
160
	self.initialGas.Set(self.msg.Gas())
O
obscuren 已提交
161
	sender.SubBalance(MessageGasValue(self.msg))
162 163 164 165

	return nil
}

O
obscuren 已提交
166
func (self *StateTransition) preCheck() (err error) {
167 168 169 170 171
	msg := self.msg
	sender, err := self.From()
	if err != nil {
		return err
	}
O
obscuren 已提交
172 173

	// Make sure this transaction's nonce is correct
174 175
	if sender.Nonce() != msg.Nonce() {
		return NonceError(msg.Nonce(), sender.Nonce())
O
obscuren 已提交
176 177 178 179
	}

	// Pre-pay gas / Buy gas of the coinbase account
	if err = self.BuyGas(); err != nil {
O
obscuren 已提交
180 181 182
		if state.IsGasLimitErr(err) {
			return err
		}
O
obscuren 已提交
183
		return InvalidTxError(err)
O
obscuren 已提交
184 185 186 187 188
	}

	return nil
}

189
func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, err error) {
O
obscuren 已提交
190 191 192 193
	if err = self.preCheck(); err != nil {
		return
	}

194 195
	msg := self.msg
	sender, _ := self.From() // err checked in preCheck
196

O
obscuren 已提交
197 198
	// Pay intrinsic gas
	if err = self.UseGas(IntrinsicGas(self.msg)); err != nil {
199
		return nil, nil, InvalidTxError(err)
200 201
	}

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

O
obscuren 已提交
222
	if err != nil && IsValueTransferErr(err) {
223
		return nil, nil, InvalidTxError(err)
224 225
	}

226
	if vm.Debug {
227
		vm.StdErrFormat(vmenv.StructLogs())
228 229
	}

230 231
	self.refundGas()
	self.state.AddBalance(self.coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice))
O
obscuren 已提交
232

233
	return ret, self.gasUsed(), err
O
obscuren 已提交
234
}
O
obscuren 已提交
235

236
func (self *StateTransition) refundGas() {
237 238
	coinbase := self.Coinbase()
	sender, _ := self.From() // err already checked
239 240
	// Return remaining gas
	remaining := new(big.Int).Mul(self.gas, self.msg.GasPrice())
O
obscuren 已提交
241
	sender.AddBalance(remaining)
242

O
obscuren 已提交
243
	uhalf := new(big.Int).Div(self.gasUsed(), common.Big2)
O
obscuren 已提交
244
	for addr, ref := range self.state.Refunds() {
O
obscuren 已提交
245
		refund := common.BigMin(uhalf, ref)
246
		self.gas.Add(self.gas, refund)
O
obscuren 已提交
247
		self.state.AddBalance(common.StringToAddress(addr), refund.Mul(refund, self.msg.GasPrice()))
O
obscuren 已提交
248 249
	}

250
	coinbase.RefundGas(self.gas, self.msg.GasPrice())
O
obscuren 已提交
251 252
}

253
func (self *StateTransition) gasUsed() *big.Int {
O
obscuren 已提交
254 255
	return new(big.Int).Sub(self.initialGas, self.gas)
}
256 257 258

// Converts an message in to a state object
func makeContract(msg Message, state *state.StateDB) *state.StateObject {
O
obscuren 已提交
259 260
	faddr, _ := msg.From()
	addr := crypto.CreateAddress(faddr, msg.Nonce())
261

O
obscuren 已提交
262 263
	contract := state.GetOrNewStateObject(addr)
	contract.SetInitCode(msg.Data())
264

O
obscuren 已提交
265
	return contract
266
}