state_transition.go 7.6 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 53 54 55 56 57 58 59 60
	gp            *GasPool
	msg           Message
	gas, gasPrice *big.Int
	initialGas    *big.Int
	value         *big.Int
	data          []byte
	state         vm.StateDB

	env *vm.EVM
61 62
}

63
// Message represents a message sent to a contract.
64
type Message interface {
J
Jeffrey Wilcke 已提交
65 66
	From() common.Address
	//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
func IntrinsicGas(data []byte, contractCreation, homestead bool) *big.Int {
	igas := new(big.Int)
	if contractCreation && homestead {
87
		igas.Set(params.TxGasContractCreation)
88
	} else {
89
		igas.Set(params.TxGas)
90
	}
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
		m := big.NewInt(nz)
99
		m.Mul(m, params.TxDataNonZeroGas)
F
Felix Lange 已提交
100 101
		igas.Add(igas, m)
		m.SetInt64(int64(len(data)) - nz)
102
		m.Mul(m, params.TxDataZeroGas)
F
Felix Lange 已提交
103
		igas.Add(igas, m)
O
obscuren 已提交
104 105 106 107
	}
	return igas
}

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

// 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.
130 131
func ApplyMessage(env *vm.EVM, msg Message, gp *GasPool) ([]byte, *big.Int, error) {
	st := NewStateTransition(env, msg, gp)
132 133 134

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

J
Jeffrey Wilcke 已提交
137 138
func (self *StateTransition) from() vm.Account {
	f := self.msg.From()
139
	if !self.state.Exist(f) {
J
Jeffrey Wilcke 已提交
140
		return self.state.CreateAccount(f)
141
	}
J
Jeffrey Wilcke 已提交
142
	return self.state.GetAccount(f)
143
}
144

145
func (self *StateTransition) to() vm.Account {
146
	if self.msg == nil {
147 148
		return nil
	}
149 150 151 152
	to := self.msg.To()
	if to == nil {
		return nil // contract creation
	}
153 154 155 156 157

	if !self.state.Exist(*to) {
		return self.state.CreateAccount(*to)
	}
	return self.state.GetAccount(*to)
158 159
}

160 161
func (self *StateTransition) useGas(amount *big.Int) error {
	if self.gas.Cmp(amount) < 0 {
162
		return vm.ErrOutOfGas
163
	}
164
	self.gas.Sub(self.gas, amount)
165 166 167 168

	return nil
}

169 170 171 172
func (self *StateTransition) addGas(amount *big.Int) {
	self.gas.Add(self.gas, amount)
}

173
func (self *StateTransition) buyGas() error {
174 175
	mgas := self.msg.Gas()
	mgval := new(big.Int).Mul(mgas, self.gasPrice)
176

J
Jeffrey Wilcke 已提交
177
	sender := self.from()
178 179
	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())
180
	}
J
Jeffrey Wilcke 已提交
181
	if err := self.gp.SubGas(mgas); err != nil {
182 183
		return err
	}
184
	self.addGas(mgas)
185 186
	self.initialGas.Set(mgas)
	sender.SubBalance(mgval)
187 188 189
	return nil
}

O
obscuren 已提交
190
func (self *StateTransition) preCheck() (err error) {
191
	msg := self.msg
J
Jeffrey Wilcke 已提交
192
	sender := self.from()
O
obscuren 已提交
193 194

	// Make sure this transaction's nonce is correct
195 196 197 198
	if msg.CheckNonce() {
		if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
			return NonceError(msg.Nonce(), n)
		}
O
obscuren 已提交
199 200
	}

201
	// Pre-pay gas
202
	if err = self.buyGas(); err != nil {
203
		if IsGasLimitErr(err) {
O
obscuren 已提交
204 205
			return err
		}
O
obscuren 已提交
206
		return InvalidTxError(err)
O
obscuren 已提交
207 208 209 210 211
	}

	return nil
}

212
// TransitionDb will move the state by applying the message against the given environment.
213
func (self *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, err error) {
O
obscuren 已提交
214 215 216
	if err = self.preCheck(); err != nil {
		return
	}
217
	msg := self.msg
J
Jeffrey Wilcke 已提交
218
	sender := self.from() // err checked in preCheck
219

220
	homestead := self.env.ChainConfig().IsHomestead(self.env.BlockNumber)
221
	contractCreation := MessageCreatesContract(msg)
O
obscuren 已提交
222
	// Pay intrinsic gas
223
	if err = self.useGas(IntrinsicGas(self.data, contractCreation, homestead)); err != nil {
224
		return nil, nil, nil, InvalidTxError(err)
225 226
	}

227
	var (
228
		vmenv = self.env
229 230 231 232 233
		// vm errors do not effect consensus and are therefor
		// not assigned to err, except for insufficient balance
		// error.
		vmerr error
	)
234
	if contractCreation {
235
		ret, _, vmerr = vmenv.Create(sender, self.data, self.gas, self.value)
O
obscuren 已提交
236
	} else {
O
obscuren 已提交
237
		// Increment the nonce for the next transaction
238
		self.state.SetNonce(sender.Address(), self.state.GetNonce(sender.Address())+1)
239
		ret, vmerr = vmenv.Call(sender, self.to().Address(), self.data, self.gas, self.value)
240
	}
241 242 243 244 245 246 247 248
	if vmerr != nil {
		glog.V(logger.Core).Infoln("vm returned with error:", err)
		// The only possible consensus-error would be if there wasn't
		// sufficient balance to make the transfer happen. The first
		// balance transfer may never fail.
		if vmerr == vm.ErrInsufficientBalance {
			return nil, nil, nil, InvalidTxError(vmerr)
		}
249 250
	}

251 252
	requiredGas = new(big.Int).Set(self.gasUsed())

253
	self.refundGas()
254
	self.state.AddBalance(self.env.Coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice))
O
obscuren 已提交
255

256
	return ret, requiredGas, self.gasUsed(), err
O
obscuren 已提交
257
}
O
obscuren 已提交
258

259
func (self *StateTransition) refundGas() {
260 261
	// Return eth for remaining gas to the sender account,
	// exchanged at the original rate.
J
Jeffrey Wilcke 已提交
262
	sender := self.from() // err already checked
263
	remaining := new(big.Int).Mul(self.gas, self.gasPrice)
O
obscuren 已提交
264
	sender.AddBalance(remaining)
265

266
	// Apply refund counter, capped to half of the used gas.
267
	uhalf := remaining.Div(self.gasUsed(), common.Big2)
268
	refund := common.BigMin(uhalf, self.state.GetRefund())
269
	self.gas.Add(self.gas, refund)
270
	self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
O
obscuren 已提交
271

272 273
	// Also return remaining gas to the block gas counter so it is
	// available for the next transaction.
274
	self.gp.AddGas(self.gas)
O
obscuren 已提交
275 276
}

277
func (self *StateTransition) gasUsed() *big.Int {
278
	return new(big.Int).Sub(self.initialGas, self.gas)
O
obscuren 已提交
279
}