state_transition.go 8.0 KB
Newer Older
F
Felix Lange 已提交
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
F
Felix Lange 已提交
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
F
Felix Lange 已提交
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
F
Felix Lange 已提交
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
F
Felix Lange 已提交
12 13 14
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
15
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
F
Felix Lange 已提交
16

O
obscuren 已提交
17
package core
18 19 20

import (
	"fmt"
21
	"math/big"
22

O
obscuren 已提交
23
	"github.com/ethereum/go-ethereum/common"
O
obscuren 已提交
24
	"github.com/ethereum/go-ethereum/core/vm"
O
obscuren 已提交
25 26
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
27
	"github.com/ethereum/go-ethereum/params"
28 29
)

30 31 32 33
var (
	Big0 = big.NewInt(0)
)

O
obscuren 已提交
34
/*
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
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 gas
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
*/
51
type StateTransition struct {
52
	gp            *GasPool
53 54 55 56 57
	msg           Message
	gas, gasPrice *big.Int
	initialGas    *big.Int
	value         *big.Int
	data          []byte
58
	state         vm.Database
59

60
	env vm.Environment
61 62
}

63
// Message represents a message sent to a contract.
64
type Message interface {
65
	From() (common.Address, error)
66
	FromFrontier() (common.Address, error)
67
	To() *common.Address
68 69 70 71 72 73

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

	Nonce() uint64
74
	CheckNonce() bool
75
	Data() []byte
76
}
O
obscuren 已提交
77

O
obscuren 已提交
78
func MessageCreatesContract(msg Message) bool {
79
	return msg.To() == nil
O
obscuren 已提交
80 81
}

82
// IntrinsicGas computes the 'intrinsic gas' for a message
F
Felix Lange 已提交
83
// with the given data.
84 85 86 87 88 89 90
func IntrinsicGas(data []byte, contractCreation, homestead bool) *big.Int {
	igas := new(big.Int)
	if contractCreation && homestead {
		igas.Set(params.TxGasContractCreation)
	} else {
		igas.Set(params.TxGas)
	}
F
Felix Lange 已提交
91 92 93 94 95 96
	if len(data) > 0 {
		var nz int64
		for _, byt := range data {
			if byt != 0 {
				nz++
			}
O
obscuren 已提交
97
		}
F
Felix Lange 已提交
98 99 100 101 102 103
		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 已提交
104 105 106 107
	}
	return igas
}

108 109 110
// NewStateTransition initialises and returns a new state transition object.
func NewStateTransition(env vm.Environment, msg Message, gp *GasPool) *StateTransition {
	return &StateTransition{
F
Felix Lange 已提交
111
		gp:         gp,
112 113 114
		env:        env,
		msg:        msg,
		gas:        new(big.Int),
115
		gasPrice:   msg.GasPrice(),
116 117 118
		initialGas: new(big.Int),
		value:      msg.Value(),
		data:       msg.Data(),
119
		state:      env.Db(),
120
	}
121 122 123 124 125 126 127 128 129 130 131 132 133 134
}

// ApplyMessage computes the new state by applying the given message
// against the old state within the environment.
//
// ApplyMessage returns the bytes returned by any EVM execution (if it took place),
// the gas used (which includes gas refunds) and an error if it failed. An error always
// indicates a core error meaning that the message would always fail for that particular
// state and would never be accepted within a block.
func ApplyMessage(env vm.Environment, msg Message, gp *GasPool) ([]byte, *big.Int, error) {
	st := NewStateTransition(env, msg, gp)

	ret, _, gasUsed, err := st.TransitionDb()
	return ret, gasUsed, err
135 136
}

137
func (self *StateTransition) from() (vm.Account, error) {
138 139 140 141
	var (
		f   common.Address
		err error
	)
142
	if self.env.ChainConfig().IsHomestead(self.env.BlockNumber()) {
143 144 145 146
		f, err = self.msg.From()
	} else {
		f, err = self.msg.FromFrontier()
	}
147 148 149
	if err != nil {
		return nil, err
	}
150 151 152 153
	if !self.state.Exist(f) {
		return self.state.CreateAccount(f), nil
	}
	return self.state.GetAccount(f), nil
154
}
155

156
func (self *StateTransition) to() vm.Account {
157
	if self.msg == nil {
158 159
		return nil
	}
160 161 162 163
	to := self.msg.To()
	if to == nil {
		return nil // contract creation
	}
164 165 166 167 168

	if !self.state.Exist(*to) {
		return self.state.CreateAccount(*to)
	}
	return self.state.GetAccount(*to)
169 170
}

171
func (self *StateTransition) useGas(amount *big.Int) error {
172
	if self.gas.Cmp(amount) < 0 {
173
		return vm.OutOfGasError
174 175 176 177 178 179
	}
	self.gas.Sub(self.gas, amount)

	return nil
}

180
func (self *StateTransition) addGas(amount *big.Int) {
181 182 183
	self.gas.Add(self.gas, amount)
}

184
func (self *StateTransition) buyGas() error {
185 186
	mgas := self.msg.Gas()
	mgval := new(big.Int).Mul(mgas, self.gasPrice)
187

188
	sender, err := self.from()
189 190 191
	if err != nil {
		return err
	}
192 193
	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())
194
	}
195
	if err = self.gp.SubGas(mgas); err != nil {
196 197
		return err
	}
198
	self.addGas(mgas)
199 200
	self.initialGas.Set(mgas)
	sender.SubBalance(mgval)
201 202 203
	return nil
}

O
obscuren 已提交
204
func (self *StateTransition) preCheck() (err error) {
205
	msg := self.msg
206
	sender, err := self.from()
207 208 209
	if err != nil {
		return err
	}
O
obscuren 已提交
210 211

	// Make sure this transaction's nonce is correct
212 213 214 215
	if msg.CheckNonce() {
		if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
			return NonceError(msg.Nonce(), n)
		}
O
obscuren 已提交
216 217
	}

218
	// Pre-pay gas
219
	if err = self.buyGas(); err != nil {
220
		if IsGasLimitErr(err) {
O
obscuren 已提交
221 222
			return err
		}
O
obscuren 已提交
223
		return InvalidTxError(err)
O
obscuren 已提交
224 225 226 227 228
	}

	return nil
}

229 230
// TransitionDb will move the state by applying the message against the given environment.
func (self *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, err error) {
O
obscuren 已提交
231 232 233
	if err = self.preCheck(); err != nil {
		return
	}
234
	msg := self.msg
235
	sender, _ := self.from() // err checked in preCheck
236

237
	homestead := self.env.ChainConfig().IsHomestead(self.env.BlockNumber())
238
	contractCreation := MessageCreatesContract(msg)
O
obscuren 已提交
239
	// Pay intrinsic gas
240
	if err = self.useGas(IntrinsicGas(self.data, contractCreation, homestead)); err != nil {
241
		return nil, nil, nil, InvalidTxError(err)
242 243
	}

244
	vmenv := self.env
245
	//var addr common.Address
246
	if contractCreation {
247 248 249 250
		ret, _, err = vmenv.Create(sender, self.data, self.gas, self.gasPrice, self.value)
		if homestead && err == vm.CodeStoreOutOfGasError {
			self.gas = Big0
		}
251

252 253 254
		if err != nil {
			ret = nil
			glog.V(logger.Core).Infoln("VM create err:", err)
255
		}
O
obscuren 已提交
256
	} else {
O
obscuren 已提交
257
		// Increment the nonce for the next transaction
258 259
		self.state.SetNonce(sender.Address(), self.state.GetNonce(sender.Address())+1)
		ret, err = vmenv.Call(sender, self.to().Address(), self.data, self.gas, self.gasPrice, self.value)
260 261 262
		if err != nil {
			glog.V(logger.Core).Infoln("VM call err:", err)
		}
O
obscuren 已提交
263
	}
264

O
obscuren 已提交
265
	if err != nil && IsValueTransferErr(err) {
266
		return nil, nil, nil, InvalidTxError(err)
267 268
	}

269 270 271 272 273
	// We aren't interested in errors here. Errors returned by the VM are non-consensus errors and therefor shouldn't bubble up
	if err != nil {
		err = nil
	}

274 275
	requiredGas = new(big.Int).Set(self.gasUsed())

276
	self.refundGas()
F
Felix Lange 已提交
277
	self.state.AddBalance(self.env.Coinbase(), new(big.Int).Mul(self.gasUsed(), self.gasPrice))
O
obscuren 已提交
278

279
	return ret, requiredGas, self.gasUsed(), err
O
obscuren 已提交
280
}
O
obscuren 已提交
281

282
func (self *StateTransition) refundGas() {
283 284
	// Return eth for remaining gas to the sender account,
	// exchanged at the original rate.
285
	sender, _ := self.from() // err already checked
286
	remaining := new(big.Int).Mul(self.gas, self.gasPrice)
O
obscuren 已提交
287
	sender.AddBalance(remaining)
288

289
	// Apply refund counter, capped to half of the used gas.
290
	uhalf := remaining.Div(self.gasUsed(), common.Big2)
291
	refund := common.BigMin(uhalf, self.state.GetRefund())
O
obscuren 已提交
292
	self.gas.Add(self.gas, refund)
293
	self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
O
obscuren 已提交
294

295 296 297
	// Also return remaining gas to the block gas counter so it is
	// available for the next transaction.
	self.gp.AddGas(self.gas)
O
obscuren 已提交
298 299
}

300
func (self *StateTransition) gasUsed() *big.Int {
O
obscuren 已提交
301 302
	return new(big.Int).Sub(self.initialGas, self.gas)
}