state_object.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package state
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. "github.com/ethereum/go-ethereum/common"
  7. "github.com/ethereum/go-ethereum/crypto"
  8. "github.com/ethereum/go-ethereum/logger"
  9. "github.com/ethereum/go-ethereum/logger/glog"
  10. "github.com/ethereum/go-ethereum/rlp"
  11. "github.com/ethereum/go-ethereum/trie"
  12. )
  13. type Code []byte
  14. func (self Code) String() string {
  15. return string(self) //strings.Join(Disassemble(self), " ")
  16. }
  17. type Storage map[string]common.Hash
  18. func (self Storage) String() (str string) {
  19. for key, value := range self {
  20. str += fmt.Sprintf("%X : %X\n", key, value)
  21. }
  22. return
  23. }
  24. func (self Storage) Copy() Storage {
  25. cpy := make(Storage)
  26. for key, value := range self {
  27. cpy[key] = value
  28. }
  29. return cpy
  30. }
  31. type StateObject struct {
  32. // State database for storing state changes
  33. db common.Database
  34. trie *trie.SecureTrie
  35. // Address belonging to this account
  36. address common.Address
  37. // The balance of the account
  38. balance *big.Int
  39. // The nonce of the account
  40. nonce uint64
  41. // The code hash if code is present (i.e. a contract)
  42. codeHash []byte
  43. // The code for this account
  44. code Code
  45. // Temporarily initialisation code
  46. initCode Code
  47. // Cached storage (flushed when updated)
  48. storage Storage
  49. // Temporary prepaid gas, reward after transition
  50. prepaid *big.Int
  51. // Total gas pool is the total amount of gas currently
  52. // left if this object is the coinbase. Gas is directly
  53. // purchased of the coinbase.
  54. gasPool *big.Int
  55. // Mark for deletion
  56. // When an object is marked for deletion it will be delete from the trie
  57. // during the "update" phase of the state transition
  58. remove bool
  59. dirty bool
  60. }
  61. func (self *StateObject) Reset() {
  62. self.storage = make(Storage)
  63. }
  64. func NewStateObject(address common.Address, db common.Database) *StateObject {
  65. // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter.
  66. //address := common.ToAddress(addr)
  67. object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int), dirty: true}
  68. object.trie = trie.NewSecure((common.Hash{}).Bytes(), db)
  69. object.storage = make(Storage)
  70. object.gasPool = new(big.Int)
  71. object.prepaid = new(big.Int)
  72. return object
  73. }
  74. func NewStateObjectFromBytes(address common.Address, data []byte, db common.Database) *StateObject {
  75. // TODO clean me up
  76. var extobject struct {
  77. Nonce uint64
  78. Balance *big.Int
  79. Root common.Hash
  80. CodeHash []byte
  81. }
  82. err := rlp.Decode(bytes.NewReader(data), &extobject)
  83. if err != nil {
  84. fmt.Println(err)
  85. return nil
  86. }
  87. object := &StateObject{address: address, db: db}
  88. object.nonce = extobject.Nonce
  89. object.balance = extobject.Balance
  90. object.codeHash = extobject.CodeHash
  91. object.trie = trie.NewSecure(extobject.Root[:], db)
  92. object.storage = make(map[string]common.Hash)
  93. object.gasPool = new(big.Int)
  94. object.prepaid = new(big.Int)
  95. object.code, _ = db.Get(extobject.CodeHash)
  96. return object
  97. }
  98. func (self *StateObject) MarkForDeletion() {
  99. self.remove = true
  100. self.dirty = true
  101. if glog.V(logger.Core) {
  102. glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
  103. }
  104. }
  105. func (c *StateObject) getAddr(addr common.Hash) common.Hash {
  106. var ret []byte
  107. rlp.DecodeBytes(c.trie.Get(addr[:]), &ret)
  108. return common.BytesToHash(ret)
  109. }
  110. func (c *StateObject) setAddr(addr []byte, value common.Hash) {
  111. v, err := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  112. if err != nil {
  113. // if RLPing failed we better panic and not fail silently. This would be considered a consensus issue
  114. panic(err)
  115. }
  116. c.trie.Update(addr, v)
  117. }
  118. func (self *StateObject) Storage() Storage {
  119. return self.storage
  120. }
  121. func (self *StateObject) GetState(key common.Hash) common.Hash {
  122. strkey := key.Str()
  123. value, exists := self.storage[strkey]
  124. if !exists {
  125. value = self.getAddr(key)
  126. if (value != common.Hash{}) {
  127. self.storage[strkey] = value
  128. }
  129. }
  130. return value
  131. }
  132. func (self *StateObject) SetState(k, value common.Hash) {
  133. self.storage[k.Str()] = value
  134. self.dirty = true
  135. }
  136. // Update updates the current cached storage to the trie
  137. func (self *StateObject) Update() {
  138. for key, value := range self.storage {
  139. if (value == common.Hash{}) {
  140. self.trie.Delete([]byte(key))
  141. continue
  142. }
  143. self.setAddr([]byte(key), value)
  144. }
  145. self.storage = make(Storage)
  146. }
  147. func (c *StateObject) GetInstr(pc *big.Int) *common.Value {
  148. if int64(len(c.code)-1) < pc.Int64() {
  149. return common.NewValue(0)
  150. }
  151. return common.NewValueFromBytes([]byte{c.code[pc.Int64()]})
  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. return stateObject
  209. }
  210. func (self *StateObject) Set(stateObject *StateObject) {
  211. *self = *stateObject
  212. }
  213. //
  214. // Attribute accessors
  215. //
  216. func (self *StateObject) Balance() *big.Int {
  217. return self.balance
  218. }
  219. func (c *StateObject) N() *big.Int {
  220. return big.NewInt(int64(c.nonce))
  221. }
  222. // Returns the address of the contract/account
  223. func (c *StateObject) Address() common.Address {
  224. return c.address
  225. }
  226. // Returns the initialization Code
  227. func (c *StateObject) Init() Code {
  228. return c.initCode
  229. }
  230. func (self *StateObject) Trie() *trie.SecureTrie {
  231. return self.trie
  232. }
  233. func (self *StateObject) Root() []byte {
  234. return self.trie.Root()
  235. }
  236. func (self *StateObject) Code() []byte {
  237. return self.code
  238. }
  239. func (self *StateObject) SetCode(code []byte) {
  240. self.code = code
  241. self.dirty = true
  242. }
  243. func (self *StateObject) SetInitCode(code []byte) {
  244. self.initCode = code
  245. self.dirty = true
  246. }
  247. func (self *StateObject) SetNonce(nonce uint64) {
  248. self.nonce = nonce
  249. self.dirty = true
  250. }
  251. func (self *StateObject) Nonce() uint64 {
  252. return self.nonce
  253. }
  254. func (self *StateObject) EachStorage(cb func(key, value []byte)) {
  255. // When iterating over the storage check the cache first
  256. for h, v := range self.storage {
  257. cb([]byte(h), v.Bytes())
  258. }
  259. it := self.trie.Iterator()
  260. for it.Next() {
  261. // ignore cached values
  262. key := self.trie.GetKey(it.Key)
  263. if _, ok := self.storage[string(key)]; !ok {
  264. cb(key, it.Value)
  265. }
  266. }
  267. }
  268. //
  269. // Encoding
  270. //
  271. // State object encoding methods
  272. func (c *StateObject) RlpEncode() []byte {
  273. return common.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()})
  274. }
  275. func (c *StateObject) CodeHash() common.Bytes {
  276. return crypto.Sha3(c.code)
  277. }
  278. func (c *StateObject) RlpDecode(data []byte) {
  279. decoder := common.NewValueFromBytes(data)
  280. c.nonce = decoder.Get(0).Uint()
  281. c.balance = decoder.Get(1).BigInt()
  282. c.trie = trie.NewSecure(decoder.Get(2).Bytes(), c.db)
  283. c.storage = make(map[string]common.Hash)
  284. c.gasPool = new(big.Int)
  285. c.codeHash = decoder.Get(3).Bytes()
  286. c.code, _ = c.db.Get(c.codeHash)
  287. }
  288. // Storage change object. Used by the manifest for notifying changes to
  289. // the sub channels.
  290. type StorageState struct {
  291. StateAddress []byte
  292. Address []byte
  293. Value *big.Int
  294. }