state_object.go 7.6 KB

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