state_transition.go 7.1 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 5 6 7 8
//
// go-ethereum is free software: you can redistribute it and/or modify
// 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 25
	"github.com/ethereum/go-ethereum/core/state"
	"github.com/ethereum/go-ethereum/core/vm"
O
obscuren 已提交
26 27
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
28
	"github.com/ethereum/go-ethereum/params"
29 30
)

O
obscuren 已提交
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 / 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
 */
47
type StateTransition struct {
O
obscuren 已提交
48
	coinbase      common.Address
49 50 51 52 53 54
	msg           Message
	gas, gasPrice *big.Int
	initialGas    *big.Int
	value         *big.Int
	data          []byte
	state         *state.StateDB
55

O
obscuren 已提交
56
	cb, rec, sen *state.StateObject
57

58
	env vm.Environment
59 60
}

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

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

	Nonce() uint64
	Data() []byte
72
}
O
obscuren 已提交
73

O
obscuren 已提交
74
func MessageCreatesContract(msg Message) bool {
75
	return msg.To() == nil
O
obscuren 已提交
76 77
}

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

99 100 101 102
func ApplyMessage(env vm.Environment, msg Message, coinbase *state.StateObject) ([]byte, *big.Int, error) {
	return NewStateTransition(env, msg, coinbase).transitionState()
}

103 104 105 106 107 108
func NewStateTransition(env vm.Environment, msg Message, coinbase *state.StateObject) *StateTransition {
	return &StateTransition{
		coinbase:   coinbase.Address(),
		env:        env,
		msg:        msg,
		gas:        new(big.Int),
109
		gasPrice:   msg.GasPrice(),
110 111 112 113 114
		initialGas: new(big.Int),
		value:      msg.Value(),
		data:       msg.Data(),
		state:      env.State(),
		cb:         coinbase,
115
	}
116 117
}

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

func (self *StateTransition) UseGas(amount *big.Int) error {
	if self.gas.Cmp(amount) < 0 {
141
		return vm.OutOfGasError
142 143 144 145 146 147 148 149 150 151 152
	}
	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 {
153 154
	mgas := self.msg.Gas()
	mgval := new(big.Int).Mul(mgas, self.gasPrice)
155

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

O
obscuren 已提交
172
func (self *StateTransition) preCheck() (err error) {
173 174 175 176 177
	msg := self.msg
	sender, err := self.From()
	if err != nil {
		return err
	}
O
obscuren 已提交
178 179

	// Make sure this transaction's nonce is correct
180 181
	if sender.Nonce() != msg.Nonce() {
		return NonceError(msg.Nonce(), sender.Nonce())
O
obscuren 已提交
182 183 184 185
	}

	// Pre-pay gas / Buy gas of the coinbase account
	if err = self.BuyGas(); err != nil {
O
obscuren 已提交
186 187 188
		if state.IsGasLimitErr(err) {
			return err
		}
O
obscuren 已提交
189
		return InvalidTxError(err)
O
obscuren 已提交
190 191 192 193 194
	}

	return nil
}

195
func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, err error) {
O
obscuren 已提交
196 197 198 199
	if err = self.preCheck(); err != nil {
		return
	}

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

O
obscuren 已提交
203
	// Pay intrinsic gas
204
	if err = self.UseGas(IntrinsicGas(self.data)); err != nil {
205
		return nil, nil, InvalidTxError(err)
206 207
	}

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

O
obscuren 已提交
230
	if err != nil && IsValueTransferErr(err) {
231
		return nil, nil, InvalidTxError(err)
232 233
	}

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

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

243 244
	self.refundGas()
	self.state.AddBalance(self.coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice))
O
obscuren 已提交
245

246
	return ret, self.gasUsed(), err
O
obscuren 已提交
247
}
O
obscuren 已提交
248

249
func (self *StateTransition) refundGas() {
250 251
	coinbase := self.Coinbase()
	sender, _ := self.From() // err already checked
252
	// Return remaining gas
253
	remaining := new(big.Int).Mul(self.gas, self.gasPrice)
O
obscuren 已提交
254
	sender.AddBalance(remaining)
255

256
	uhalf := remaining.Div(self.gasUsed(), common.Big2)
O
obscuren 已提交
257 258
	refund := common.BigMin(uhalf, self.state.Refunds())
	self.gas.Add(self.gas, refund)
259
	self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
O
obscuren 已提交
260

261
	coinbase.AddGas(self.gas, self.gasPrice)
O
obscuren 已提交
262 263
}

264
func (self *StateTransition) gasUsed() *big.Int {
O
obscuren 已提交
265 266
	return new(big.Int).Sub(self.initialGas, self.gas)
}