state_transition.go 5.8 KB
Newer Older
O
obscuren 已提交
1
package core
2 3 4

import (
	"fmt"
5 6
	"math/big"

O
obscuren 已提交
7
	"github.com/ethereum/go-ethereum/core/types"
8 9
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethutil"
O
obscuren 已提交
10
	"github.com/ethereum/go-ethereum/state"
11
	"github.com/ethereum/go-ethereum/vm"
12 13
)

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

O
obscuren 已提交
40
	cb, rec, sen *state.StateObject
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

	Env vm.Environment
}

type Message interface {
	Hash() []byte

	From() []byte
	To() []byte

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

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

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

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
func NewStateTransition(coinbase *state.StateObject, msg Message, state *state.StateDB, block *types.Block) *StateTransition {
O
obscuren 已提交
73
	return &StateTransition{coinbase.Address(), msg.To(), msg, new(big.Int), new(big.Int).Set(msg.GasPrice()), new(big.Int), msg.Value(), msg.Data(), state, block, coinbase, nil, nil, nil}
74 75 76 77 78 79 80 81
}

func (self *StateTransition) VmEnv() vm.Environment {
	if self.Env == nil {
		self.Env = NewEnv(self.state, self.msg, self.block)
	}

	return self.Env
82 83
}

O
obscuren 已提交
84
func (self *StateTransition) Coinbase() *state.StateObject {
O
obscuren 已提交
85
	return self.state.GetOrNewStateObject(self.coinbase)
86
}
87
func (self *StateTransition) From() *state.StateObject {
O
obscuren 已提交
88
	return self.state.GetOrNewStateObject(self.msg.From())
89
}
90
func (self *StateTransition) To() *state.StateObject {
O
obscuren 已提交
91
	if self.msg != nil && MessageCreatesContract(self.msg) {
92 93
		return nil
	}
O
obscuren 已提交
94
	return self.state.GetOrNewStateObject(self.msg.To())
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
}

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

113
	sender := self.From()
O
obscuren 已提交
114
	if sender.Balance().Cmp(MessageGasValue(self.msg)) < 0 {
115
		return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address()[:4], MessageGasValue(self.msg), sender.Balance())
116 117 118
	}

	coinbase := self.Coinbase()
119
	err = coinbase.BuyGas(self.msg.Gas(), self.msg.GasPrice())
120 121 122 123
	if err != nil {
		return err
	}

124
	self.AddGas(self.msg.Gas())
O
obscuren 已提交
125 126
	self.initialGas.Set(self.msg.Gas())
	sender.SubAmount(MessageGasValue(self.msg))
127 128 129 130

	return nil
}

O
obscuren 已提交
131 132
func (self *StateTransition) preCheck() (err error) {
	var (
133 134
		msg    = self.msg
		sender = self.From()
O
obscuren 已提交
135 136 137
	)

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

	// Pre-pay gas / Buy gas of the coinbase account
	if err = self.BuyGas(); err != nil {
		return err
	}

	return nil
}

O
obscuren 已提交
150
func (self *StateTransition) TransitionState() (ret []byte, err error) {
151
	statelogger.Debugf("(~) %x\n", self.msg.Hash())
152

O
obscuren 已提交
153 154 155 156 157
	// XXX Transactions after this point are considered valid.
	if err = self.preCheck(); err != nil {
		return
	}

158
	var (
159 160
		msg    = self.msg
		sender = self.From()
161 162
	)

O
obscuren 已提交
163 164
	defer self.RefundGas()

O
obscuren 已提交
165 166 167
	// Increment the nonce for the next transaction
	sender.Nonce += 1

O
obscuren 已提交
168
	// Transaction gas
O
obscuren 已提交
169
	if err = self.UseGas(vm.GasTx); err != nil {
O
obscuren 已提交
170
		return
171 172
	}

O
obscuren 已提交
173
	// Pay data gas
O
obscuren 已提交
174 175 176 177 178 179 180 181 182
	var dgas int64
	for _, byt := range self.data {
		if byt != 0 {
			dgas += vm.GasData.Int64()
		} else {
			dgas += 1 // This is 1/5. If GasData changes this fails
		}
	}
	if err = self.UseGas(big.NewInt(dgas)); err != nil {
O
obscuren 已提交
183
		return
184 185
	}

186
	vmenv := self.VmEnv()
O
obscuren 已提交
187
	var ref vm.ContextRef
O
obscuren 已提交
188
	if MessageCreatesContract(msg) {
189 190
		contract := MakeContract(msg, self.state)
		ret, err, ref = vmenv.Create(sender, contract.Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
191 192 193 194
		if err == nil {
			dataGas := big.NewInt(int64(len(ret)))
			dataGas.Mul(dataGas, vm.GasCreateByte)
			if err = self.UseGas(dataGas); err == nil {
195
				//self.state.SetCode(ref.Address(), ret)
196 197 198
				ref.SetCode(ret)
			}
		}
O
obscuren 已提交
199
	} else {
200
		ret, err = vmenv.Call(self.From(), self.To().Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
O
obscuren 已提交
201
	}
202

O
obscuren 已提交
203
	if err != nil {
204
		self.UseGas(self.gas)
205 206 207 208
	}

	return
}
O
obscuren 已提交
209 210

// Converts an transaction in to a state object
211 212
func MakeContract(msg Message, state *state.StateDB) *state.StateObject {
	addr := AddressFromMessage(msg)
O
obscuren 已提交
213

O
obscuren 已提交
214
	contract := state.GetOrNewStateObject(addr)
215
	contract.InitCode = msg.Data()
O
obscuren 已提交
216

O
obscuren 已提交
217
	return contract
O
obscuren 已提交
218
}
O
obscuren 已提交
219 220

func (self *StateTransition) RefundGas() {
221 222 223 224 225
	coinbase, sender := self.Coinbase(), self.From()
	// Return remaining gas
	remaining := new(big.Int).Mul(self.gas, self.msg.GasPrice())
	sender.AddAmount(remaining)

O
obscuren 已提交
226
	uhalf := new(big.Int).Div(self.GasUsed(), ethutil.Big2)
O
obscuren 已提交
227 228
	for addr, ref := range self.state.Refunds() {
		refund := ethutil.BigMin(uhalf, ref)
229
		self.gas.Add(self.gas, refund)
O
obscuren 已提交
230
		self.state.AddBalance([]byte(addr), refund.Mul(refund, self.msg.GasPrice()))
O
obscuren 已提交
231 232
	}

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

func (self *StateTransition) GasUsed() *big.Int {
	return new(big.Int).Sub(self.initialGas, self.gas)
}