state_object.go 8.4 KB

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