state_object.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  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. // GNU Lesser General Public License for more details.
  13. //
  14. // 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. package state
  17. import (
  18. "bytes"
  19. "fmt"
  20. "math/big"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/ethdb"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "github.com/ethereum/go-ethereum/trie"
  28. )
  29. type Code []byte
  30. func (self Code) String() string {
  31. return string(self) //strings.Join(Disassemble(self), " ")
  32. }
  33. type Storage map[string]common.Hash
  34. func (self Storage) String() (str string) {
  35. for key, value := range self {
  36. str += fmt.Sprintf("%X : %X\n", key, value)
  37. }
  38. return
  39. }
  40. func (self Storage) Copy() Storage {
  41. cpy := make(Storage)
  42. for key, value := range self {
  43. cpy[key] = value
  44. }
  45. return cpy
  46. }
  47. type StateObject struct {
  48. // State database for storing state changes
  49. db ethdb.Database
  50. trie *trie.SecureTrie
  51. // Address belonging to this account
  52. address common.Address
  53. // The balance of the account
  54. balance *big.Int
  55. // The nonce of the account
  56. nonce uint64
  57. // The code hash if code is present (i.e. a contract)
  58. codeHash []byte
  59. // The code for this account
  60. code Code
  61. // Temporarily initialisation code
  62. initCode Code
  63. // Cached storage (flushed when updated)
  64. storage Storage
  65. // Total gas pool is the total amount of gas currently
  66. // left if this object is the coinbase. Gas is directly
  67. // purchased of the coinbase.
  68. gasPool *big.Int
  69. // Mark for deletion
  70. // When an object is marked for deletion it will be delete from the trie
  71. // during the "update" phase of the state transition
  72. remove bool
  73. deleted bool
  74. dirty bool
  75. }
  76. func NewStateObject(address common.Address, db ethdb.Database) *StateObject {
  77. object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int), dirty: true}
  78. object.trie, _ = trie.NewSecure(common.Hash{}, db)
  79. object.storage = make(Storage)
  80. object.gasPool = new(big.Int)
  81. return object
  82. }
  83. func NewStateObjectFromBytes(address common.Address, data []byte, db ethdb.Database) *StateObject {
  84. var extobject struct {
  85. Nonce uint64
  86. Balance *big.Int
  87. Root common.Hash
  88. CodeHash []byte
  89. }
  90. err := rlp.Decode(bytes.NewReader(data), &extobject)
  91. if err != nil {
  92. glog.Errorf("can't decode state object %x: %v", address, err)
  93. return nil
  94. }
  95. trie, err := trie.NewSecure(extobject.Root, db)
  96. if err != nil {
  97. // TODO: bubble this up or panic
  98. glog.Errorf("can't create account trie with root %x: %v", extobject.Root[:], err)
  99. return nil
  100. }
  101. object := &StateObject{address: address, db: db}
  102. object.nonce = extobject.Nonce
  103. object.balance = extobject.Balance
  104. object.codeHash = extobject.CodeHash
  105. object.trie = trie
  106. object.storage = make(map[string]common.Hash)
  107. object.gasPool = new(big.Int)
  108. object.code, _ = db.Get(extobject.CodeHash)
  109. return object
  110. }
  111. func (self *StateObject) MarkForDeletion() {
  112. self.remove = true
  113. self.dirty = true
  114. if glog.V(logger.Core) {
  115. glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
  116. }
  117. }
  118. func (c *StateObject) getAddr(addr common.Hash) common.Hash {
  119. var ret []byte
  120. rlp.DecodeBytes(c.trie.Get(addr[:]), &ret)
  121. return common.BytesToHash(ret)
  122. }
  123. func (c *StateObject) setAddr(addr []byte, value common.Hash) {
  124. v, err := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  125. if err != nil {
  126. // if RLPing failed we better panic and not fail silently. This would be considered a consensus issue
  127. panic(err)
  128. }
  129. c.trie.Update(addr, v)
  130. }
  131. func (self *StateObject) Storage() Storage {
  132. return self.storage
  133. }
  134. func (self *StateObject) GetState(key common.Hash) common.Hash {
  135. strkey := key.Str()
  136. value, exists := self.storage[strkey]
  137. if !exists {
  138. value = self.getAddr(key)
  139. if (value != common.Hash{}) {
  140. self.storage[strkey] = value
  141. }
  142. }
  143. return value
  144. }
  145. func (self *StateObject) SetState(k, value common.Hash) {
  146. self.storage[k.Str()] = value
  147. self.dirty = true
  148. }
  149. // Update updates the current cached storage to the trie
  150. func (self *StateObject) Update() {
  151. for key, value := range self.storage {
  152. if (value == common.Hash{}) {
  153. self.trie.Delete([]byte(key))
  154. continue
  155. }
  156. self.setAddr([]byte(key), value)
  157. }
  158. }
  159. func (c *StateObject) AddBalance(amount *big.Int) {
  160. c.SetBalance(new(big.Int).Add(c.balance, amount))
  161. if glog.V(logger.Core) {
  162. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
  163. }
  164. }
  165. func (c *StateObject) SubBalance(amount *big.Int) {
  166. c.SetBalance(new(big.Int).Sub(c.balance, amount))
  167. if glog.V(logger.Core) {
  168. glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
  169. }
  170. }
  171. func (c *StateObject) SetBalance(amount *big.Int) {
  172. c.balance = amount
  173. c.dirty = true
  174. }
  175. func (c *StateObject) St() Storage {
  176. return c.storage
  177. }
  178. //
  179. // Gas setters and getters
  180. //
  181. // Return the gas back to the origin. Used by the Virtual machine or Closures
  182. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  183. func (self *StateObject) SetGasLimit(gasLimit *big.Int) {
  184. self.gasPool = new(big.Int).Set(gasLimit)
  185. self.dirty = true
  186. if glog.V(logger.Core) {
  187. glog.Infof("%x: gas (+ %v)", self.Address(), self.gasPool)
  188. }
  189. }
  190. func (self *StateObject) SubGas(gas, price *big.Int) error {
  191. if self.gasPool.Cmp(gas) < 0 {
  192. return GasLimitError(self.gasPool, gas)
  193. }
  194. self.gasPool.Sub(self.gasPool, gas)
  195. self.dirty = true
  196. return nil
  197. }
  198. func (self *StateObject) AddGas(gas, price *big.Int) {
  199. self.gasPool.Add(self.gasPool, gas)
  200. self.dirty = true
  201. }
  202. func (self *StateObject) Copy() *StateObject {
  203. stateObject := NewStateObject(self.Address(), self.db)
  204. stateObject.balance.Set(self.balance)
  205. stateObject.codeHash = common.CopyBytes(self.codeHash)
  206. stateObject.nonce = self.nonce
  207. stateObject.trie = self.trie
  208. stateObject.code = common.CopyBytes(self.code)
  209. stateObject.initCode = common.CopyBytes(self.initCode)
  210. stateObject.storage = self.storage.Copy()
  211. stateObject.gasPool.Set(self.gasPool)
  212. stateObject.remove = self.remove
  213. stateObject.dirty = self.dirty
  214. stateObject.deleted = self.deleted
  215. return stateObject
  216. }
  217. //
  218. // Attribute accessors
  219. //
  220. func (self *StateObject) Balance() *big.Int {
  221. return self.balance
  222. }
  223. // Returns the address of the contract/account
  224. func (c *StateObject) Address() common.Address {
  225. return c.address
  226. }
  227. func (self *StateObject) Trie() *trie.SecureTrie {
  228. return self.trie
  229. }
  230. func (self *StateObject) Root() []byte {
  231. return self.trie.Root()
  232. }
  233. func (self *StateObject) Code() []byte {
  234. return self.code
  235. }
  236. func (self *StateObject) SetCode(code []byte) {
  237. self.code = code
  238. self.dirty = true
  239. }
  240. func (self *StateObject) SetNonce(nonce uint64) {
  241. self.nonce = nonce
  242. self.dirty = true
  243. }
  244. func (self *StateObject) Nonce() uint64 {
  245. return self.nonce
  246. }
  247. func (self *StateObject) EachStorage(cb func(key, value []byte)) {
  248. // When iterating over the storage check the cache first
  249. for h, v := range self.storage {
  250. cb([]byte(h), v.Bytes())
  251. }
  252. it := self.trie.Iterator()
  253. for it.Next() {
  254. // ignore cached values
  255. key := self.trie.GetKey(it.Key)
  256. if _, ok := self.storage[string(key)]; !ok {
  257. cb(key, it.Value)
  258. }
  259. }
  260. }
  261. //
  262. // Encoding
  263. //
  264. // State object encoding methods
  265. func (c *StateObject) RlpEncode() []byte {
  266. return common.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()})
  267. }
  268. func (c *StateObject) CodeHash() common.Bytes {
  269. return crypto.Sha3(c.code)
  270. }
  271. // Storage change object. Used by the manifest for notifying changes to
  272. // the sub channels.
  273. type StorageState struct {
  274. StateAddress []byte
  275. Address []byte
  276. Value *big.Int
  277. }