/
validate_market_price_updates.go
334 lines (304 loc) · 11.5 KB
/
validate_market_price_updates.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package keeper
import (
errorsmod "cosmossdk.io/errors"
"fmt"
errorlib "github.com/furyanprotocol/v4-chain/protocol/lib/error"
"math/big"
"time"
gometrics "github.com/armon/go-metrics"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
pricefeedmetrics "github.com/furyanprotocol/v4-chain/protocol/daemons/pricefeed/metrics"
"github.com/furyanprotocol/v4-chain/protocol/lib"
"github.com/furyanprotocol/v4-chain/protocol/lib/metrics"
"github.com/furyanprotocol/v4-chain/protocol/x/prices/types"
)
const (
CrossingPriceUpdateCutoffPpm = uint32(500_000) // 50%
)
// PerformStatefulPriceUpdateValidation performs stateful validations on `MsgUpdateMarketPrices`.
// Depending on the input, this func performs non-deterministic stateful validation.
func (k Keeper) PerformStatefulPriceUpdateValidation(
ctx sdk.Context,
marketPriceUpdates *types.MsgUpdateMarketPrices,
performNonDeterministicValidation bool,
) error {
var determinismMetricKeyValue string
if performNonDeterministicValidation {
determinismMetricKeyValue = metrics.NonDeterministic
} else {
determinismMetricKeyValue = metrics.Deterministic
}
defer telemetry.ModuleMeasureSince(
types.ModuleName,
time.Now(),
metrics.StatefulPriceUpdateValidation,
determinismMetricKeyValue,
metrics.Latency,
)
marketParamPrices, err := k.GetAllMarketParamPrices(ctx)
if err != nil {
telemetry.IncrCounter(
1,
types.ModuleName,
metrics.StatefulPriceUpdateValidation,
metrics.Error,
)
return errorlib.WrapErrorWithSourceModuleContext(
errorsmod.Wrap(err, "failed to get all market param prices"),
types.ModuleName,
)
}
if err := k.performDeterministicStatefulValidation(ctx, marketPriceUpdates, marketParamPrices); err != nil {
telemetry.IncrCounter(
1,
types.ModuleName,
metrics.StatefulPriceUpdateValidation,
metrics.Deterministic,
metrics.Error,
)
return errorlib.WrapErrorWithSourceModuleContext(err, types.ModuleName)
}
if performNonDeterministicValidation {
err := k.performNonDeterministicStatefulValidation(ctx, marketPriceUpdates, marketParamPrices)
if err != nil {
telemetry.IncrCounter(
1,
types.ModuleName,
metrics.StatefulPriceUpdateValidation,
metrics.NonDeterministic,
metrics.Error,
)
return errorlib.WrapErrorWithSourceModuleContext(err, types.ModuleName)
}
}
return nil
}
// performNonDeterministicStatefulValidation performs stateful validations that are non-deterministic.
//
// Specificically, for each price update, validate the following:
// - The index price exists.
// - The price is "accurate". See `validatePriceAccuracy` for how "accuracy" is determined.
//
// Note: this is NOT determistic, because it relies on "index price" that is subject to each validator.
func (k Keeper) performNonDeterministicStatefulValidation(
ctx sdk.Context,
marketPriceUpdates *types.MsgUpdateMarketPrices,
allMarketParamPrices []types.MarketParamPrice,
) error {
idToMarket := getIdToMarketParamPrice(allMarketParamPrices)
allMarketParams := make([]types.MarketParam, len(allMarketParamPrices))
for i, marketParamPrice := range allMarketParamPrices {
allMarketParams[i] = marketParamPrice.Param
}
idToIndexPrice := k.indexPriceCache.GetValidMedianPrices(allMarketParams, k.timeProvider.Now())
for _, priceUpdate := range marketPriceUpdates.GetMarketPriceUpdates() {
// Check market exists.
marketParamPrice, err := getMarketParamPrice(priceUpdate.MarketId, idToMarket)
if err != nil {
return err
}
// Check index price exists.
indexPrice, indexPriceExists := idToIndexPrice[priceUpdate.MarketId]
if !indexPriceExists {
// Index price not available, so the update price accuracy cannot be determined.
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.IndexPriceNotAvailForAccuracyCheck, metrics.Count},
1,
[]gometrics.Label{ // To track per market, include the id as a label.
pricefeedmetrics.GetLabelForMarketId(marketParamPrice.Param.Id),
},
)
return errorsmod.Wrapf(
types.ErrIndexPriceNotAvailable,
"index price for market (%d) is not available",
priceUpdate.MarketId,
)
}
// Check price is "accurate".
if err := k.validatePriceAccuracy(marketParamPrice, priceUpdate, indexPrice); err != nil {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.IndexPriceNotAccurate, metrics.Count},
1,
[]gometrics.Label{ // To track per market, include the id as a label.
pricefeedmetrics.GetLabelForMarketId(marketParamPrice.Param.Id),
},
)
return err
}
}
// Report missing markets in the price updates.
missingMarketIds := k.GetMarketsMissingFromPriceUpdates(ctx, marketPriceUpdates.MarketPriceUpdates)
if len(missingMarketIds) > 0 {
telemetry.SetGauge(
float32(len(missingMarketIds)),
types.ModuleName,
metrics.MissingPriceUpdates,
metrics.Count,
)
k.Logger(ctx).Info(fmt.Sprintf("markets were not included in the price updates: %+v", missingMarketIds))
}
return nil
}
// performDeterministicStatefulValidation performs stateful validations that are deterministic.
//
// Specificically, for each price update, validate the following:
// - The market exists.
// - The price update is greater than the min price change.
func (k Keeper) performDeterministicStatefulValidation(
ctx sdk.Context,
marketPriceUpdates *types.MsgUpdateMarketPrices,
allMarketParamPrices []types.MarketParamPrice,
) error {
idToMarketParamPrice := getIdToMarketParamPrice(allMarketParamPrices)
for _, priceUpdate := range marketPriceUpdates.GetMarketPriceUpdates() {
// Check market exists.
marketParamPrice, err := getMarketParamPrice(priceUpdate.MarketId, idToMarketParamPrice)
if err != nil {
return err
}
// Check price respects min price change.
if !isAboveRequiredMinPriceChange(marketParamPrice, priceUpdate.Price) {
return errorsmod.Wrapf(
types.ErrInvalidMarketPriceUpdateDeterministic,
"update price (%d) for market (%d) does not meet min price change requirement"+
" (%d ppm) based on the current market price (%d)",
priceUpdate.Price,
priceUpdate.MarketId,
marketParamPrice.Param.MinPriceChangePpm,
marketParamPrice.Price.Price,
)
}
}
return nil
}
// validatePriceAccuracy checks if the price update is "accurate".
//
// "Accurate" means either one of the following conditions must be met:
//
// - Towards condition: the price update is between the index price and the current price, inclusive
//
// - Crossing condition: if the proposed price crosses the index price, then the absolute difference
// in ticks between the index price and the current price, in ticks (old_ticks), must be:
// -- old_ticks > 1: greater than or equal to the square of the absolute difference between this node's
// index price and the proposed price update, in ticks (new_ticks),
// -- old_ticks <= 1: greater than or equal to the absolute difference between this node's index price
// and the proposed price update
//
// Note that ticks are defined as the minimum price change of the currency at the current price
func (k Keeper) validatePriceAccuracy(
currMarketParamPrice types.MarketParamPrice,
priceUpdate *types.MsgUpdateMarketPrices_MarketPrice,
indexPrice uint64,
) error {
if isTowardsIndexPrice(PriceTuple{
OldPrice: currMarketParamPrice.Price.Price,
IndexPrice: indexPrice,
NewPrice: priceUpdate.Price,
}) {
return nil
}
if !isCrossingIndexPrice(PriceTuple{
OldPrice: currMarketParamPrice.Price.Price,
IndexPrice: indexPrice,
NewPrice: priceUpdate.Price,
}) {
return errorsmod.Wrapf(
types.ErrInvalidMarketPriceUpdateNonDeterministic,
"update price (%d) for market (%d) trends in the opposite direction of the index price (%d) compared "+
"to the current price (%d)",
priceUpdate.Price,
priceUpdate.MarketId,
indexPrice,
currMarketParamPrice.Price.Price,
)
}
tickSizePpm := computeTickSizePpm(currMarketParamPrice.Price.Price, currMarketParamPrice.Param.MinPriceChangePpm)
oldDelta := new(big.Int).SetUint64(lib.AbsDiffUint64(currMarketParamPrice.Price.Price, indexPrice))
newDelta := new(big.Int).SetUint64(lib.AbsDiffUint64(indexPrice, priceUpdate.Price))
// If the index price is <= 1 tick from the old price, we want to compare absolute values of old_delta
// and new_delta to determine if the price change is valid.
if priceDeltaIsWithinOneTick(oldDelta, tickSizePpm) {
if newDelta.Cmp(oldDelta) > 0 {
return errorsmod.Wrapf(
types.ErrInvalidMarketPriceUpdateNonDeterministic,
"update price (%d) for market (%d) crosses the index price (%d) with current price (%d) "+
"and deviates from index price (%d) more than minimum allowed (%d)",
priceUpdate.Price,
priceUpdate.MarketId,
indexPrice,
currMarketParamPrice.Price.Price,
newDelta.Uint64(),
oldDelta.Uint64(),
)
}
return nil
}
// Update price crosses index price and old_ticks > 1: check new_ticks <= sqrt(old_ticks)
if !newPriceMeetsSqrtCondition(oldDelta, newDelta, tickSizePpm) {
return errorsmod.Wrapf(
types.ErrInvalidMarketPriceUpdateNonDeterministic,
"update price (%d) for market (%d) crosses the index price (%d) with current price (%d) "+
"and deviates from index price (%d) more than minimum allowed (%d)",
priceUpdate.Price,
priceUpdate.MarketId,
indexPrice,
currMarketParamPrice.Price.Price,
newDelta.Uint64(),
maximumAllowedPriceDelta(oldDelta, tickSizePpm),
)
}
return nil
}
// GetMarketsMissingFromPriceUpdates returns a list of market ids that should have been included but
// not present in the `MsgUpdateMarketPrices`.
//
// Note: this is NOT determistic, because it relies on "index price" that is subject to each validator.
func (k Keeper) GetMarketsMissingFromPriceUpdates(
ctx sdk.Context,
marketPriceUpdates []*types.MsgUpdateMarketPrices_MarketPrice,
) []uint32 {
// Gather all markets that are part of the proposed updates.
proposedUpdatesMap := make(map[uint32]struct{}, len(marketPriceUpdates))
for _, proposedUpdate := range marketPriceUpdates {
proposedUpdatesMap[proposedUpdate.MarketId] = struct{}{}
}
// Gather all markets that we think should be updated.
var missingMarkets []uint32
// Note that `GetValidMarketPriceUpdates` return value is ordered by market id.
// This is NOT deterministic, because the returned values are based on "index price".
allLocalUpdates := k.GetValidMarketPriceUpdates(ctx).MarketPriceUpdates
for _, localUpdate := range allLocalUpdates {
if _, exists := proposedUpdatesMap[localUpdate.MarketId]; !exists {
missingMarkets = append(missingMarkets, localUpdate.MarketId)
}
}
return missingMarkets
}
// getIdToMarketParamPrice returns a map of market id to market param price given a slice of market param prices.
func getIdToMarketParamPrice(marketParamPrices []types.MarketParamPrice) map[uint32]types.MarketParamPrice {
idToMarketParamPrice := make(map[uint32]types.MarketParamPrice, len(marketParamPrices))
for _, marketParamPrice := range marketParamPrices {
idToMarketParamPrice[marketParamPrice.Param.Id] = marketParamPrice
}
return idToMarketParamPrice
}
// getMarketParamPrice returns a market param price given a market id. Returns an error if a market
// param price does not exist.
func getMarketParamPrice(
marketId uint32,
idToMarketParamPrice map[uint32]types.MarketParamPrice,
) (
types.MarketParamPrice,
error,
) {
marketParamPrice, marketParamPriceExists := idToMarketParamPrice[marketId]
if !marketParamPriceExists {
return marketParamPrice, errorsmod.Wrapf(
types.ErrInvalidMarketPriceUpdateDeterministic,
"market param price (%d) does not exist",
marketId,
)
}
return marketParamPrice, nil
}