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