state_object.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. // The state object
  35. State *StateDB
  36. // Address belonging to this account
  37. address common.Address
  38. // The balance of the account
  39. balance *big.Int
  40. // The nonce of the account
  41. nonce uint64
  42. // The code hash if code is present (i.e. a contract)
  43. codeHash []byte
  44. // The code for this account
  45. code Code
  46. // Temporarily initialisation code
  47. initCode Code
  48. // Cached storage (flushed when updated)
  49. storage Storage
  50. // Temporary prepaid gas, reward after transition
  51. prepaid *big.Int
  52. // Total gas pool is the total amount of gas currently
  53. // left if this object is the coinbase. Gas is directly
  54. // purchased of the coinbase.
  55. gasPool *big.Int
  56. // Mark for deletion
  57. // When an object is marked for deletion it will be delete from the trie
  58. // during the "update" phase of the state transition
  59. remove bool
  60. dirty bool
  61. }
  62. func (self *StateObject) Reset() {
  63. self.storage = make(Storage)
  64. self.State.Reset()
  65. }
  66. func NewStateObject(address common.Address, db common.Database) *StateObject {
  67. // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter.
  68. //address := common.ToAddress(addr)
  69. object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int), dirty: true}
  70. object.State = New(common.Hash{}, db) //New(trie.New(common.Config.Db, ""))
  71. object.storage = make(Storage)
  72. object.gasPool = new(big.Int)
  73. object.prepaid = new(big.Int)
  74. return object
  75. }
  76. func NewStateObjectFromBytes(address common.Address, data []byte, db common.Database) *StateObject {
  77. // TODO clean me up
  78. var extobject struct {
  79. Nonce uint64
  80. Balance *big.Int
  81. Root common.Hash
  82. CodeHash []byte
  83. }
  84. err := rlp.Decode(bytes.NewReader(data), &extobject)
  85. if err != nil {
  86. fmt.Println(err)
  87. return nil
  88. }
  89. object := &StateObject{address: address, db: db}
  90. //object.RlpDecode(data)
  91. object.nonce = extobject.Nonce
  92. object.balance = extobject.Balance
  93. object.codeHash = extobject.CodeHash
  94. object.State = New(extobject.Root, db)
  95. object.storage = make(map[string]common.Hash)
  96. object.gasPool = new(big.Int)
  97. object.prepaid = new(big.Int)
  98. object.code, _ = db.Get(extobject.CodeHash)
  99. return object
  100. }
  101. func (self *StateObject) MarkForDeletion() {
  102. self.remove = true
  103. self.dirty = true
  104. if glog.V(logger.Core) {
  105. glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
  106. }
  107. }
  108. func (c *StateObject) getAddr(addr common.Hash) common.Hash {
  109. var ret []byte
  110. rlp.DecodeBytes(c.State.trie.Get(addr[:]), &ret)
  111. return common.BytesToHash(ret)
  112. }
  113. func (c *StateObject) setAddr(addr []byte, value common.Hash) {
  114. v, err := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  115. if err != nil {
  116. // if RLPing failed we better panic and not fail silently. This would be considered a consensus issue
  117. panic(err)
  118. }
  119. c.State.trie.Update(addr, v)
  120. }
  121. func (self *StateObject) Storage() Storage {
  122. return self.storage
  123. }
  124. func (self *StateObject) GetState(key common.Hash) common.Hash {
  125. strkey := key.Str()
  126. value, exists := self.storage[strkey]
  127. if !exists {
  128. value = self.getAddr(key)
  129. if (value != common.Hash{}) {
  130. self.storage[strkey] = value
  131. }
  132. }
  133. return value
  134. }
  135. func (self *StateObject) SetState(k, value common.Hash) {
  136. self.storage[k.Str()] = value
  137. self.dirty = true
  138. }
  139. func (self *StateObject) Sync() {
  140. for key, value := range self.storage {
  141. if (value == common.Hash{}) {
  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.Core) {
  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.Core) {
  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.Core) {
  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. func (self *StateObject) EachStorage(cb func(key, value []byte)) {
  268. // When iterating over the storage check the cache first
  269. for h, v := range self.storage {
  270. cb([]byte(h), v.Bytes())
  271. }
  272. it := self.State.trie.Iterator()
  273. for it.Next() {
  274. // ignore cached values
  275. key := self.State.trie.GetKey(it.Key)
  276. if _, ok := self.storage[string(key)]; !ok {
  277. cb(key, it.Value)
  278. }
  279. }
  280. }
  281. //
  282. // Encoding
  283. //
  284. // State object encoding methods
  285. func (c *StateObject) RlpEncode() []byte {
  286. return common.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()})
  287. }
  288. func (c *StateObject) CodeHash() common.Bytes {
  289. return crypto.Sha3(c.code)
  290. }
  291. func (c *StateObject) RlpDecode(data []byte) {
  292. decoder := common.NewValueFromBytes(data)
  293. c.nonce = decoder.Get(0).Uint()
  294. c.balance = decoder.Get(1).BigInt()
  295. c.State = New(common.BytesToHash(decoder.Get(2).Bytes()), c.db) //New(trie.New(common.Config.Db, decoder.Get(2).Interface()))
  296. c.storage = make(map[string]common.Hash)
  297. c.gasPool = new(big.Int)
  298. c.codeHash = decoder.Get(3).Bytes()
  299. c.code, _ = c.db.Get(c.codeHash)
  300. }
  301. // Storage change object. Used by the manifest for notifying changes to
  302. // the sub channels.
  303. type StorageState struct {
  304. StateAddress []byte
  305. Address []byte
  306. Value *big.Int
  307. }