forked from hyperledger-archives/burrow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state_cache.go
303 lines (279 loc) · 7.83 KB
/
state_cache.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Copyright 2017 Monax Industries Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package acmstate
import (
"fmt"
"sort"
"sync"
"github.com/hyperledger/burrow/execution/errors"
"github.com/hyperledger/burrow/acm"
"github.com/hyperledger/burrow/binary"
"github.com/hyperledger/burrow/crypto"
)
type Cache struct {
sync.RWMutex
name string
backend Reader
accounts map[crypto.Address]*accountInfo
readonly bool
}
type accountInfo struct {
sync.RWMutex
account *acm.Account
storage map[binary.Word256]binary.Word256
removed bool
updated bool
}
type CacheOption func(*Cache) *Cache
// Returns a Cache that wraps an underlying Reader to use on a cache miss, can write to an output Writer
// via Sync. Goroutine safe for concurrent access.
func NewCache(backend Reader, options ...CacheOption) *Cache {
cache := &Cache{
backend: backend,
accounts: make(map[crypto.Address]*accountInfo),
}
for _, option := range options {
option(cache)
}
return cache
}
func Named(name string) CacheOption {
return func(cache *Cache) *Cache {
cache.name = name
return cache
}
}
var ReadOnly CacheOption = func(cache *Cache) *Cache {
cache.readonly = true
return cache
}
func (cache *Cache) GetAccount(address crypto.Address) (*acm.Account, error) {
accInfo, err := cache.get(address)
if err != nil {
return nil, err
}
accInfo.RLock()
defer accInfo.RUnlock()
if accInfo.removed {
return nil, nil
}
return accInfo.account.Copy(), nil
}
func (cache *Cache) UpdateAccount(account *acm.Account) error {
if account == nil {
return errors.ErrorCodef(errors.ErrorCodeIllegalWrite, "UpdateAccount called with nil account")
}
if cache.readonly {
return errors.ErrorCodef(errors.ErrorCodeIllegalWrite,
"UpdateAccount called in a read-only context on account %v", account.GetAddress())
}
accInfo, err := cache.get(account.GetAddress())
if err != nil {
return err
}
accInfo.Lock()
defer accInfo.Unlock()
if accInfo.removed {
return errors.ErrorCodef(errors.ErrorCodeIllegalWrite, "UpdateAccount on a removed account: %s", account.GetAddress())
}
accInfo.account = account.Copy()
accInfo.updated = true
return nil
}
func (cache *Cache) RemoveAccount(address crypto.Address) error {
if cache.readonly {
return errors.ErrorCodef(errors.ErrorCodeIllegalWrite, "RemoveAccount called on read-only account %v", address)
}
accInfo, err := cache.get(address)
if err != nil {
return err
}
accInfo.Lock()
defer accInfo.Unlock()
if accInfo.removed {
return fmt.Errorf("RemoveAccount on a removed account: %s", address)
}
accInfo.removed = true
return nil
}
// Iterates over all cached accounts first in cache and then in backend until consumer returns true for 'stop'
func (cache *Cache) IterateCachedAccount(consumer func(*acm.Account) (stop bool)) (stopped bool, err error) {
// Try cache first for early exit
cache.RLock()
for _, info := range cache.accounts {
if consumer(info.account) {
cache.RUnlock()
return true, nil
}
}
cache.RUnlock()
return false, nil
}
func (cache *Cache) GetStorage(address crypto.Address, key binary.Word256) (binary.Word256, error) {
accInfo, err := cache.get(address)
if err != nil {
return binary.Zero256, err
}
// Check cache
accInfo.RLock()
value, ok := accInfo.storage[key]
accInfo.RUnlock()
if !ok {
accInfo.Lock()
defer accInfo.Unlock()
value, ok = accInfo.storage[key]
if !ok {
// Load from backend
value, err = cache.backend.GetStorage(address, key)
if err != nil {
return binary.Zero256, err
}
accInfo.storage[key] = value
}
}
return value, nil
}
// NOTE: Set value to zero to remove.
func (cache *Cache) SetStorage(address crypto.Address, key binary.Word256, value binary.Word256) error {
if cache.readonly {
return errors.ErrorCodef(errors.ErrorCodeIllegalWrite,
"SetStorage called in a read-only context on account %v", address)
}
accInfo, err := cache.get(address)
if accInfo.account == nil {
return errors.ErrorCodef(errors.ErrorCodeIllegalWrite,
"SetStorage called on an account that does not exist: %v", address)
}
accInfo.Lock()
defer accInfo.Unlock()
if err != nil {
return err
}
if accInfo.removed {
return errors.ErrorCodef(errors.ErrorCodeIllegalWrite, "SetStorage on a removed account: %s", address)
}
accInfo.storage[key] = value
accInfo.updated = true
return nil
}
// Iterates over all cached storage items first in cache and then in backend until consumer returns true for 'stop'
func (cache *Cache) IterateCachedStorage(address crypto.Address,
consumer func(key, value binary.Word256) error) error {
accInfo, err := cache.get(address)
if err != nil {
return err
}
accInfo.RLock()
// Try cache first for early exit
for key, value := range accInfo.storage {
if err := consumer(key, value); err != nil {
accInfo.RUnlock()
return err
}
}
accInfo.RUnlock()
return err
}
// Syncs changes to the backend in deterministic order. Sends storage updates before updating
// the account they belong so that storage values can be taken account of in the update.
func (cache *Cache) Sync(st Writer) error {
if cache.readonly {
// Sync is (should be) a no-op for read-only - any modifications should have been caught in respective methods
return nil
}
cache.Lock()
defer cache.Unlock()
var addresses crypto.Addresses
for address := range cache.accounts {
addresses = append(addresses, address)
}
sort.Sort(addresses)
for _, address := range addresses {
accInfo := cache.accounts[address]
accInfo.RLock()
if accInfo.removed {
err := st.RemoveAccount(address)
if err != nil {
return err
}
} else if accInfo.updated {
// First update account in case it needs to be created
err := st.UpdateAccount(accInfo.account)
if err != nil {
return err
}
// Sort keys
var keys binary.Words256
for key := range accInfo.storage {
keys = append(keys, key)
}
sort.Sort(keys)
// Update account's storage
for _, key := range keys {
value := accInfo.storage[key]
err := st.SetStorage(address, key, value)
if err != nil {
return err
}
}
}
accInfo.RUnlock()
}
return nil
}
// Resets the cache to empty initialising the backing map to the same size as the previous iteration.
func (cache *Cache) Reset(backend Reader) {
cache.Lock()
defer cache.Unlock()
cache.backend = backend
cache.accounts = make(map[crypto.Address]*accountInfo, len(cache.accounts))
}
// Syncs the Cache to output and Resets it to use backend as Reader
func (cache *Cache) Flush(output Writer, backend Reader) error {
err := cache.Sync(output)
if err != nil {
return err
}
cache.Reset(backend)
return nil
}
func (cache *Cache) String() string {
if cache.name == "" {
return fmt.Sprintf("StateCache{Length: %v}", len(cache.accounts))
}
return fmt.Sprintf("StateCache{Name: %v; Length: %v}", cache.name, len(cache.accounts))
}
// Get the cache accountInfo item creating it if necessary
func (cache *Cache) get(address crypto.Address) (*accountInfo, error) {
cache.RLock()
accInfo := cache.accounts[address]
cache.RUnlock()
if accInfo == nil {
cache.Lock()
defer cache.Unlock()
accInfo = cache.accounts[address]
if accInfo == nil {
account, err := cache.backend.GetAccount(address)
if err != nil {
return nil, err
}
accInfo = &accountInfo{
account: account,
storage: make(map[binary.Word256]binary.Word256),
}
cache.accounts[address] = accInfo
}
}
return accInfo, nil
}