state_object.go 7.24 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 state
18 19

import (
20
	"bytes"
21
	"fmt"
22 23
	"math/big"

obscuren's avatar
obscuren committed
24
	"github.com/ethereum/go-ethereum/common"
obscuren's avatar
obscuren committed
25
	"github.com/ethereum/go-ethereum/crypto"
26
	"github.com/ethereum/go-ethereum/ethdb"
obscuren's avatar
obscuren committed
27 28
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
29
	"github.com/ethereum/go-ethereum/rlp"
30
	"github.com/ethereum/go-ethereum/trie"
31 32 33 34 35
)

type Code []byte

func (self Code) String() string {
36
	return string(self) //strings.Join(Disassemble(self), " ")
37 38
}

39
type Storage map[string]common.Hash
40

41 42
func (self Storage) String() (str string) {
	for key, value := range self {
43
		str += fmt.Sprintf("%X : %X\n", key, value)
44 45 46 47 48
	}

	return
}

49 50 51 52 53 54 55 56 57 58
func (self Storage) Copy() Storage {
	cpy := make(Storage)
	for key, value := range self {
		cpy[key] = value
	}

	return cpy
}

type StateObject struct {
59
	// State database for storing state changes
60
	db   ethdb.Database
61
	trie *trie.SecureTrie
62 63

	// Address belonging to this account
obscuren's avatar
obscuren committed
64
	address common.Address
65 66 67 68 69
	// The balance of the account
	balance *big.Int
	// The nonce of the account
	nonce uint64
	// The code hash if code is present (i.e. a contract)
70
	codeHash []byte
71 72 73
	// The code for this account
	code Code
	// Temporarily initialisation code
74
	initCode Code
75
	// Cached storage (flushed when updated)
76 77 78 79 80
	storage Storage

	// Mark for deletion
	// When an object is marked for deletion it will be delete from the trie
	// during the "update" phase of the state transition
81 82 83
	remove  bool
	deleted bool
	dirty   bool
84 85
}

86
func NewStateObject(address common.Address, db ethdb.Database) *StateObject {
87
	object := &StateObject{db: db, address: address, balance: new(big.Int), dirty: true}
Felix Lange's avatar
Felix Lange committed
88
	object.trie, _ = trie.NewSecure(common.Hash{}, db)
89 90 91 92
	object.storage = make(Storage)
	return object
}

93
func NewStateObjectFromBytes(address common.Address, data []byte, db ethdb.Database) *StateObject {
94 95 96
	var extobject struct {
		Nonce    uint64
		Balance  *big.Int
obscuren's avatar
obscuren committed
97
		Root     common.Hash
98 99 100 101
		CodeHash []byte
	}
	err := rlp.Decode(bytes.NewReader(data), &extobject)
	if err != nil {
Felix Lange's avatar
Felix Lange committed
102 103 104 105 106 107 108
		glog.Errorf("can't decode state object %x: %v", address, err)
		return nil
	}
	trie, err := trie.NewSecure(extobject.Root, db)
	if err != nil {
		// TODO: bubble this up or panic
		glog.Errorf("can't create account trie with root %x: %v", extobject.Root[:], err)
109 110 111
		return nil
	}

112
	object := &StateObject{address: address, db: db}
113
	object.nonce = extobject.Nonce
114 115
	object.balance = extobject.Balance
	object.codeHash = extobject.CodeHash
Felix Lange's avatar
Felix Lange committed
116
	object.trie = trie
117
	object.storage = make(map[string]common.Hash)
118
	object.code, _ = db.Get(extobject.CodeHash)
119 120 121 122 123
	return object
}

func (self *StateObject) MarkForDeletion() {
	self.remove = true
124
	self.dirty = true
obscuren's avatar
obscuren committed
125

obscuren's avatar
obscuren committed
126
	if glog.V(logger.Core) {
obscuren's avatar
obscuren committed
127 128
		glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
	}
129 130
}

131 132
func (c *StateObject) getAddr(addr common.Hash) common.Hash {
	var ret []byte
133
	rlp.DecodeBytes(c.trie.Get(addr[:]), &ret)
134
	return common.BytesToHash(ret)
135 136
}

137 138 139 140 141 142
func (c *StateObject) setAddr(addr []byte, value common.Hash) {
	v, err := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
	if err != nil {
		// if RLPing failed we better panic and not fail silently. This would be considered a consensus issue
		panic(err)
	}
143
	c.trie.Update(addr, v)
144 145
}

146
func (self *StateObject) Storage() Storage {
147 148 149
	return self.storage
}

150
func (self *StateObject) GetState(key common.Hash) common.Hash {
obscuren's avatar
obscuren committed
151
	strkey := key.Str()
152 153
	value, exists := self.storage[strkey]
	if !exists {
obscuren's avatar
obscuren committed
154
		value = self.getAddr(key)
155
		if (value != common.Hash{}) {
obscuren's avatar
obscuren committed
156
			self.storage[strkey] = value
157 158 159 160 161 162
		}
	}

	return value
}

163 164
func (self *StateObject) SetState(k, value common.Hash) {
	self.storage[k.Str()] = value
165
	self.dirty = true
166 167
}

168 169
// Update updates the current cached storage to the trie
func (self *StateObject) Update() {
170
	for key, value := range self.storage {
171
		if (value == common.Hash{}) {
172
			self.trie.Delete([]byte(key))
173 174 175
			continue
		}

obscuren's avatar
obscuren committed
176
		self.setAddr([]byte(key), value)
177 178 179
	}
}

180 181
func (c *StateObject) AddBalance(amount *big.Int) {
	c.SetBalance(new(big.Int).Add(c.balance, amount))
182

obscuren's avatar
obscuren committed
183
	if glog.V(logger.Core) {
obscuren's avatar
obscuren committed
184 185
		glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
	}
186 187
}

188 189
func (c *StateObject) SubBalance(amount *big.Int) {
	c.SetBalance(new(big.Int).Sub(c.balance, amount))
190

obscuren's avatar
obscuren committed
191
	if glog.V(logger.Core) {
obscuren's avatar
obscuren committed
192 193
		glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
	}
194 195
}

196
func (c *StateObject) SetBalance(amount *big.Int) {
197
	c.balance = amount
198
	c.dirty = true
199 200
}

201 202 203 204
func (c *StateObject) St() Storage {
	return c.storage
}

205 206 207 208
// Return the gas back to the origin. Used by the Virtual machine or Closures
func (c *StateObject) ReturnGas(gas, price *big.Int) {}

func (self *StateObject) Copy() *StateObject {
209
	stateObject := NewStateObject(self.Address(), self.db)
210
	stateObject.balance.Set(self.balance)
obscuren's avatar
obscuren committed
211
	stateObject.codeHash = common.CopyBytes(self.codeHash)
212
	stateObject.nonce = self.nonce
213
	stateObject.trie = self.trie
obscuren's avatar
obscuren committed
214 215
	stateObject.code = common.CopyBytes(self.code)
	stateObject.initCode = common.CopyBytes(self.initCode)
216
	stateObject.storage = self.storage.Copy()
obscuren's avatar
obscuren committed
217
	stateObject.remove = self.remove
218
	stateObject.dirty = self.dirty
219
	stateObject.deleted = self.deleted
220 221 222 223 224 225 226 227

	return stateObject
}

//
// Attribute accessors
//

228 229 230 231
func (self *StateObject) Balance() *big.Int {
	return self.balance
}

232
// Returns the address of the contract/account
obscuren's avatar
obscuren committed
233
func (c *StateObject) Address() common.Address {
234 235 236
	return c.address
}

obscuren's avatar
obscuren committed
237
func (self *StateObject) Trie() *trie.SecureTrie {
238
	return self.trie
obscuren's avatar
obscuren committed
239 240
}

obscuren's avatar
obscuren committed
241
func (self *StateObject) Root() []byte {
242
	return self.trie.Root()
obscuren's avatar
obscuren committed
243 244
}

245 246 247 248
func (self *StateObject) Code() []byte {
	return self.code
}

249
func (self *StateObject) SetCode(code []byte) {
250 251 252 253 254 255 256 257 258 259 260
	self.code = code
	self.dirty = true
}

func (self *StateObject) SetNonce(nonce uint64) {
	self.nonce = nonce
	self.dirty = true
}

func (self *StateObject) Nonce() uint64 {
	return self.nonce
261 262
}

263 264 265 266 267 268
func (self *StateObject) EachStorage(cb func(key, value []byte)) {
	// When iterating over the storage check the cache first
	for h, v := range self.storage {
		cb([]byte(h), v.Bytes())
	}

269
	it := self.trie.Iterator()
270 271
	for it.Next() {
		// ignore cached values
272
		key := self.trie.GetKey(it.Key)
273 274 275 276 277 278
		if _, ok := self.storage[string(key)]; !ok {
			cb(key, it.Value)
		}
	}
}

279 280 281 282 283 284
//
// Encoding
//

// State object encoding methods
func (c *StateObject) RlpEncode() []byte {
obscuren's avatar
obscuren committed
285
	return common.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()})
286 287
}

obscuren's avatar
obscuren committed
288
func (c *StateObject) CodeHash() common.Bytes {
289
	return crypto.Sha3(c.code)
290 291 292 293 294 295 296 297 298
}

// Storage change object. Used by the manifest for notifying changes to
// the sub channels.
type StorageState struct {
	StateAddress []byte
	Address      []byte
	Value        *big.Int
}