state_object.go 8.7 KB

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