-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathcontext.go
More file actions
481 lines (408 loc) · 16 KB
/
Copy pathcontext.go
File metadata and controls
481 lines (408 loc) · 16 KB
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
package types
import (
"context"
"time"
abci "github.com/cometbft/cometbft/abci/types"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
"go.opentelemetry.io/otel/trace"
"cosmossdk.io/core/comet"
"cosmossdk.io/core/header"
"cosmossdk.io/log/v2"
"github.com/cosmos/cosmos-sdk/store/v2/gaskv"
storetypes "github.com/cosmos/cosmos-sdk/store/v2/types"
)
// ExecMode defines the execution mode which can be set on a Context.
type ExecMode uint8
// All possible execution modes.
const (
ExecModeCheck ExecMode = iota
ExecModeReCheck
ExecModeSimulate
ExecModePrepareProposal
ExecModeProcessProposal
ExecModeVoteExtension
ExecModeVerifyVoteExtension
ExecModeFinalize
)
/*
Context is an immutable object contains all information needed to
process a request.
It contains a context.Context object inside if you want to use that,
but please do not over-use it. We try to keep all data structured
and standard additions here would be better just to add to the Context struct
*/
type Context struct {
baseCtx context.Context
ms storetypes.MultiStore
// Deprecated: Use HeaderService for height, time, and chainID and CometService for the rest
header cmtproto.Header
// Deprecated: Use HeaderService for hash
headerHash []byte
// Deprecated: Use HeaderService for chainID and CometService for the rest
chainID string
txBytes []byte
logger log.Logger
voteInfo []abci.VoteInfo
gasMeter storetypes.GasMeter
blockGasMeter storetypes.GasMeter
checkTx bool
recheckTx bool // if recheckTx == true, then checkTx must also be true
sigverifyTx bool // when run simulation, because the private key corresponding to the account in the genesis.json randomly generated, we must skip the sigverify.
execMode ExecMode
minGasPrice DecCoins
consParams cmtproto.ConsensusParams
eventManager *EventManager
priority int64 // The tx priority, only relevant in CheckTx
kvGasConfig storetypes.GasConfig
transientKVGasConfig storetypes.GasConfig
streamingManager storetypes.StreamingManager
cometInfo comet.BlockInfo
headerInfo header.Info
// For block-stm
// // the index of the current tx in the block, -1 means not in finalize block context
txIndex int
// the index of the current msg in the tx, -1 means not in finalize block context
msgIndex int
// the total number of transactions in current block
txCount int
// sum the gas used by all the transactions in the current block, only accessible by end blocker
blockGasUsed uint64
incarnationCache map[string]any // incarnationCache is shared between multiple incarnations of the same transaction, it must only cache stateless computation results that only depends on tx body and block level information that don't change during block execution, like the result of tx signature verification.
// sum the gas wanted by all the transactions in the current block, only accessible by end blocker
blockGasWanted uint64
}
// Proposed rename, not done to avoid API breakage
type Request = Context
// Read-only accessors
func (c Context) Context() context.Context { return c.baseCtx }
func (c Context) MultiStore() storetypes.MultiStore { return c.ms }
func (c Context) BlockHeight() int64 { return c.header.Height }
func (c Context) BlockTime() time.Time { return c.header.Time }
func (c Context) ChainID() string { return c.chainID }
func (c Context) TxBytes() []byte { return c.txBytes }
func (c Context) Logger() log.Logger { return c.logger }
func (c Context) VoteInfos() []abci.VoteInfo { return c.voteInfo }
func (c Context) GasMeter() storetypes.GasMeter { return c.gasMeter }
func (c Context) BlockGasMeter() storetypes.GasMeter { return c.blockGasMeter }
func (c Context) IsCheckTx() bool { return c.checkTx }
func (c Context) IsReCheckTx() bool { return c.recheckTx }
func (c Context) IsSigverifyTx() bool { return c.sigverifyTx }
func (c Context) ExecMode() ExecMode { return c.execMode }
func (c Context) MinGasPrices() DecCoins { return c.minGasPrice }
func (c Context) EventManager() *EventManager { return c.eventManager }
func (c Context) Priority() int64 { return c.priority }
func (c Context) KVGasConfig() storetypes.GasConfig { return c.kvGasConfig }
func (c Context) TransientKVGasConfig() storetypes.GasConfig { return c.transientKVGasConfig }
func (c Context) StreamingManager() storetypes.StreamingManager { return c.streamingManager }
func (c Context) CometInfo() comet.BlockInfo { return c.cometInfo }
func (c Context) HeaderInfo() header.Info { return c.headerInfo }
func (c Context) TxIndex() int { return c.txIndex }
func (c Context) MsgIndex() int { return c.msgIndex }
func (c Context) TxCount() int { return c.txCount }
func (c Context) BlockGasUsed() uint64 { return c.blockGasUsed }
func (c Context) IncarnationCache() map[string]any { return c.incarnationCache }
func (c Context) BlockGasWanted() uint64 { return c.blockGasWanted }
// BlockHeader returns the header by value.
func (c Context) BlockHeader() cmtproto.Header {
return c.header
}
// HeaderHash returns a copy of the header hash obtained during abci.RequestBeginBlock
func (c Context) HeaderHash() []byte {
hash := make([]byte, len(c.headerHash))
copy(hash, c.headerHash)
return hash
}
func (c Context) ConsensusParams() cmtproto.ConsensusParams {
return c.consParams
}
func (c Context) Deadline() (deadline time.Time, ok bool) {
return c.baseCtx.Deadline()
}
func (c Context) Done() <-chan struct{} {
return c.baseCtx.Done()
}
func (c Context) Err() error {
return c.baseCtx.Err()
}
func NewContext(ms storetypes.MultiStore, header cmtproto.Header, isCheckTx bool, logger log.Logger) Context {
// https://github.com/gogo/protobuf/issues/519
header.Time = header.Time.UTC()
return Context{
baseCtx: context.Background(),
ms: ms,
header: header,
chainID: header.ChainID,
checkTx: isCheckTx,
sigverifyTx: true,
logger: logger,
gasMeter: storetypes.NewInfiniteGasMeter(),
minGasPrice: DecCoins{},
eventManager: NewEventManager(),
kvGasConfig: storetypes.KVGasConfig(),
transientKVGasConfig: storetypes.TransientGasConfig(),
txIndex: -1,
msgIndex: -1,
}
}
// WithContext returns a Context with an updated context.Context.
func (c Context) WithContext(ctx context.Context) Context {
c.baseCtx = ctx
return c
}
// WithMultiStore returns a Context with an updated MultiStore.
func (c Context) WithMultiStore(ms storetypes.MultiStore) Context {
c.ms = ms
return c
}
// WithBlockHeader returns a Context with an updated CometBFT block header in UTC time.
func (c Context) WithBlockHeader(header cmtproto.Header) Context {
// https://github.com/gogo/protobuf/issues/519
header.Time = header.Time.UTC()
c.header = header
return c
}
// WithHeaderHash returns a Context with an updated CometBFT block header hash.
func (c Context) WithHeaderHash(hash []byte) Context {
temp := make([]byte, len(hash))
copy(temp, hash)
c.headerHash = temp
return c
}
// WithBlockTime returns a Context with an updated CometBFT block header time in UTC with no monotonic component.
// Stripping the monotonic component is for time equality.
func (c Context) WithBlockTime(newTime time.Time) Context {
newHeader := c.BlockHeader()
// https://github.com/gogo/protobuf/issues/519
newHeader.Time = newTime.Round(0).UTC()
return c.WithBlockHeader(newHeader)
}
// WithProposer returns a Context with an updated proposer consensus address.
func (c Context) WithProposer(addr ConsAddress) Context {
newHeader := c.BlockHeader()
newHeader.ProposerAddress = addr.Bytes()
return c.WithBlockHeader(newHeader)
}
// WithBlockHeight returns a Context with an updated block height.
func (c Context) WithBlockHeight(height int64) Context {
newHeader := c.BlockHeader()
newHeader.Height = height
return c.WithBlockHeader(newHeader)
}
// WithChainID returns a Context with an updated chain identifier.
func (c Context) WithChainID(chainID string) Context {
c.chainID = chainID
return c
}
// WithTxBytes returns a Context with an updated txBytes.
func (c Context) WithTxBytes(txBytes []byte) Context {
c.txBytes = txBytes
return c
}
// WithLogger returns a Context with an updated logger.
func (c Context) WithLogger(logger log.Logger) Context {
c.logger = logger
return c
}
// WithVoteInfos returns a Context with an updated consensus VoteInfo.
func (c Context) WithVoteInfos(voteInfo []abci.VoteInfo) Context {
c.voteInfo = voteInfo
return c
}
// WithGasMeter returns a Context with an updated transaction GasMeter.
func (c Context) WithGasMeter(meter storetypes.GasMeter) Context {
c.gasMeter = meter
return c
}
// WithBlockGasMeter returns a Context with an updated block GasMeter
func (c Context) WithBlockGasMeter(meter storetypes.GasMeter) Context {
c.blockGasMeter = meter
return c
}
// WithKVGasConfig returns a Context with an updated gas configuration for
// the KVStore
func (c Context) WithKVGasConfig(gasConfig storetypes.GasConfig) Context {
c.kvGasConfig = gasConfig
return c
}
// WithTransientKVGasConfig returns a Context with an updated gas configuration for
// the transient KVStore
func (c Context) WithTransientKVGasConfig(gasConfig storetypes.GasConfig) Context {
c.transientKVGasConfig = gasConfig
return c
}
// WithIsCheckTx enables or disables CheckTx value for verifying transactions and returns an updated Context
func (c Context) WithIsCheckTx(isCheckTx bool) Context {
c.checkTx = isCheckTx
c.execMode = ExecModeCheck
return c
}
// WithIsReCheckTx called with true will also set true on checkTx in order to
// enforce the invariant that if recheckTx = true then checkTx = true as well.
func (c Context) WithIsReCheckTx(isRecheckTx bool) Context {
if isRecheckTx {
c.checkTx = true
}
c.recheckTx = isRecheckTx
c.execMode = ExecModeReCheck
return c
}
// WithIsSigverifyTx called with true will sigverify in auth module
func (c Context) WithIsSigverifyTx(isSigverifyTx bool) Context {
c.sigverifyTx = isSigverifyTx
return c
}
// WithExecMode returns a Context with an updated ExecMode.
func (c Context) WithExecMode(m ExecMode) Context {
c.execMode = m
return c
}
// WithMinGasPrices returns a Context with an updated minimum gas price value
func (c Context) WithMinGasPrices(gasPrices DecCoins) Context {
c.minGasPrice = gasPrices
return c
}
// WithConsensusParams returns a Context with an updated consensus params
func (c Context) WithConsensusParams(params cmtproto.ConsensusParams) Context {
c.consParams = params
return c
}
// WithEventManager returns a Context with an updated event manager
func (c Context) WithEventManager(em *EventManager) Context {
c.eventManager = em
return c
}
// WithPriority returns a Context with an updated tx priority
func (c Context) WithPriority(p int64) Context {
c.priority = p
return c
}
// WithStreamingManager returns a Context with an updated streaming manager
func (c Context) WithStreamingManager(sm storetypes.StreamingManager) Context {
c.streamingManager = sm
return c
}
// WithCometInfo returns a Context with an updated comet info
func (c Context) WithCometInfo(cometInfo comet.BlockInfo) Context {
c.cometInfo = cometInfo
return c
}
// WithHeaderInfo returns a Context with an updated header info
func (c Context) WithHeaderInfo(headerInfo header.Info) Context {
// Settime to UTC
headerInfo.Time = headerInfo.Time.UTC()
c.headerInfo = headerInfo
return c
}
func (c Context) WithTxIndex(txIndex int) Context {
c.txIndex = txIndex
return c
}
func (c Context) WithTxCount(txCount int) Context {
c.txCount = txCount
return c
}
func (c Context) WithMsgIndex(msgIndex int) Context {
c.msgIndex = msgIndex
return c
}
func (c Context) WithBlockGasUsed(gasUsed uint64) Context {
c.blockGasUsed = gasUsed
return c
}
func (c Context) WithBlockGasWanted(gasWanted uint64) Context {
c.blockGasWanted = gasWanted
return c
}
// TODO: remove???
func (c Context) IsZero() bool {
return c.ms == nil
}
func (c Context) WithValue(key, value any) Context {
c.baseCtx = context.WithValue(c.baseCtx, key, value)
return c
}
func (c Context) Value(key any) any {
if key == SdkContextKey {
return c
}
return c.baseCtx.Value(key)
}
// ----------------------------------------------------------------------------
// Store / Caching
// ----------------------------------------------------------------------------
// KVStore fetches a KVStore from the MultiStore.
func (c Context) KVStore(key storetypes.StoreKey) storetypes.KVStore {
return gaskv.NewStore(c.ms.GetKVStore(key), c.gasMeter, c.kvGasConfig)
}
// TransientStore fetches a TransientStore from the MultiStore.
func (c Context) TransientStore(key storetypes.StoreKey) storetypes.KVStore {
return gaskv.NewStore(c.ms.GetKVStore(key), c.gasMeter, c.transientKVGasConfig)
}
// ObjectStore fetches an object store from the MultiStore,
func (c Context) ObjectStore(key storetypes.StoreKey) storetypes.ObjKVStore {
return gaskv.NewObjStore(c.ms.GetObjKVStore(key), c.gasMeter, c.transientKVGasConfig)
}
// CacheContext returns a new Context with the multi-store cached and a new
// EventManager. The cached context is written to the context when writeCache
// is called. Note, events are automatically emitted on the parent context's
// EventManager when the caller executes the write.
func (c Context) CacheContext() (cc Context, writeCache func()) {
cms := c.ms.CacheMultiStore()
cc = c.WithMultiStore(cms).WithEventManager(NewEventManager())
writeCache = func() {
c.EventManager().EmitEvents(cc.EventManager().Events())
cms.Write()
}
return cc, writeCache
}
func (c Context) GetIncarnationCache(key string) (any, bool) {
if c.incarnationCache == nil {
return nil, false
}
val, ok := c.incarnationCache[key]
return val, ok
}
func (c Context) SetIncarnationCache(key string, value any) {
if c.incarnationCache == nil {
// noop if cache is not initialized
return
}
c.incarnationCache[key] = value
}
func (c Context) WithIncarnationCache(cache map[string]any) Context {
c.incarnationCache = cache
return c
}
// StartSpan starts an otel span and returns a new context with the span attached.
// Use this instead of calling tracer.Start directly to have the span correctly
// attached to this context type.
func (c Context) StartSpan(tracer trace.Tracer, spanName string, opts ...trace.SpanStartOption) (Context, trace.Span) {
goCtx, span := tracer.Start(c.baseCtx, spanName, opts...)
return c.WithContext(goCtx), span
}
var (
_ context.Context = Context{}
_ storetypes.Context = Context{}
)
// ContextKey defines a type alias for a stdlib Context key.
type ContextKey string
// SdkContextKey is the key in the context.Context which holds the sdk.Context.
const SdkContextKey ContextKey = "sdk-context"
// WrapSDKContext returns a stdlib context.Context with the provided sdk.Context's internal
// context as a value. It is useful for passing an sdk.Context through methods that take a
// stdlib context.Context parameter such as generated gRPC methods. To get the original
// sdk.Context back, call UnwrapSDKContext.
//
// Deprecated: there is no need to wrap anymore as the Cosmos SDK context implements context.Context.
func WrapSDKContext(ctx Context) context.Context {
return ctx
}
// UnwrapSDKContext retrieves a Context from a context.Context instance
// attached with WrapSDKContext. It panics if a Context was not properly
// attached
func UnwrapSDKContext(ctx context.Context) Context {
if sdkCtx, ok := ctx.(Context); ok {
return sdkCtx
}
return ctx.Value(SdkContextKey).(Context)
}