state_object.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 (self *StateObject) Reset() {
  76. self.storage = make(Storage)
  77. }
  78. func NewStateObject(address common.Address, db common.Database) *StateObject {
  79. object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int), dirty: true}
  80. object.trie = trie.NewSecure((common.Hash{}).Bytes(), db)
  81. object.storage = make(Storage)
  82. object.gasPool = new(big.Int)
  83. return object
  84. }
  85. func NewStateObjectFromBytes(address common.Address, data []byte, db common.Database) *StateObject {
  86. // TODO clean me up
  87. var extobject struct {
  88. Nonce uint64
  89. Balance *big.Int
  90. Root common.Hash
  91. CodeHash []byte
  92. }
  93. err := rlp.Decode(bytes.NewReader(data), &extobject)
  94. if err != nil {
  95. fmt.Println(err)
  96. return nil
  97. }
  98. object := &StateObject{address: address, db: db}
  99. object.nonce = extobject.Nonce
  100. object.balance = extobject.Balance
  101. object.codeHash = extobject.CodeHash
  102. object.trie = trie.NewSecure(extobject.Root[:], db)
  103. object.storage = make(map[string]common.Hash)
  104. object.gasPool = new(big.Int)
  105. object.code, _ = db.Get(extobject.CodeHash)
  106. return object
  107. }
  108. func (self *StateObject) MarkForDeletion() {
  109. self.remove = true
  110. self.dirty = true
  111. if glog.V(logger.Core) {
  112. glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
  113. }
  114. }
  115. func (c *StateObject) getAddr(addr common.Hash) common.Hash {
  116. var ret []byte
  117. rlp.DecodeBytes(c.trie.Get(addr[:]), &ret)
  118. return common.BytesToHash(ret)
  119. }
  120. func (c *StateObject) setAddr(addr []byte, value common.Hash) {
  121. v, err := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  122. if err != nil {
  123. // if RLPing failed we better panic and not fail silently. This would be considered a consensus issue
  124. panic(err)
  125. }
  126. c.trie.Update(addr, v)
  127. }
  128. func (self *StateObject) Storage() Storage {
  129. return self.storage
  130. }
  131. func (self *StateObject) GetState(key common.Hash) common.Hash {
  132. strkey := key.Str()
  133. value, exists := self.storage[strkey]
  134. if !exists {
  135. value = self.getAddr(key)
  136. if (value != common.Hash{}) {
  137. self.storage[strkey] = value
  138. }
  139. }
  140. return value
  141. }
  142. func (self *StateObject) SetState(k, value common.Hash) {
  143. self.storage[k.Str()] = value
  144. self.dirty = true
  145. }
  146. // Update updates the current cached storage to the trie
  147. func (self *StateObject) Update() {
  148. for key, value := range self.storage {
  149. if (value == common.Hash{}) {
  150. self.trie.Delete([]byte(key))
  151. continue
  152. }
  153. self.setAddr([]byte(key), value)
  154. }
  155. }
  156. func (c *StateObject) GetInstr(pc *big.Int) *common.Value {
  157. if int64(len(c.code)-1) < pc.Int64() {
  158. return common.NewValue(0)
  159. }
  160. return common.NewValueFromBytes([]byte{c.code[pc.Int64()]})
  161. }
  162. func (c *StateObject) AddBalance(amount *big.Int) {
  163. c.SetBalance(new(big.Int).Add(c.balance, amount))
  164. if glog.V(logger.Core) {
  165. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
  166. }
  167. }
  168. func (c *StateObject) SubBalance(amount *big.Int) {
  169. c.SetBalance(new(big.Int).Sub(c.balance, amount))
  170. if glog.V(logger.Core) {
  171. glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
  172. }
  173. }
  174. func (c *StateObject) SetBalance(amount *big.Int) {
  175. c.balance = amount
  176. c.dirty = true
  177. }
  178. func (c *StateObject) St() Storage {
  179. return c.storage
  180. }
  181. //
  182. // Gas setters and getters
  183. //
  184. // Return the gas back to the origin. Used by the Virtual machine or Closures
  185. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  186. func (self *StateObject) SetGasLimit(gasLimit *big.Int) {
  187. self.gasPool = new(big.Int).Set(gasLimit)
  188. if glog.V(logger.Core) {
  189. glog.Infof("%x: gas (+ %v)", self.Address(), self.gasPool)
  190. }
  191. }
  192. func (self *StateObject) SubGas(gas, price *big.Int) error {
  193. if self.gasPool.Cmp(gas) < 0 {
  194. return GasLimitError(self.gasPool, gas)
  195. }
  196. self.gasPool.Sub(self.gasPool, gas)
  197. rGas := new(big.Int).Set(gas)
  198. rGas.Mul(rGas, price)
  199. self.dirty = true
  200. return nil
  201. }
  202. func (self *StateObject) AddGas(gas, price *big.Int) {
  203. self.gasPool.Add(self.gasPool, gas)
  204. }
  205. func (self *StateObject) Copy() *StateObject {
  206. stateObject := NewStateObject(self.Address(), self.db)
  207. stateObject.balance.Set(self.balance)
  208. stateObject.codeHash = common.CopyBytes(self.codeHash)
  209. stateObject.nonce = self.nonce
  210. stateObject.trie = self.trie
  211. stateObject.code = common.CopyBytes(self.code)
  212. stateObject.initCode = common.CopyBytes(self.initCode)
  213. stateObject.storage = self.storage.Copy()
  214. stateObject.gasPool.Set(self.gasPool)
  215. stateObject.remove = self.remove
  216. stateObject.dirty = self.dirty
  217. return stateObject
  218. }
  219. func (self *StateObject) Set(stateObject *StateObject) {
  220. *self = *stateObject
  221. }
  222. //
  223. // Attribute accessors
  224. //
  225. func (self *StateObject) Balance() *big.Int {
  226. return self.balance
  227. }
  228. func (c *StateObject) N() *big.Int {
  229. return big.NewInt(int64(c.nonce))
  230. }
  231. // Returns the address of the contract/account
  232. func (c *StateObject) Address() common.Address {
  233. return c.address
  234. }
  235. // Returns the initialization Code
  236. func (c *StateObject) Init() Code {
  237. return c.initCode
  238. }
  239. func (self *StateObject) Trie() *trie.SecureTrie {
  240. return self.trie
  241. }
  242. func (self *StateObject) Root() []byte {
  243. return self.trie.Root()
  244. }
  245. func (self *StateObject) Code() []byte {
  246. return self.code
  247. }
  248. func (self *StateObject) SetCode(code []byte) {
  249. self.code = code
  250. self.dirty = true
  251. }
  252. func (self *StateObject) SetInitCode(code []byte) {
  253. self.initCode = code
  254. self.dirty = true
  255. }
  256. func (self *StateObject) SetNonce(nonce uint64) {
  257. self.nonce = nonce
  258. self.dirty = true
  259. }
  260. func (self *StateObject) Nonce() uint64 {
  261. return self.nonce
  262. }
  263. func (self *StateObject) EachStorage(cb func(key, value []byte)) {
  264. // When iterating over the storage check the cache first
  265. for h, v := range self.storage {
  266. cb([]byte(h), v.Bytes())
  267. }
  268. it := self.trie.Iterator()
  269. for it.Next() {
  270. // ignore cached values
  271. key := self.trie.GetKey(it.Key)
  272. if _, ok := self.storage[string(key)]; !ok {
  273. cb(key, it.Value)
  274. }
  275. }
  276. }
  277. //
  278. // Encoding
  279. //
  280. // State object encoding methods
  281. func (c *StateObject) RlpEncode() []byte {
  282. return common.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()})
  283. }
  284. func (c *StateObject) CodeHash() common.Bytes {
  285. return crypto.Sha3(c.code)
  286. }
  287. func (c *StateObject) RlpDecode(data []byte) {
  288. decoder := common.NewValueFromBytes(data)
  289. c.nonce = decoder.Get(0).Uint()
  290. c.balance = decoder.Get(1).BigInt()
  291. c.trie = trie.NewSecure(decoder.Get(2).Bytes(), c.db)
  292. c.storage = make(map[string]common.Hash)
  293. c.gasPool = new(big.Int)
  294. c.codeHash = decoder.Get(3).Bytes()
  295. c.code, _ = c.db.Get(c.codeHash)
  296. }
  297. // Storage change object. Used by the manifest for notifying changes to
  298. // the sub channels.
  299. type StorageState struct {
  300. StateAddress []byte
  301. Address []byte
  302. Value *big.Int
  303. }