state_object.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package state
  2. import (
  3. "fmt"
  4. "math/big"
  5. "github.com/ethereum/go-ethereum/crypto"
  6. "github.com/ethereum/go-ethereum/ethutil"
  7. "github.com/ethereum/go-ethereum/trie"
  8. )
  9. type Code []byte
  10. func (self Code) String() string {
  11. return string(self) //strings.Join(Disassemble(self), " ")
  12. }
  13. type Storage map[string]*ethutil.Value
  14. func (self Storage) Copy() Storage {
  15. cpy := make(Storage)
  16. for key, value := range self {
  17. // XXX Do we need a 'value' copy or is this sufficient?
  18. cpy[key] = value
  19. }
  20. return cpy
  21. }
  22. type StateObject struct {
  23. // Address of the object
  24. address []byte
  25. // Shared attributes
  26. balance *big.Int
  27. codeHash []byte
  28. Nonce uint64
  29. // Contract related attributes
  30. State *State
  31. Code Code
  32. InitCode Code
  33. storage Storage
  34. // Total gas pool is the total amount of gas currently
  35. // left if this object is the coinbase. Gas is directly
  36. // purchased of the coinbase.
  37. gasPool *big.Int
  38. // Mark for deletion
  39. // When an object is marked for deletion it will be delete from the trie
  40. // during the "update" phase of the state transition
  41. remove bool
  42. }
  43. func (self *StateObject) Reset() {
  44. self.storage = make(Storage)
  45. self.State.Reset()
  46. }
  47. func NewStateObject(addr []byte) *StateObject {
  48. // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter.
  49. address := ethutil.Address(addr)
  50. object := &StateObject{address: address, balance: new(big.Int), gasPool: new(big.Int)}
  51. object.State = New(trie.New(ethutil.Config.Db, ""))
  52. object.storage = make(Storage)
  53. object.gasPool = new(big.Int)
  54. return object
  55. }
  56. func NewContract(address []byte, balance *big.Int, root []byte) *StateObject {
  57. contract := NewStateObject(address)
  58. contract.balance = balance
  59. contract.State = New(trie.New(ethutil.Config.Db, string(root)))
  60. return contract
  61. }
  62. func NewStateObjectFromBytes(address, data []byte) *StateObject {
  63. object := &StateObject{address: address}
  64. object.RlpDecode(data)
  65. return object
  66. }
  67. func (self *StateObject) MarkForDeletion() {
  68. self.remove = true
  69. statelogger.DebugDetailf("%x: #%d %v (deletion)\n", self.Address(), self.Nonce, self.balance)
  70. }
  71. func (c *StateObject) GetAddr(addr []byte) *ethutil.Value {
  72. return ethutil.NewValueFromBytes([]byte(c.State.Trie.Get(string(addr))))
  73. }
  74. func (c *StateObject) SetAddr(addr []byte, value interface{}) {
  75. c.State.Trie.Update(string(addr), string(ethutil.NewValue(value).Encode()))
  76. }
  77. func (self *StateObject) GetStorage(key *big.Int) *ethutil.Value {
  78. return self.GetState(key.Bytes())
  79. }
  80. func (self *StateObject) SetStorage(key *big.Int, value *ethutil.Value) {
  81. self.SetState(key.Bytes(), value)
  82. }
  83. func (self *StateObject) Storage() map[string]*ethutil.Value {
  84. return self.storage
  85. }
  86. func (self *StateObject) GetState(k []byte) *ethutil.Value {
  87. key := ethutil.LeftPadBytes(k, 32)
  88. value := self.storage[string(key)]
  89. if value == nil {
  90. value = self.GetAddr(key)
  91. if !value.IsNil() {
  92. self.storage[string(key)] = value
  93. }
  94. }
  95. return value
  96. }
  97. func (self *StateObject) SetState(k []byte, value *ethutil.Value) {
  98. key := ethutil.LeftPadBytes(k, 32)
  99. self.storage[string(key)] = value.Copy()
  100. }
  101. // Iterate over each storage address and yield callback
  102. func (self *StateObject) EachStorage(cb trie.EachCallback) {
  103. // First loop over the uncommit/cached values in storage
  104. for key, value := range self.storage {
  105. // XXX Most iterators Fns as it stands require encoded values
  106. encoded := ethutil.NewValue(value.Encode())
  107. cb(key, encoded)
  108. }
  109. it := self.State.Trie.NewIterator()
  110. it.Each(func(key string, value *ethutil.Value) {
  111. // If it's cached don't call the callback.
  112. if self.storage[key] == nil {
  113. cb(key, value)
  114. }
  115. })
  116. }
  117. func (self *StateObject) Sync() {
  118. for key, value := range self.storage {
  119. if value.Len() == 0 { // value.BigInt().Cmp(ethutil.Big0) == 0 {
  120. //data := self.getStorage([]byte(key))
  121. //fmt.Printf("deleting %x %x 0x%x\n", self.Address(), []byte(key), data)
  122. self.State.Trie.Delete(string(key))
  123. continue
  124. }
  125. self.SetAddr([]byte(key), value)
  126. }
  127. valid, t2 := trie.ParanoiaCheck(self.State.Trie)
  128. if !valid {
  129. statelogger.Infof("Warn: PARANOIA: Different state storage root during copy %x vs %x\n", self.State.Root(), t2.GetRoot())
  130. self.State.Trie = t2
  131. }
  132. }
  133. func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value {
  134. if int64(len(c.Code)-1) < pc.Int64() {
  135. return ethutil.NewValue(0)
  136. }
  137. return ethutil.NewValueFromBytes([]byte{c.Code[pc.Int64()]})
  138. }
  139. func (c *StateObject) AddBalance(amount *big.Int) {
  140. c.SetBalance(new(big.Int).Add(c.balance, amount))
  141. statelogger.Debugf("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce, c.balance, amount)
  142. }
  143. func (c *StateObject) AddAmount(amount *big.Int) { c.AddBalance(amount) }
  144. func (c *StateObject) SubBalance(amount *big.Int) {
  145. c.SetBalance(new(big.Int).Sub(c.balance, amount))
  146. statelogger.Debugf("%x: #%d %v (- %v)\n", c.Address(), c.Nonce, c.balance, amount)
  147. }
  148. func (c *StateObject) SubAmount(amount *big.Int) { c.SubBalance(amount) }
  149. func (c *StateObject) SetBalance(amount *big.Int) {
  150. c.balance = amount
  151. }
  152. func (self *StateObject) Balance() *big.Int { return self.balance }
  153. //
  154. // Gas setters and getters
  155. //
  156. // Return the gas back to the origin. Used by the Virtual machine or Closures
  157. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  158. func (c *StateObject) ConvertGas(gas, price *big.Int) error {
  159. total := new(big.Int).Mul(gas, price)
  160. if total.Cmp(c.balance) > 0 {
  161. return fmt.Errorf("insufficient amount: %v, %v", c.balance, total)
  162. }
  163. c.SubAmount(total)
  164. return nil
  165. }
  166. func (self *StateObject) SetGasPool(gasLimit *big.Int) {
  167. self.gasPool = new(big.Int).Set(gasLimit)
  168. statelogger.DebugDetailf("%x: fuel (+ %v)", self.Address(), self.gasPool)
  169. }
  170. func (self *StateObject) BuyGas(gas, price *big.Int) error {
  171. if self.gasPool.Cmp(gas) < 0 {
  172. return GasLimitError(self.gasPool, gas)
  173. }
  174. rGas := new(big.Int).Set(gas)
  175. rGas.Mul(rGas, price)
  176. self.AddAmount(rGas)
  177. return nil
  178. }
  179. func (self *StateObject) RefundGas(gas, price *big.Int) {
  180. self.gasPool.Add(self.gasPool, gas)
  181. rGas := new(big.Int).Set(gas)
  182. rGas.Mul(rGas, price)
  183. self.balance.Sub(self.balance, rGas)
  184. }
  185. func (self *StateObject) Copy() *StateObject {
  186. stateObject := NewStateObject(self.Address())
  187. stateObject.balance.Set(self.balance)
  188. stateObject.codeHash = ethutil.CopyBytes(self.codeHash)
  189. stateObject.Nonce = self.Nonce
  190. if self.State != nil {
  191. stateObject.State = self.State.Copy()
  192. }
  193. stateObject.Code = ethutil.CopyBytes(self.Code)
  194. stateObject.InitCode = ethutil.CopyBytes(self.InitCode)
  195. stateObject.storage = self.storage.Copy()
  196. stateObject.gasPool.Set(self.gasPool)
  197. stateObject.remove = self.remove
  198. return stateObject
  199. }
  200. func (self *StateObject) Set(stateObject *StateObject) {
  201. *self = *stateObject
  202. }
  203. //
  204. // Attribute accessors
  205. //
  206. func (c *StateObject) N() *big.Int {
  207. return big.NewInt(int64(c.Nonce))
  208. }
  209. // Returns the address of the contract/account
  210. func (c *StateObject) Address() []byte {
  211. return c.address
  212. }
  213. // Returns the initialization Code
  214. func (c *StateObject) Init() Code {
  215. return c.InitCode
  216. }
  217. // To satisfy ClosureRef
  218. func (self *StateObject) Object() *StateObject {
  219. return self
  220. }
  221. func (self *StateObject) Root() []byte {
  222. return self.State.Trie.GetRoot()
  223. }
  224. //
  225. // Encoding
  226. //
  227. // State object encoding methods
  228. func (c *StateObject) RlpEncode() []byte {
  229. return ethutil.Encode([]interface{}{c.Nonce, c.balance, c.Root(), c.CodeHash()})
  230. }
  231. func (c *StateObject) CodeHash() ethutil.Bytes {
  232. return crypto.Sha3(c.Code)
  233. }
  234. func (c *StateObject) RlpDecode(data []byte) {
  235. decoder := ethutil.NewValueFromBytes(data)
  236. c.Nonce = decoder.Get(0).Uint()
  237. c.balance = decoder.Get(1).BigInt()
  238. c.State = New(trie.New(ethutil.Config.Db, decoder.Get(2).Interface()))
  239. c.storage = make(map[string]*ethutil.Value)
  240. c.gasPool = new(big.Int)
  241. c.codeHash = decoder.Get(3).Bytes()
  242. c.Code, _ = ethutil.Config.Db.Get(c.codeHash)
  243. }
  244. // Storage change object. Used by the manifest for notifying changes to
  245. // the sub channels.
  246. type StorageState struct {
  247. StateAddress []byte
  248. Address []byte
  249. Value *big.Int
  250. }