-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathtypes.go
398 lines (349 loc) · 10.5 KB
/
types.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
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
package group
import (
"fmt"
"time"
proto "github.com/gogo/protobuf/proto"
"github.com/gogo/protobuf/types"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/group/errors"
"github.com/cosmos/cosmos-sdk/x/group/internal/math"
"github.com/cosmos/cosmos-sdk/x/group/internal/orm"
)
// MaxMetadataLength defines the max length of the metadata bytes field
// for various entities within the group module
// TODO: This could be used as params once x/params is upgraded to use protobuf
const MaxMetadataLength = 255
type DecisionPolicyResult struct {
Allow bool
Final bool
}
// DecisionPolicy is the persistent set of rules to determine the result of election on a proposal.
type DecisionPolicy interface {
codec.ProtoMarshaler
ValidateBasic() error
GetTimeout() time.Duration
Allow(tally Tally, totalPower string, votingDuration time.Duration) (DecisionPolicyResult, error)
Validate(g GroupInfo) error
}
// Implements DecisionPolicy Interface
var _ DecisionPolicy = &ThresholdDecisionPolicy{}
// NewThresholdDecisionPolicy creates a threshold DecisionPolicy
func NewThresholdDecisionPolicy(threshold string, timeout time.Duration) DecisionPolicy {
return &ThresholdDecisionPolicy{threshold, timeout}
}
func (p ThresholdDecisionPolicy) ValidateBasic() error {
if _, err := math.NewPositiveDecFromString(p.Threshold); err != nil {
return sdkerrors.Wrap(err, "threshold")
}
timeout := p.Timeout
if timeout <= time.Nanosecond {
return sdkerrors.Wrap(errors.ErrInvalid, "timeout")
}
return nil
}
// Allow allows a proposal to pass when the tally of yes votes equals or exceeds the threshold before the timeout.
func (p ThresholdDecisionPolicy) Allow(tally Tally, totalPower string, votingDuration time.Duration) (DecisionPolicyResult, error) {
pTimeout := types.DurationProto(p.Timeout)
timeout, err := types.DurationFromProto(pTimeout)
if err != nil {
return DecisionPolicyResult{}, err
}
if timeout <= votingDuration {
return DecisionPolicyResult{Allow: false, Final: true}, nil
}
threshold, err := math.NewPositiveDecFromString(p.Threshold)
if err != nil {
return DecisionPolicyResult{}, err
}
yesCount, err := math.NewNonNegativeDecFromString(tally.YesCount)
if err != nil {
return DecisionPolicyResult{}, err
}
if yesCount.Cmp(threshold) >= 0 {
return DecisionPolicyResult{Allow: true, Final: true}, nil
}
totalPowerDec, err := math.NewNonNegativeDecFromString(totalPower)
if err != nil {
return DecisionPolicyResult{}, err
}
totalCounts, err := tally.TotalCounts()
if err != nil {
return DecisionPolicyResult{}, err
}
undecided, err := math.SubNonNegative(totalPowerDec, totalCounts)
if err != nil {
return DecisionPolicyResult{}, err
}
sum, err := yesCount.Add(undecided)
if err != nil {
return DecisionPolicyResult{}, err
}
if sum.Cmp(threshold) < 0 {
return DecisionPolicyResult{Allow: false, Final: true}, nil
}
return DecisionPolicyResult{Allow: false, Final: false}, nil
}
// Validate returns an error if policy threshold is greater than the total group weight
func (p *ThresholdDecisionPolicy) Validate(g GroupInfo) error {
threshold, err := math.NewPositiveDecFromString(p.Threshold)
if err != nil {
return sdkerrors.Wrap(err, "threshold")
}
totalWeight, err := math.NewNonNegativeDecFromString(g.TotalWeight)
if err != nil {
return sdkerrors.Wrap(err, "group total weight")
}
if threshold.Cmp(totalWeight) > 0 {
return sdkerrors.Wrap(errors.ErrInvalid, "policy threshold should not be greater than the total group weight")
}
return nil
}
var _ orm.Validateable = GroupPolicyInfo{}
// NewGroupPolicyInfo creates a new GroupPolicyInfo instance
func NewGroupPolicyInfo(address sdk.AccAddress, group uint64, admin sdk.AccAddress, metadata []byte,
version uint64, decisionPolicy DecisionPolicy, createdAt time.Time) (GroupPolicyInfo, error) {
p := GroupPolicyInfo{
Address: address.String(),
GroupId: group,
Admin: admin.String(),
Metadata: metadata,
Version: version,
CreatedAt: createdAt,
}
err := p.SetDecisionPolicy(decisionPolicy)
if err != nil {
return GroupPolicyInfo{}, err
}
return p, nil
}
func (g *GroupPolicyInfo) SetDecisionPolicy(decisionPolicy DecisionPolicy) error {
msg, ok := decisionPolicy.(proto.Message)
if !ok {
return fmt.Errorf("can't proto marshal %T", msg)
}
any, err := codectypes.NewAnyWithValue(msg)
if err != nil {
return err
}
g.DecisionPolicy = any
return nil
}
func (g GroupPolicyInfo) GetDecisionPolicy() DecisionPolicy {
decisionPolicy, ok := g.DecisionPolicy.GetCachedValue().(DecisionPolicy)
if !ok {
return nil
}
return decisionPolicy
}
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (g GroupPolicyInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
var decisionPolicy DecisionPolicy
return unpacker.UnpackAny(g.DecisionPolicy, &decisionPolicy)
}
func (g GroupPolicyInfo) PrimaryKeyFields() []interface{} {
addr, err := sdk.AccAddressFromBech32(g.Address)
if err != nil {
panic(err)
}
return []interface{}{addr.Bytes()}
}
func (g GroupPolicyInfo) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(g.Admin)
if err != nil {
return sdkerrors.Wrap(err, "admin")
}
_, err = sdk.AccAddressFromBech32(g.Address)
if err != nil {
return sdkerrors.Wrap(err, "group policy")
}
if g.GroupId == 0 {
return sdkerrors.Wrap(errors.ErrEmpty, "group")
}
if g.Version == 0 {
return sdkerrors.Wrap(errors.ErrEmpty, "version")
}
policy := g.GetDecisionPolicy()
if policy == nil {
return sdkerrors.Wrap(errors.ErrEmpty, "policy")
}
if err := policy.ValidateBasic(); err != nil {
return sdkerrors.Wrap(err, "policy")
}
return nil
}
func (g GroupMember) PrimaryKeyFields() []interface{} {
addr, err := sdk.AccAddressFromBech32(g.Member.Address)
if err != nil {
panic(err)
}
return []interface{}{g.GroupId, addr.Bytes()}
}
func (g GroupMember) ValidateBasic() error {
if g.GroupId == 0 {
return sdkerrors.Wrap(errors.ErrEmpty, "group")
}
err := g.Member.ValidateBasic()
if err != nil {
return sdkerrors.Wrap(err, "member")
}
return nil
}
func (v Vote) PrimaryKeyFields() []interface{} {
addr, err := sdk.AccAddressFromBech32(v.Voter)
if err != nil {
panic(err)
}
return []interface{}{v.ProposalId, addr.Bytes()}
}
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (q QueryGroupPoliciesByGroupResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
return unpackGroupPolicies(unpacker, q.GroupPolicies)
}
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (q QueryGroupPoliciesByAdminResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
return unpackGroupPolicies(unpacker, q.GroupPolicies)
}
func unpackGroupPolicies(unpacker codectypes.AnyUnpacker, accs []*GroupPolicyInfo) error {
for _, g := range accs {
err := g.UnpackInterfaces(unpacker)
if err != nil {
return err
}
}
return nil
}
type operation func(x, y math.Dec) (math.Dec, error)
func (t *Tally) operation(vote Vote, weight string, op operation) error {
weightDec, err := math.NewPositiveDecFromString(weight)
if err != nil {
return err
}
yesCount, err := t.GetYesCount()
if err != nil {
return sdkerrors.Wrap(err, "yes count")
}
noCount, err := t.GetNoCount()
if err != nil {
return sdkerrors.Wrap(err, "no count")
}
abstainCount, err := t.GetAbstainCount()
if err != nil {
return sdkerrors.Wrap(err, "abstain count")
}
vetoCount, err := t.GetVetoCount()
if err != nil {
return sdkerrors.Wrap(err, "veto count")
}
switch vote.Choice {
case Choice_CHOICE_YES:
yesCount, err := op(yesCount, weightDec)
if err != nil {
return sdkerrors.Wrap(err, "yes count")
}
t.YesCount = yesCount.String()
case Choice_CHOICE_NO:
noCount, err := op(noCount, weightDec)
if err != nil {
return sdkerrors.Wrap(err, "no count")
}
t.NoCount = noCount.String()
case Choice_CHOICE_ABSTAIN:
abstainCount, err := op(abstainCount, weightDec)
if err != nil {
return sdkerrors.Wrap(err, "abstain count")
}
t.AbstainCount = abstainCount.String()
case Choice_CHOICE_VETO:
vetoCount, err := op(vetoCount, weightDec)
if err != nil {
return sdkerrors.Wrap(err, "veto count")
}
t.VetoCount = vetoCount.String()
default:
return sdkerrors.Wrapf(errors.ErrInvalid, "unknown choice %s", vote.Choice.String())
}
return nil
}
func (t Tally) GetYesCount() (math.Dec, error) {
yesCount, err := math.NewNonNegativeDecFromString(t.YesCount)
if err != nil {
return math.Dec{}, err
}
return yesCount, nil
}
func (t Tally) GetNoCount() (math.Dec, error) {
noCount, err := math.NewNonNegativeDecFromString(t.NoCount)
if err != nil {
return math.Dec{}, err
}
return noCount, nil
}
func (t Tally) GetAbstainCount() (math.Dec, error) {
abstainCount, err := math.NewNonNegativeDecFromString(t.AbstainCount)
if err != nil {
return math.Dec{}, err
}
return abstainCount, nil
}
func (t Tally) GetVetoCount() (math.Dec, error) {
vetoCount, err := math.NewNonNegativeDecFromString(t.VetoCount)
if err != nil {
return math.Dec{}, err
}
return vetoCount, nil
}
func (t *Tally) Add(vote Vote, weight string) error {
if err := t.operation(vote, weight, math.Add); err != nil {
return err
}
return nil
}
// TotalCounts is the sum of all weights.
func (t Tally) TotalCounts() (math.Dec, error) {
yesCount, err := t.GetYesCount()
if err != nil {
return math.Dec{}, sdkerrors.Wrap(err, "yes count")
}
noCount, err := t.GetNoCount()
if err != nil {
return math.Dec{}, sdkerrors.Wrap(err, "no count")
}
abstainCount, err := t.GetAbstainCount()
if err != nil {
return math.Dec{}, sdkerrors.Wrap(err, "abstain count")
}
vetoCount, err := t.GetVetoCount()
if err != nil {
return math.Dec{}, sdkerrors.Wrap(err, "veto count")
}
totalCounts := math.NewDecFromInt64(0)
totalCounts, err = totalCounts.Add(yesCount)
if err != nil {
return math.Dec{}, err
}
totalCounts, err = totalCounts.Add(noCount)
if err != nil {
return math.Dec{}, err
}
totalCounts, err = totalCounts.Add(abstainCount)
if err != nil {
return math.Dec{}, err
}
totalCounts, err = totalCounts.Add(vetoCount)
if err != nil {
return math.Dec{}, err
}
return totalCounts, nil
}
// ChoiceFromString returns a Choice from a string. It returns an error
// if the string is invalid.
func ChoiceFromString(str string) (Choice, error) {
choice, ok := Choice_value[str]
if !ok {
return Choice_CHOICE_UNSPECIFIED, fmt.Errorf("'%s' is not a valid vote choice", str)
}
return Choice(choice), nil
}