state_transition.go 6.3 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
	"github.com/ethereum/go-ethereum/crypto"
O
obscuren 已提交
9
	"github.com/ethereum/go-ethereum/state"
10
	"github.com/ethereum/go-ethereum/vm"
11 12
)

O
obscuren 已提交
13 14
const tryJit = false

O
obscuren 已提交
15
var ()
O
obscuren 已提交
16

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

O
obscuren 已提交
42
	cb, rec, sen *state.StateObject
43

44
	env vm.Environment
45 46 47
}

type Message interface {
O
obscuren 已提交
48 49
	From() common.Address
	To() common.Address
50 51 52 53 54 55 56

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

	Nonce() uint64
	Data() []byte
57 58
}

59 60
func AddressFromMessage(msg Message) []byte {
	// Generate a new address
O
obscuren 已提交
61
	return crypto.Sha3(common.NewValue([]interface{}{msg.From(), msg.Nonce()}).Encode())[12:]
62 63
}

O
obscuren 已提交
64 65 66 67
func MessageCreatesContract(msg Message) bool {
	return len(msg.To()) == 0
}

O
obscuren 已提交
68 69 70 71
func MessageGasValue(msg Message) *big.Int {
	return new(big.Int).Mul(msg.Gas(), msg.GasPrice())
}

72 73 74 75
func ApplyMessage(env vm.Environment, msg Message, coinbase *state.StateObject) ([]byte, *big.Int, error) {
	return NewStateTransition(env, msg, coinbase).transitionState()
}

76 77 78 79 80 81 82 83 84 85 86 87
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,
88
	}
89 90
}

O
obscuren 已提交
91
func (self *StateTransition) Coinbase() *state.StateObject {
O
obscuren 已提交
92
	return self.state.GetOrNewStateObject(self.coinbase)
93
}
94
func (self *StateTransition) From() *state.StateObject {
O
obscuren 已提交
95
	return self.state.GetOrNewStateObject(self.msg.From())
96
}
97
func (self *StateTransition) To() *state.StateObject {
O
obscuren 已提交
98
	if self.msg != nil && MessageCreatesContract(self.msg) {
99 100
		return nil
	}
O
obscuren 已提交
101
	return self.state.GetOrNewStateObject(self.msg.To())
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
}

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

120
	sender := self.From()
O
obscuren 已提交
121
	if sender.Balance().Cmp(MessageGasValue(self.msg)) < 0 {
122
		return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address()[:4], MessageGasValue(self.msg), sender.Balance())
123 124 125
	}

	coinbase := self.Coinbase()
126
	err = coinbase.BuyGas(self.msg.Gas(), self.msg.GasPrice())
127 128 129 130
	if err != nil {
		return err
	}

131
	self.AddGas(self.msg.Gas())
O
obscuren 已提交
132
	self.initialGas.Set(self.msg.Gas())
O
obscuren 已提交
133
	sender.SubBalance(MessageGasValue(self.msg))
134 135 136 137

	return nil
}

O
obscuren 已提交
138 139
func (self *StateTransition) preCheck() (err error) {
	var (
140 141
		msg    = self.msg
		sender = self.From()
O
obscuren 已提交
142 143 144
	)

	// Make sure this transaction's nonce is correct
145 146
	if sender.Nonce() != msg.Nonce() {
		return NonceError(msg.Nonce(), sender.Nonce())
O
obscuren 已提交
147 148 149 150
	}

	// Pre-pay gas / Buy gas of the coinbase account
	if err = self.BuyGas(); err != nil {
O
obscuren 已提交
151 152 153
		if state.IsGasLimitErr(err) {
			return err
		}
O
obscuren 已提交
154
		return InvalidTxError(err)
O
obscuren 已提交
155 156 157 158 159
	}

	return nil
}

160
func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, err error) {
161
	// statelogger.Debugf("(~) %x\n", self.msg.Hash())
162

O
obscuren 已提交
163 164 165 166 167
	// XXX Transactions after this point are considered valid.
	if err = self.preCheck(); err != nil {
		return
	}

168
	var (
169 170
		msg    = self.msg
		sender = self.From()
171 172
	)

O
obscuren 已提交
173
	// Transaction gas
O
obscuren 已提交
174
	if err = self.UseGas(vm.GasTx); err != nil {
175
		return nil, nil, InvalidTxError(err)
176 177
	}

O
obscuren 已提交
178 179 180 181
	// Increment the nonce for the next transaction
	self.state.SetNonce(sender.Address(), sender.Nonce()+1)
	//sender.Nonce += 1

O
obscuren 已提交
182
	// Pay data gas
O
obscuren 已提交
183 184 185
	var dgas int64
	for _, byt := range self.data {
		if byt != 0 {
O
obscuren 已提交
186
			dgas += vm.GasTxDataNonzeroByte.Int64()
O
obscuren 已提交
187
		} else {
O
obscuren 已提交
188
			dgas += vm.GasTxDataZeroByte.Int64()
O
obscuren 已提交
189 190 191
		}
	}
	if err = self.UseGas(big.NewInt(dgas)); err != nil {
192
		return nil, nil, InvalidTxError(err)
193 194
	}

195
	vmenv := self.env
O
obscuren 已提交
196
	var ref vm.ContextRef
O
obscuren 已提交
197
	if MessageCreatesContract(msg) {
198
		contract := makeContract(msg, self.state)
199
		ret, err, ref = vmenv.Create(sender, contract.Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
200 201 202
		if err == nil {
			dataGas := big.NewInt(int64(len(ret)))
			dataGas.Mul(dataGas, vm.GasCreateByte)
O
obscuren 已提交
203
			if err := self.UseGas(dataGas); err == nil {
204
				ref.SetCode(ret)
205 206
			} else {
				statelogger.Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
207 208
			}
		}
O
obscuren 已提交
209
	} else {
210
		ret, err = vmenv.Call(self.From(), self.To().Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
O
obscuren 已提交
211
	}
212

O
obscuren 已提交
213
	if err != nil && IsValueTransferErr(err) {
214
		return nil, nil, InvalidTxError(err)
215 216
	}

217 218
	self.refundGas()
	self.state.AddBalance(self.coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice))
O
obscuren 已提交
219

220
	return ret, self.gasUsed(), err
O
obscuren 已提交
221
}
O
obscuren 已提交
222

223
func (self *StateTransition) refundGas() {
224 225 226
	coinbase, sender := self.Coinbase(), self.From()
	// Return remaining gas
	remaining := new(big.Int).Mul(self.gas, self.msg.GasPrice())
O
obscuren 已提交
227
	sender.AddBalance(remaining)
228

O
obscuren 已提交
229
	uhalf := new(big.Int).Div(self.gasUsed(), common.Big2)
O
obscuren 已提交
230
	for addr, ref := range self.state.Refunds() {
O
obscuren 已提交
231
		refund := common.BigMin(uhalf, ref)
232
		self.gas.Add(self.gas, refund)
O
Bump  
obscuren 已提交
233
		self.state.AddBalance([]byte(addr), refund.Mul(refund, self.msg.GasPrice()))
O
obscuren 已提交
234 235
	}

236
	coinbase.RefundGas(self.gas, self.msg.GasPrice())
O
obscuren 已提交
237 238
}

239
func (self *StateTransition) gasUsed() *big.Int {
O
obscuren 已提交
240 241
	return new(big.Int).Sub(self.initialGas, self.gas)
}
242 243 244 245 246 247 248 249 250 251

// Converts an message in to a state object
func makeContract(msg Message, state *state.StateDB) *state.StateObject {
	addr := AddressFromMessage(msg)

	contract := state.GetOrNewStateObject(addr)
	contract.SetInitCode(msg.Data())

	return contract
}