state_object.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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/rlp"
  9. "github.com/ethereum/go-ethereum/trie"
  10. )
  11. type Code []byte
  12. func (self Code) String() string {
  13. return string(self) //strings.Join(Disassemble(self), " ")
  14. }
  15. type Storage map[string]*common.Value
  16. func (self Storage) String() (str string) {
  17. for key, value := range self {
  18. str += fmt.Sprintf("%X : %X\n", key, value.Bytes())
  19. }
  20. return
  21. }
  22. func (self Storage) Copy() Storage {
  23. cpy := make(Storage)
  24. for key, value := range self {
  25. // XXX Do we need a 'value' copy or is this sufficient?
  26. cpy[key] = value
  27. }
  28. return cpy
  29. }
  30. type StateObject struct {
  31. // State database for storing state changes
  32. db common.Database
  33. // The state object
  34. State *StateDB
  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. self.State.Reset()
  64. }
  65. func NewStateObject(address common.Address, db common.Database) *StateObject {
  66. // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter.
  67. //address := common.ToAddress(addr)
  68. object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int), dirty: true}
  69. object.State = New(common.Hash{}, db) //New(trie.New(common.Config.Db, ""))
  70. object.storage = make(Storage)
  71. object.gasPool = new(big.Int)
  72. object.prepaid = new(big.Int)
  73. return object
  74. }
  75. func NewStateObjectFromBytes(address common.Address, data []byte, db common.Database) *StateObject {
  76. // TODO clean me up
  77. var extobject struct {
  78. Nonce uint64
  79. Balance *big.Int
  80. Root common.Hash
  81. CodeHash []byte
  82. }
  83. err := rlp.Decode(bytes.NewReader(data), &extobject)
  84. if err != nil {
  85. fmt.Println(err)
  86. return nil
  87. }
  88. object := &StateObject{address: address, db: db}
  89. //object.RlpDecode(data)
  90. object.nonce = extobject.Nonce
  91. object.balance = extobject.Balance
  92. object.codeHash = extobject.CodeHash
  93. object.State = New(extobject.Root, db)
  94. object.storage = make(map[string]*common.Value)
  95. object.gasPool = new(big.Int)
  96. object.prepaid = new(big.Int)
  97. object.code, _ = db.Get(extobject.CodeHash)
  98. return object
  99. }
  100. func (self *StateObject) MarkForDeletion() {
  101. self.remove = true
  102. self.dirty = true
  103. statelogger.Debugf("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
  104. }
  105. func (c *StateObject) getAddr(addr common.Hash) *common.Value {
  106. return common.NewValueFromBytes([]byte(c.State.trie.Get(addr[:])))
  107. }
  108. func (c *StateObject) setAddr(addr []byte, value interface{}) {
  109. c.State.trie.Update(addr, common.Encode(value))
  110. }
  111. func (self *StateObject) GetStorage(key *big.Int) *common.Value {
  112. return self.GetState(common.BytesToHash(key.Bytes()))
  113. }
  114. func (self *StateObject) SetStorage(key *big.Int, value *common.Value) {
  115. self.SetState(common.BytesToHash(key.Bytes()), value)
  116. }
  117. func (self *StateObject) Storage() Storage {
  118. return self.storage
  119. }
  120. func (self *StateObject) GetState(key common.Hash) *common.Value {
  121. strkey := key.Str()
  122. value := self.storage[strkey]
  123. if value == nil {
  124. value = self.getAddr(key)
  125. if !value.IsNil() {
  126. self.storage[strkey] = value
  127. }
  128. }
  129. return value
  130. }
  131. func (self *StateObject) SetState(k common.Hash, value *common.Value) {
  132. self.storage[k.Str()] = value.Copy()
  133. self.dirty = true
  134. }
  135. func (self *StateObject) Sync() {
  136. for key, value := range self.storage {
  137. if value.Len() == 0 {
  138. self.State.trie.Delete([]byte(key))
  139. continue
  140. }
  141. self.setAddr([]byte(key), value)
  142. }
  143. self.storage = make(Storage)
  144. }
  145. func (c *StateObject) GetInstr(pc *big.Int) *common.Value {
  146. if int64(len(c.code)-1) < pc.Int64() {
  147. return common.NewValue(0)
  148. }
  149. return common.NewValueFromBytes([]byte{c.code[pc.Int64()]})
  150. }
  151. func (c *StateObject) AddBalance(amount *big.Int) {
  152. c.SetBalance(new(big.Int).Add(c.balance, amount))
  153. statelogger.Debugf("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
  154. }
  155. func (c *StateObject) SubBalance(amount *big.Int) {
  156. c.SetBalance(new(big.Int).Sub(c.balance, amount))
  157. statelogger.Debugf("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
  158. }
  159. func (c *StateObject) SetBalance(amount *big.Int) {
  160. c.balance = amount
  161. c.dirty = true
  162. }
  163. func (c *StateObject) St() Storage {
  164. return c.storage
  165. }
  166. //
  167. // Gas setters and getters
  168. //
  169. // Return the gas back to the origin. Used by the Virtual machine or Closures
  170. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  171. func (c *StateObject) ConvertGas(gas, price *big.Int) error {
  172. total := new(big.Int).Mul(gas, price)
  173. if total.Cmp(c.balance) > 0 {
  174. return fmt.Errorf("insufficient amount: %v, %v", c.balance, total)
  175. }
  176. c.SubBalance(total)
  177. c.dirty = true
  178. return nil
  179. }
  180. func (self *StateObject) SetGasPool(gasLimit *big.Int) {
  181. self.gasPool = new(big.Int).Set(gasLimit)
  182. statelogger.Debugf("%x: gas (+ %v)", self.Address(), self.gasPool)
  183. }
  184. func (self *StateObject) BuyGas(gas, price *big.Int) error {
  185. if self.gasPool.Cmp(gas) < 0 {
  186. return GasLimitError(self.gasPool, gas)
  187. }
  188. self.gasPool.Sub(self.gasPool, gas)
  189. rGas := new(big.Int).Set(gas)
  190. rGas.Mul(rGas, price)
  191. self.dirty = true
  192. return nil
  193. }
  194. func (self *StateObject) RefundGas(gas, price *big.Int) {
  195. self.gasPool.Add(self.gasPool, gas)
  196. }
  197. func (self *StateObject) Copy() *StateObject {
  198. stateObject := NewStateObject(self.Address(), self.db)
  199. stateObject.balance.Set(self.balance)
  200. stateObject.codeHash = common.CopyBytes(self.codeHash)
  201. stateObject.nonce = self.nonce
  202. if self.State != nil {
  203. stateObject.State = self.State.Copy()
  204. }
  205. stateObject.code = common.CopyBytes(self.code)
  206. stateObject.initCode = common.CopyBytes(self.initCode)
  207. stateObject.storage = self.storage.Copy()
  208. stateObject.gasPool.Set(self.gasPool)
  209. stateObject.remove = self.remove
  210. stateObject.dirty = self.dirty
  211. return stateObject
  212. }
  213. func (self *StateObject) Set(stateObject *StateObject) {
  214. *self = *stateObject
  215. }
  216. //
  217. // Attribute accessors
  218. //
  219. func (self *StateObject) Balance() *big.Int {
  220. return self.balance
  221. }
  222. func (c *StateObject) N() *big.Int {
  223. return big.NewInt(int64(c.nonce))
  224. }
  225. // Returns the address of the contract/account
  226. func (c *StateObject) Address() common.Address {
  227. return c.address
  228. }
  229. // Returns the initialization Code
  230. func (c *StateObject) Init() Code {
  231. return c.initCode
  232. }
  233. func (self *StateObject) Trie() *trie.SecureTrie {
  234. return self.State.trie
  235. }
  236. func (self *StateObject) Root() []byte {
  237. return self.Trie().Root()
  238. }
  239. func (self *StateObject) Code() []byte {
  240. return self.code
  241. }
  242. func (self *StateObject) SetCode(code []byte) {
  243. self.code = code
  244. self.dirty = true
  245. }
  246. func (self *StateObject) SetInitCode(code []byte) {
  247. self.initCode = code
  248. self.dirty = true
  249. }
  250. func (self *StateObject) SetNonce(nonce uint64) {
  251. self.nonce = nonce
  252. self.dirty = true
  253. }
  254. func (self *StateObject) Nonce() uint64 {
  255. return self.nonce
  256. }
  257. //
  258. // Encoding
  259. //
  260. // State object encoding methods
  261. func (c *StateObject) RlpEncode() []byte {
  262. return common.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()})
  263. }
  264. func (c *StateObject) CodeHash() common.Bytes {
  265. return crypto.Sha3(c.code)
  266. }
  267. func (c *StateObject) RlpDecode(data []byte) {
  268. decoder := common.NewValueFromBytes(data)
  269. c.nonce = decoder.Get(0).Uint()
  270. c.balance = decoder.Get(1).BigInt()
  271. c.State = New(common.BytesToHash(decoder.Get(2).Bytes()), c.db) //New(trie.New(common.Config.Db, decoder.Get(2).Interface()))
  272. c.storage = make(map[string]*common.Value)
  273. c.gasPool = new(big.Int)
  274. c.codeHash = decoder.Get(3).Bytes()
  275. c.code, _ = c.db.Get(c.codeHash)
  276. }
  277. // Storage change object. Used by the manifest for notifying changes to
  278. // the sub channels.
  279. type StorageState struct {
  280. StateAddress []byte
  281. Address []byte
  282. Value *big.Int
  283. }