aboutsummaryrefslogtreecommitdiffstats
path: root/state/managed_state.go
blob: b0a129af09439356594065f0a4a4d91a109457bf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package state

import "sync"

type ManagedState struct {
    *StateDB

    mu sync.RWMutex

    accounts map[string]*StateObject
}

func ManageState(statedb *StateDB) *ManagedState {
    return &ManagedState{
        StateDB:  statedb,
        accounts: make(map[string]*StateObject),
    }
}

func (ms *ManagedState) IncrementNonce(addr []byte) {
    ms.mu.Lock()
    defer ms.mu.Unlock()

    ms.getAccount(addr).nonce++
}

func (ms *ManagedState) DecrementNonce(addr []byte) {
    // Decrementing a nonce does not mean we are interested in the account
    // incrementing only happens if you control the account, therefor
    // incrementing  behaves differently from decrementing
    if ms.hasAccount(addr) {
        ms.mu.Lock()
        defer ms.mu.Unlock()

        ms.getAccount(addr).nonce--
    }
}

func (ms *ManagedState) GetNonce(addr []byte) uint64 {
    ms.mu.RLock()
    defer ms.mu.RUnlock()
    return ms.getAccount(addr).nonce
}

func (ms *ManagedState) hasAccount(addr []byte) bool {
    _, ok := ms.accounts[string(addr)]
    return ok
}

func (ms *ManagedState) getAccount(addr []byte) *StateObject {
    if _, ok := ms.accounts[string(addr)]; !ok {
        ms.accounts[string(addr)] = ms.GetOrNewStateObject(addr)
    }

    return ms.accounts[string(addr)]
}