-
Notifications
You must be signed in to change notification settings - Fork 107
/
state.go
316 lines (271 loc) · 10.7 KB
/
state.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
304
305
306
307
308
309
310
311
312
313
314
315
316
package state
import (
"context"
"fmt"
"github.com/oasisprotocol/oasis-core/go/common"
"github.com/oasisprotocol/oasis-core/go/common/cbor"
"github.com/oasisprotocol/oasis-core/go/common/crypto/hash"
"github.com/oasisprotocol/oasis-core/go/common/keyformat"
"github.com/oasisprotocol/oasis-core/go/consensus/tendermint/api"
roothash "github.com/oasisprotocol/oasis-core/go/roothash/api"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs"
)
var (
// runtimeKeyFmt is the key format used for per-runtime roothash state.
//
// Value is CBOR-serialized roothash.RuntimeState.
runtimeKeyFmt = keyformat.New(0x20, keyformat.H(&common.Namespace{}))
// parametersKeyFmt is the key format used for consensus parameters.
//
// Value is CBOR-serialized roothash.ConsensusParameters.
parametersKeyFmt = keyformat.New(0x21)
// roundTimeoutQueueKeyFmt is the key format used for the round timeout queue.
//
// The format is (height, runtimeID). Value is runtimeID.
roundTimeoutQueueKeyFmt = keyformat.New(0x22, int64(0), keyformat.H(&common.Namespace{}))
// rejectTransactionsKeyFmt is the key format used to disable transactions.
//
// Value is a CBOR-serialized `true`.
rejectTransactionsKeyFmt = keyformat.New(0x23)
// evidenceKeyFmt is the key format used for storing valid misbehaviour evidence.
//
// Key format is: 0x24 <H(runtime-id) (hash.Hash)> <round (uint64)> <evidence-hash (hash.Hash)>
evidenceKeyFmt = keyformat.New(0x24, keyformat.H(&common.Namespace{}), uint64(0), &hash.Hash{})
// stateRootKeyFmt is the key format used for runtime state roots.
//
// Value is the runtime's latest state root.
stateRootKeyFmt = keyformat.New(0x25, keyformat.H(&common.Namespace{}))
// ioRootKeyFmt is the key format used for runtime I/O roots.
//
// Value is the runtime's latest I/O root.
ioRootKeyFmt = keyformat.New(0x26, keyformat.H(&common.Namespace{}))
cborTrue = cbor.Marshal(true)
)
// ImmutableState is the immutable roothash state wrapper.
type ImmutableState struct {
is *api.ImmutableState
}
func NewImmutableState(ctx context.Context, state api.ApplicationQueryState, version int64) (*ImmutableState, error) {
is, err := api.NewImmutableState(ctx, state, version)
if err != nil {
return nil, err
}
return &ImmutableState{is}, nil
}
func (s *ImmutableState) runtimesWithRoundTimeouts(ctx context.Context, height *int64) ([]common.Namespace, []int64, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
var startKey []byte
if height == nil {
startKey = roundTimeoutQueueKeyFmt.Encode()
} else {
startKey = roundTimeoutQueueKeyFmt.Encode(height)
}
var runtimeIDs []common.Namespace
var heights []int64
for it.Seek(startKey); it.Valid(); it.Next() {
var decHeight int64
if !roundTimeoutQueueKeyFmt.Decode(it.Key(), &decHeight) || (height != nil && decHeight != *height) {
break
}
var runtimeID common.Namespace
if err := runtimeID.UnmarshalBinary(it.Value()); err != nil {
return nil, nil, api.UnavailableStateError(err)
}
runtimeIDs = append(runtimeIDs, runtimeID)
if height == nil {
heights = append(heights, decHeight)
}
}
return runtimeIDs, heights, nil
}
// RuntimesWithRoundTimeouts returns the runtimes that have round timeouts scheduled at the given
// height.
func (s *ImmutableState) RuntimesWithRoundTimeouts(ctx context.Context, height int64) ([]common.Namespace, error) {
runtimeIDs, _, err := s.runtimesWithRoundTimeouts(ctx, &height)
return runtimeIDs, err
}
// RuntimesWithRoundTimeoutsAny returns the runtimes that have round timeouts scheduled at any
// height.
func (s *ImmutableState) RuntimesWithRoundTimeoutsAny(ctx context.Context) ([]common.Namespace, []int64, error) {
return s.runtimesWithRoundTimeouts(ctx, nil)
}
// RuntimeState returns the roothash runtime state for a specific runtime.
func (s *ImmutableState) RuntimeState(ctx context.Context, id common.Namespace) (*roothash.RuntimeState, error) {
raw, err := s.is.Get(ctx, runtimeKeyFmt.Encode(&id))
if err != nil {
return nil, api.UnavailableStateError(err)
}
if raw == nil {
return nil, roothash.ErrInvalidRuntime
}
var state roothash.RuntimeState
if err = cbor.Unmarshal(raw, &state); err != nil {
return nil, api.UnavailableStateError(err)
}
return &state, nil
}
func (s *ImmutableState) getRoot(ctx context.Context, id common.Namespace, kf *keyformat.KeyFormat) (hash.Hash, error) {
raw, err := s.is.Get(ctx, kf.Encode(&id))
if err != nil {
return hash.Hash{}, api.UnavailableStateError(err)
}
if raw == nil {
return hash.Hash{}, roothash.ErrInvalidRuntime
}
var h hash.Hash
if err = h.UnmarshalBinary(raw); err != nil {
return hash.Hash{}, api.UnavailableStateError(err)
}
return h, nil
}
// StateRoot returns the state root for a specific runtime.
func (s *ImmutableState) StateRoot(ctx context.Context, id common.Namespace) (hash.Hash, error) {
return s.getRoot(ctx, id, stateRootKeyFmt)
}
// IORoot returns the state root for a specific runtime.
func (s *ImmutableState) IORoot(ctx context.Context, id common.Namespace) (hash.Hash, error) {
return s.getRoot(ctx, id, ioRootKeyFmt)
}
// Runtimes returns the list of all roothash runtime states.
func (s *ImmutableState) Runtimes(ctx context.Context) ([]*roothash.RuntimeState, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
var runtimes []*roothash.RuntimeState
for it.Seek(runtimeKeyFmt.Encode()); it.Valid(); it.Next() {
if !runtimeKeyFmt.Decode(it.Key()) {
break
}
var state roothash.RuntimeState
if err := cbor.Unmarshal(it.Value(), &state); err != nil {
return nil, api.UnavailableStateError(err)
}
runtimes = append(runtimes, &state)
}
if it.Err() != nil {
return nil, api.UnavailableStateError(it.Err())
}
return runtimes, nil
}
// ConsensusParameters returns the roothash consensus parameters.
func (s *ImmutableState) ConsensusParameters(ctx context.Context) (*roothash.ConsensusParameters, error) {
raw, err := s.is.Get(ctx, parametersKeyFmt.Encode())
if err != nil {
return nil, api.UnavailableStateError(err)
}
if raw == nil {
return nil, fmt.Errorf("tendermint/roothash: expected consensus parameters to be present in app state")
}
var params roothash.ConsensusParameters
if err = cbor.Unmarshal(raw, ¶ms); err != nil {
return nil, api.UnavailableStateError(err)
}
return ¶ms, nil
}
// RejectTransactions returns true iff all transactions should be rejected.
func (s *ImmutableState) RejectTransactions(ctx context.Context) (bool, error) {
raw, err := s.is.Get(ctx, rejectTransactionsKeyFmt.Encode())
if err != nil {
return false, api.UnavailableStateError(err)
}
if raw == nil {
return false, nil
}
// This only ever will be true if present.
return true, nil
}
// EvidenceHashExists returns true if the evidence hash for the runtime exists.
func (s *ImmutableState) EvidenceHashExists(ctx context.Context, runtimeID common.Namespace, round uint64, hash hash.Hash) (bool, error) {
data, err := s.is.Get(ctx, evidenceKeyFmt.Encode(&runtimeID, round, &hash))
return data != nil, api.UnavailableStateError(err)
}
// MutableState is the mutable roothash state wrapper.
type MutableState struct {
*ImmutableState
ms mkvs.KeyValueTree
}
func NewMutableState(tree mkvs.KeyValueTree) *MutableState {
return &MutableState{
ImmutableState: &ImmutableState{
&api.ImmutableState{ImmutableKeyValueTree: tree},
},
ms: tree,
}
}
// SetRuntimeState sets a runtime's roothash state.
func (s *MutableState) SetRuntimeState(ctx context.Context, state *roothash.RuntimeState) error {
if err := s.ms.Insert(ctx, runtimeKeyFmt.Encode(&state.Runtime.ID), cbor.Marshal(state)); err != nil {
return api.UnavailableStateError(err)
}
// Store the current state and I/O roots separately to make them easier to retrieve when
// constructing proofs of runtime state.
stateRoot, _ := state.CurrentBlock.Header.StateRoot.MarshalBinary()
ioRoot, _ := state.CurrentBlock.Header.IORoot.MarshalBinary()
if err := s.ms.Insert(ctx, stateRootKeyFmt.Encode(&state.Runtime.ID), stateRoot); err != nil {
return api.UnavailableStateError(err)
}
if err := s.ms.Insert(ctx, ioRootKeyFmt.Encode(&state.Runtime.ID), ioRoot); err != nil {
return api.UnavailableStateError(err)
}
return nil
}
// SetConsensusParameters sets roothash consensus parameters.
//
// NOTE: This method must only be called from InitChain/EndBlock contexts.
func (s *MutableState) SetConsensusParameters(ctx context.Context, params *roothash.ConsensusParameters) error {
if err := s.is.CheckContextMode(ctx, []api.ContextMode{api.ContextInitChain, api.ContextEndBlock}); err != nil {
return err
}
err := s.ms.Insert(ctx, parametersKeyFmt.Encode(), cbor.Marshal(params))
return api.UnavailableStateError(err)
}
// ScheduleRoundTimeout schedules a new runtime round timeout at a given height.
func (s *MutableState) ScheduleRoundTimeout(ctx context.Context, runtimeID common.Namespace, height int64) error {
encodedID, _ := runtimeID.MarshalBinary()
err := s.ms.Insert(ctx, roundTimeoutQueueKeyFmt.Encode(height, &runtimeID), encodedID)
return api.UnavailableStateError(err)
}
// ClearRoundTimeout clears a previously scheduled round timeout at a given height.
func (s *MutableState) ClearRoundTimeout(ctx context.Context, runtimeID common.Namespace, height int64) error {
err := s.ms.Remove(ctx, roundTimeoutQueueKeyFmt.Encode(height, &runtimeID))
return api.UnavailableStateError(err)
}
// SetRejectTransactions sets the transaction disable.
func (s *MutableState) SetRejectTransactions(ctx context.Context) error {
err := s.ms.Insert(ctx, rejectTransactionsKeyFmt.Encode(), cborTrue)
return api.UnavailableStateError(err)
}
// ClearRejectTransactions clears the transaction disable.
func (s *MutableState) ClearRejectTransactions(ctx context.Context) error {
err := s.ms.Remove(ctx, rejectTransactionsKeyFmt.Encode())
return api.UnavailableStateError(err)
}
// SetEvidenceHash sets the provided evidence hash.
func (s *MutableState) SetEvidenceHash(ctx context.Context, runtimeID common.Namespace, round uint64, hash hash.Hash) error {
err := s.ms.Insert(ctx, evidenceKeyFmt.Encode(&runtimeID, round, &hash), []byte(""))
return api.UnavailableStateError(err)
}
// RemoveExpiredEvidence removes expired evidence.
func (s *MutableState) RemoveExpiredEvidence(ctx context.Context, runtimeID common.Namespace, minRound uint64) error {
it := s.is.NewIterator(ctx)
defer it.Close()
var toDelete [][]byte
for it.Seek(evidenceKeyFmt.Encode(&runtimeID)); it.Valid(); it.Next() {
var runtimeID keyformat.PreHashed
var round uint64
var hash hash.Hash
if !evidenceKeyFmt.Decode(it.Key(), &runtimeID, &round, &hash) {
break
}
if round > minRound {
break
}
toDelete = append(toDelete, it.Key())
}
for _, key := range toDelete {
if err := s.ms.Remove(ctx, key); err != nil {
return api.UnavailableStateError(err)
}
}
return nil
}