state_transition.go 6.96 KB
Newer Older
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
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,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
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/>.
16

obscuren's avatar
obscuren committed
17
package core
18 19 20

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

obscuren's avatar
obscuren committed
23
	"github.com/ethereum/go-ethereum/common"
obscuren's avatar
obscuren committed
24
	"github.com/ethereum/go-ethereum/core/vm"
obscuren's avatar
obscuren committed
25 26
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
27
	"github.com/ethereum/go-ethereum/params"
28 29
)

obscuren's avatar
obscuren committed
30
/*
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
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
*/
47
type StateTransition struct {
48
	gp            *GasPool
49 50 51 52 53
	msg           Message
	gas, gasPrice *big.Int
	initialGas    *big.Int
	value         *big.Int
	data          []byte
54
	state         vm.Database
55

56
	env vm.Environment
57 58
}

59
// Message represents a message sent to a contract.
60
type Message interface {
61 62
	From() (common.Address, error)
	To() *common.Address
63 64 65 66 67 68 69

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

	Nonce() uint64
	Data() []byte
70
}
obscuren's avatar
obscuren committed
71

obscuren's avatar
obscuren committed
72
func MessageCreatesContract(msg Message) bool {
73
	return msg.To() == nil
obscuren's avatar
obscuren committed
74 75
}

76 77 78
// IntrinsicGas computes the 'intrisic gas' for a message
// with the given data.
func IntrinsicGas(data []byte) *big.Int {
obscuren's avatar
obscuren committed
79
	igas := new(big.Int).Set(params.TxGas)
80 81 82 83 84 85
	if len(data) > 0 {
		var nz int64
		for _, byt := range data {
			if byt != 0 {
				nz++
			}
obscuren's avatar
obscuren committed
86
		}
87 88 89 90 91 92
		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)
obscuren's avatar
obscuren committed
93 94 95 96
	}
	return igas
}

97
func ApplyMessage(env vm.Environment, msg Message, gp *GasPool) ([]byte, *big.Int, error) {
98
	var st = StateTransition{
99
		gp:         gp,
100 101 102
		env:        env,
		msg:        msg,
		gas:        new(big.Int),
103
		gasPrice:   msg.GasPrice(),
104 105 106
		initialGas: new(big.Int),
		value:      msg.Value(),
		data:       msg.Data(),
107
		state:      env.Db(),
108
	}
109
	return st.transitionDb()
110 111
}

112
func (self *StateTransition) from() (vm.Account, error) {
113 114 115 116
	f, err := self.msg.From()
	if err != nil {
		return nil, err
	}
117 118 119 120
	if !self.state.Exist(f) {
		return self.state.CreateAccount(f), nil
	}
	return self.state.GetAccount(f), nil
121
}
122
func (self *StateTransition) to() vm.Account {
123
	if self.msg == nil {
124 125
		return nil
	}
126 127 128 129
	to := self.msg.To()
	if to == nil {
		return nil // contract creation
	}
130 131 132 133 134

	if !self.state.Exist(*to) {
		return self.state.CreateAccount(*to)
	}
	return self.state.GetAccount(*to)
135 136
}

137
func (self *StateTransition) useGas(amount *big.Int) error {
138
	if self.gas.Cmp(amount) < 0 {
139
		return vm.OutOfGasError
140 141 142 143 144 145
	}
	self.gas.Sub(self.gas, amount)

	return nil
}

146
func (self *StateTransition) addGas(amount *big.Int) {
147 148 149
	self.gas.Add(self.gas, amount)
}

150
func (self *StateTransition) buyGas() error {
151 152
	mgas := self.msg.Gas()
	mgval := new(big.Int).Mul(mgas, self.gasPrice)
153

154
	sender, err := self.from()
155 156 157
	if err != nil {
		return err
	}
158 159
	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())
160
	}
161
	if err = self.gp.SubGas(mgas); err != nil {
162 163
		return err
	}
164
	self.addGas(mgas)
165 166
	self.initialGas.Set(mgas)
	sender.SubBalance(mgval)
167 168 169
	return nil
}

170
func (self *StateTransition) preCheck() (err error) {
171
	msg := self.msg
172
	sender, err := self.from()
173 174 175
	if err != nil {
		return err
	}
176 177

	// Make sure this transaction's nonce is correct
178 179 180
	//if sender.Nonce() != msg.Nonce() {
	if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
		return NonceError(msg.Nonce(), n)
181 182
	}

183
	// Pre-pay gas
184
	if err = self.buyGas(); err != nil {
185
		if IsGasLimitErr(err) {
obscuren's avatar
obscuren committed
186 187
			return err
		}
188
		return InvalidTxError(err)
189 190 191 192 193
	}

	return nil
}

194
func (self *StateTransition) transitionDb() (ret []byte, usedGas *big.Int, err error) {
195 196 197 198
	if err = self.preCheck(); err != nil {
		return
	}

199
	msg := self.msg
200
	sender, _ := self.from() // err checked in preCheck
201

obscuren's avatar
obscuren committed
202
	// Pay intrinsic gas
203
	if err = self.useGas(IntrinsicGas(self.data)); err != nil {
204
		return nil, nil, InvalidTxError(err)
205 206
	}

207
	vmenv := self.env
208
	var addr common.Address
obscuren's avatar
obscuren committed
209
	if MessageCreatesContract(msg) {
210
		ret, addr, err = vmenv.Create(sender, self.data, self.gas, self.gasPrice, self.value)
211 212
		if err == nil {
			dataGas := big.NewInt(int64(len(ret)))
213
			dataGas.Mul(dataGas, params.CreateDataGas)
214 215
			if err := self.useGas(dataGas); err == nil {
				self.state.SetCode(addr, ret)
216
			} else {
217
				ret = nil // does not affect consensus but useful for StateTests validations
obscuren's avatar
obscuren committed
218
				glog.V(logger.Core).Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
219 220
			}
		}
221
		glog.V(logger.Core).Infoln("VM create err:", err)
obscuren's avatar
obscuren committed
222
	} else {
obscuren's avatar
obscuren committed
223
		// Increment the nonce for the next transaction
224 225
		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)
226
		glog.V(logger.Core).Infoln("VM call err:", err)
obscuren's avatar
obscuren committed
227
	}
228

obscuren's avatar
obscuren committed
229
	if err != nil && IsValueTransferErr(err) {
230
		return nil, nil, InvalidTxError(err)
231 232
	}

233 234 235 236 237
	// 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
	}

238
	if vm.Debug {
239
		vm.StdErrFormat(vmenv.StructLogs())
240 241
	}

242
	self.refundGas()
243
	self.state.AddBalance(self.env.Coinbase(), new(big.Int).Mul(self.gasUsed(), self.gasPrice))
244

245
	return ret, self.gasUsed(), err
246
}
obscuren's avatar
obscuren committed
247

248
func (self *StateTransition) refundGas() {
249 250
	// Return eth for remaining gas to the sender account,
	// exchanged at the original rate.
251
	sender, _ := self.from() // err already checked
252
	remaining := new(big.Int).Mul(self.gas, self.gasPrice)
253
	sender.AddBalance(remaining)
254

255
	// Apply refund counter, capped to half of the used gas.
256
	uhalf := remaining.Div(self.gasUsed(), common.Big2)
257
	refund := common.BigMin(uhalf, self.state.GetRefund())
258
	self.gas.Add(self.gas, refund)
259
	self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
obscuren's avatar
obscuren committed
260

261 262 263
	// Also return remaining gas to the block gas counter so it is
	// available for the next transaction.
	self.gp.AddGas(self.gas)
obscuren's avatar
obscuren committed
264 265
}

266
func (self *StateTransition) gasUsed() *big.Int {
obscuren's avatar
obscuren committed
267 268
	return new(big.Int).Sub(self.initialGas, self.gas)
}