managed_state.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package state
  2. import (
  3. "sync"
  4. "github.com/ethereum/go-ethereum/common"
  5. )
  6. type account struct {
  7. stateObject *StateObject
  8. nstart uint64
  9. nonces []bool
  10. }
  11. type ManagedState struct {
  12. *StateDB
  13. mu sync.RWMutex
  14. accounts map[string]*account
  15. }
  16. func ManageState(statedb *StateDB) *ManagedState {
  17. return &ManagedState{
  18. StateDB: statedb,
  19. accounts: make(map[string]*account),
  20. }
  21. }
  22. func (ms *ManagedState) SetState(statedb *StateDB) {
  23. ms.mu.Lock()
  24. defer ms.mu.Unlock()
  25. ms.StateDB = statedb
  26. }
  27. func (ms *ManagedState) RemoveNonce(addr common.Address, n uint64) {
  28. if ms.hasAccount(addr) {
  29. ms.mu.Lock()
  30. defer ms.mu.Unlock()
  31. account := ms.getAccount(addr)
  32. if n-account.nstart <= uint64(len(account.nonces)) {
  33. reslice := make([]bool, n-account.nstart)
  34. copy(reslice, account.nonces[:n-account.nstart])
  35. account.nonces = reslice
  36. }
  37. }
  38. }
  39. func (ms *ManagedState) NewNonce(addr common.Address) uint64 {
  40. ms.mu.RLock()
  41. defer ms.mu.RUnlock()
  42. account := ms.getAccount(addr)
  43. for i, nonce := range account.nonces {
  44. if !nonce {
  45. return account.nstart + uint64(i)
  46. }
  47. }
  48. account.nonces = append(account.nonces, true)
  49. return uint64(len(account.nonces)) + account.nstart
  50. }
  51. func (ms *ManagedState) hasAccount(addr common.Address) bool {
  52. _, ok := ms.accounts[addr.Str()]
  53. return ok
  54. }
  55. func (ms *ManagedState) getAccount(addr common.Address) *account {
  56. straddr := addr.Str()
  57. if account, ok := ms.accounts[straddr]; !ok {
  58. so := ms.GetOrNewStateObject(addr)
  59. ms.accounts[straddr] = newAccount(so)
  60. } else {
  61. // Always make sure the state account nonce isn't actually higher
  62. // than the tracked one.
  63. so := ms.StateDB.GetStateObject(addr)
  64. if so != nil && uint64(len(account.nonces))+account.nstart < so.nonce {
  65. ms.accounts[straddr] = newAccount(so)
  66. }
  67. }
  68. return ms.accounts[straddr]
  69. }
  70. func newAccount(so *StateObject) *account {
  71. return &account{so, so.nonce - 1, nil}
  72. }