forked from decred/politeia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmds.go
546 lines (495 loc) · 15.4 KB
/
cmds.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
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// Copyright (c) 2021 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package pi
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"sort"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
backend "github.com/decred/politeia/politeiad/backendv2"
"github.com/decred/politeia/politeiad/backendv2/tstorebe/store"
"github.com/decred/politeia/politeiad/plugins/pi"
"github.com/decred/politeia/politeiad/plugins/ticketvote"
"github.com/decred/politeia/politeiad/plugins/usermd"
"github.com/decred/politeia/util"
)
const (
pluginID = pi.PluginID
// Blob entry data descriptors
dataDescriptorBillingStatus = pluginID + "-billingstatus-v1"
)
var (
// billingStatusChanges contains the allowed billing status transitions. If
// billingStatusChanges[currentStatus][newStatus] exists then the the billing
// status transition is allowed.
billingStatusChanges = map[pi.BillingStatusT]map[pi.BillingStatusT]struct{}{
// Active to...
pi.BillingStatusActive: {
pi.BillingStatusClosed: {},
pi.BillingStatusCompleted: {},
},
// Closed to...
pi.BillingStatusClosed: {
pi.BillingStatusActive: {},
pi.BillingStatusCompleted: {},
},
// Completed to...
pi.BillingStatusCompleted: {
pi.BillingStatusActive: {},
pi.BillingStatusClosed: {},
},
}
)
// cmdSetBillingStatus sets proposal's billing status.
func (p *piPlugin) cmdSetBillingStatus(token []byte, payload string) (string, error) {
// Decode payload
var sbs pi.SetBillingStatus
err := json.Unmarshal([]byte(payload), &sbs)
if err != nil {
return "", err
}
// Verify token
err = tokenMatches(token, sbs.Token)
if err != nil {
return "", err
}
// Verify billing status
switch sbs.Status {
case pi.BillingStatusActive, pi.BillingStatusClosed,
pi.BillingStatusCompleted:
// These are allowed; continue
default:
// Billing status is invalid
return "", backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(pi.ErrorCodeBillingStatusInvalid),
ErrorContext: "invalid billing status",
}
}
// Verify signature
msg := sbs.Token + strconv.FormatUint(uint64(sbs.Status), 10) + sbs.Reason
err = util.VerifySignature(sbs.Signature, sbs.PublicKey, msg)
if err != nil {
return "", convertSignatureError(err)
}
// Ensure reason is provided when status is set to closed.
if sbs.Status == pi.BillingStatusClosed && sbs.Reason == "" {
return "", backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(pi.ErrorCodeBillingStatusChangeNotAllowed),
ErrorContext: "must provide a reason when setting " +
"billing status to closed",
}
}
// Ensure proposal's vote ended and it was approved
vsr, err := p.voteSummary(token)
if err != nil {
return "", err
}
if vsr.Status != ticketvote.VoteStatusApproved {
return "", backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(pi.ErrorCodeBillingStatusChangeNotAllowed),
ErrorContext: "setting billing status is allowed only if " +
"proposal vote was approved",
}
}
// Ensure that this is not an RFP proposal. RFP proposals do not
// request funding and do not bill against the treasury, which
// means that they don't have a billing status. RFP submission
// proposals, however, do request funding and do have a billing
// status.
r, err := p.record(backend.RecordRequest{
Token: token,
Filenames: []string{ticketvote.FileNameVoteMetadata},
})
if err != nil {
return "", err
}
vm, err := voteMetadataDecode(r.Files)
if err != nil {
return "", err
}
if isRFP(vm) {
return "", backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(pi.ErrorCodeBillingStatusChangeNotAllowed),
ErrorContext: "rfp proposals do not have a billing status",
}
}
// Ensure number of billing status changes does not exceed the maximum
bscs, err := p.billingStatusChanges(token)
if err != nil {
return "", err
}
if uint32(len(bscs)+1) > p.billingStatusChangesMax {
return "", backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(pi.ErrorCodeBillingStatusChangeNotAllowed),
ErrorContext: "number of billing status changes exceeds the " +
"maximum allowed number of billing status changes",
}
}
// Ensure billing status change transition is valid
currStatus := proposalBillingStatus(vsr.Status, bscs)
_, ok := billingStatusChanges[currStatus][sbs.Status]
if !ok {
return "", backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(pi.ErrorCodeBillingStatusChangeNotAllowed),
ErrorContext: fmt.Sprintf("invalid billing status transition, "+
"%v to %v is not allowed", pi.BillingStatuses[currStatus],
pi.BillingStatuses[sbs.Status]),
}
}
// Save billing status change
receipt := p.identity.SignMessage([]byte(sbs.Signature))
bsc := pi.BillingStatusChange{
Token: sbs.Token,
Status: sbs.Status,
Reason: sbs.Reason,
PublicKey: sbs.PublicKey,
Signature: sbs.Signature,
Timestamp: time.Now().Unix(),
Receipt: hex.EncodeToString(receipt[:]),
}
err = p.billingStatusSave(token, bsc)
if err != nil {
return "", err
}
// Prepare reply
sbsr := pi.SetBillingStatusReply{
Timestamp: bsc.Timestamp,
Receipt: bsc.Receipt,
}
reply, err := json.Marshal(sbsr)
if err != nil {
return "", err
}
return string(reply), nil
}
// tokenMatches verifies that the command token (the token for the record that
// this plugin command is being executed on) matches the payload token (the
// token that the plugin command payload contains that is typically used in the
// payload signature). The payload token must be the full length token.
func tokenMatches(cmdToken []byte, payloadToken string) error {
pt, err := tokenDecode(payloadToken)
if err != nil {
return backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(pi.ErrorCodeTokenInvalid),
ErrorContext: util.TokenRegexp(),
}
}
if !bytes.Equal(cmdToken, pt) {
return backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(pi.ErrorCodeTokenInvalid),
ErrorContext: fmt.Sprintf("payload token does not "+
"match command token: got %x, want %x",
pt, cmdToken),
}
}
return nil
}
// cmdBillingStatusChanges returns the billing status changes of a proposal.
func (p *piPlugin) cmdBillingStatusChanges(token []byte) (string, error) {
// Get billing status changes
bscs, err := p.billingStatusChanges(token)
if err != nil {
return "", err
}
// Prepare reply
bscsr := pi.BillingStatusChangesReply{
BillingStatusChanges: bscs,
}
reply, err := json.Marshal(bscsr)
if err != nil {
return "", err
}
return string(reply), nil
}
// cmdSummary returns the pi summary of a proposal.
func (p *piPlugin) cmdSummary(token []byte) (string, error) {
// Get the proposal status
propStatus, err := p.getProposalStatus(token)
if err != nil {
return "", err
}
// Prepare the reply
sr := pi.SummaryReply{
Summary: pi.ProposalSummary{
Status: propStatus,
},
}
reply, err := json.Marshal(sr)
if err != nil {
return "", err
}
return string(reply), nil
}
// statusChangeReason returns the last status change reason of a proposal.
// This function assumes the proposal has at least one status change.
func (p *piPlugin) lastStatusChangeReason(metadata []backend.MetadataStream) (string, error) {
// Decode status changes
statusChanges, err := statusChangesDecode(metadata)
if err != nil {
return "", err
}
// Return latest status change reason
return statusChanges[len(statusChanges)-1].Reason, nil
}
// statusChangesDecode decodes and returns the StatusChangeMetadata from the
// metadata streams if one is present.
func statusChangesDecode(metadata []backend.MetadataStream) ([]usermd.StatusChangeMetadata, error) {
statuses := make([]usermd.StatusChangeMetadata, 0, 16)
for _, v := range metadata {
if v.PluginID != usermd.PluginID ||
v.StreamID != usermd.StreamIDStatusChanges {
// Not the mdstream we're looking for
continue
}
d := json.NewDecoder(strings.NewReader(v.Payload))
for {
var sc usermd.StatusChangeMetadata
err := d.Decode(&sc)
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
statuses = append(statuses, sc)
}
break
}
return statuses, nil
}
// proposalStatusApproved returns the proposal status of an approved proposal.
func proposalStatusApproved(voteMD *ticketvote.VoteMetadata, bscs []pi.BillingStatusChange) (pi.PropStatusT, error) {
// If the proposal in an RFP then we don't need to
// check the billing status changes. RFP proposals
// do not bill against the treasury. This does not
// apply to RFP submission proposals.
if isRFP(voteMD) {
return pi.PropStatusApproved, nil
}
// Use the billing status to determine the proposal status.
bs := proposalBillingStatus(ticketvote.VoteStatusApproved, bscs)
switch bs {
case pi.BillingStatusClosed:
return pi.PropStatusClosed, nil
case pi.BillingStatusCompleted:
return pi.PropStatusCompleted, nil
case pi.BillingStatusActive:
return pi.PropStatusActive, nil
}
// Shouldn't happen return an error
return pi.PropStatusInvalid,
errors.Errorf(
"couldn't determine proposal status of an approved propsoal: "+
"billingStatus: %v", bs)
}
// proposalBillingStatus accepts proposal's vote status with the billing status
// changes and returns the proposal's billing status.
func proposalBillingStatus(vs ticketvote.VoteStatusT, bscs []pi.BillingStatusChange) pi.BillingStatusT {
// If proposal vote wasn't approved,
// return invalid billing status.
if vs != ticketvote.VoteStatusApproved {
return pi.BillingStatusInvalid
}
var bs pi.BillingStatusT
if len(bscs) == 0 {
// Proposals that have been approved, but have not had
// their billing status set yet are considered to be
// active.
bs = pi.BillingStatusActive
} else {
// Use the status from the most recent billing status
// change.
bs = bscs[len(bscs)-1].Status
}
return bs
}
// proposalStatus combines record metadata and plugin metadata in order to
// create a unified map of the various paths a proposal can take throughout
// the proposal process.
func proposalStatus(state backend.StateT, status backend.StatusT, voteStatus ticketvote.VoteStatusT, voteMD *ticketvote.VoteMetadata, bscs []pi.BillingStatusChange) (pi.PropStatusT, error) {
switch state {
case backend.StateUnvetted:
switch status {
case backend.StatusUnreviewed:
return pi.PropStatusUnvetted, nil
case backend.StatusArchived:
return pi.PropStatusUnvettedAbandoned, nil
case backend.StatusCensored:
return pi.PropStatusUnvettedCensored, nil
}
case backend.StateVetted:
switch status {
case backend.StatusArchived:
return pi.PropStatusAbandoned, nil
case backend.StatusCensored:
return pi.PropStatusCensored, nil
case backend.StatusPublic:
switch voteStatus {
case ticketvote.VoteStatusUnauthorized:
return pi.PropStatusUnderReview, nil
case ticketvote.VoteStatusAuthorized:
return pi.PropStatusVoteAuthorized, nil
case ticketvote.VoteStatusStarted:
return pi.PropStatusVoteStarted, nil
case ticketvote.VoteStatusRejected:
return pi.PropStatusRejected, nil
case ticketvote.VoteStatusApproved:
return proposalStatusApproved(voteMD, bscs)
}
}
}
// Shouldn't happen return an error
return pi.PropStatusInvalid,
errors.Errorf(
"couldn't determine proposal status: proposal state: %v, "+
"proposal status %v, vote status: %v", state, status, voteStatus)
}
// record returns a record from the backend with it's contents filtered
// according to the provided record request.
//
// A backend ErrRecordNotFound error is returned if the record is not found.
func (p *piPlugin) record(rr backend.RecordRequest) (*backend.Record, error) {
if rr.Token == nil {
return nil, errors.Errorf("token not provided")
}
reply, err := p.backend.Records([]backend.RecordRequest{rr})
if err != nil {
return nil, err
}
r, ok := reply[hex.EncodeToString(rr.Token)]
if !ok {
return nil, backend.ErrRecordNotFound
}
return &r, nil
}
// recordAbridged returns a record with all files omitted.
//
// A backend ErrRecordNotFound error is returned if the record is not found.
func (p *piPlugin) recordAbridged(token []byte) (*backend.Record, error) {
rr := backend.RecordRequest{
Token: token,
OmitAllFiles: true,
}
return p.record(rr)
}
// convertSignatureError converts a util SignatureError to a backend
// PluginError that contains a pi plugin error code.
func convertSignatureError(err error) backend.PluginError {
var e util.SignatureError
var s pi.ErrorCodeT
if errors.As(err, &e) {
switch e.ErrorCode {
case util.ErrorStatusPublicKeyInvalid:
s = pi.ErrorCodePublicKeyInvalid
case util.ErrorStatusSignatureInvalid:
s = pi.ErrorCodeSignatureInvalid
}
}
return backend.PluginError{
PluginID: pi.PluginID,
ErrorCode: uint32(s),
ErrorContext: e.ErrorContext,
}
}
// billingStatusSave saves a BillingStatusChange to the backend.
func (p *piPlugin) billingStatusSave(token []byte, bsc pi.BillingStatusChange) error {
// Prepare blob
be, err := billingStatusEncode(bsc)
if err != nil {
return err
}
// Save blob
return p.tstore.BlobSave(token, *be)
}
// billingStatusChanges returns the billing status changes of a proposal.
func (p *piPlugin) billingStatusChanges(token []byte) ([]pi.BillingStatusChange, error) {
// Retrieve blobs
blobs, err := p.tstore.BlobsByDataDesc(token,
[]string{dataDescriptorBillingStatus})
if err != nil {
return nil, err
}
// Decode blobs
statusChanges := make([]pi.BillingStatusChange, 0, len(blobs))
for _, v := range blobs {
a, err := billingStatusDecode(v)
if err != nil {
return nil, err
}
statusChanges = append(statusChanges, *a)
}
// Sanity check. They should already be sorted from oldest to
// newest.
sort.SliceStable(statusChanges, func(i, j int) bool {
return statusChanges[i].Timestamp < statusChanges[j].Timestamp
})
return statusChanges, nil
}
// billingStatusEncode encodes a BillingStatusChange into a BlobEntry.
func billingStatusEncode(bsc pi.BillingStatusChange) (*store.BlobEntry, error) {
data, err := json.Marshal(bsc)
if err != nil {
return nil, err
}
hint, err := json.Marshal(
store.DataDescriptor{
Type: store.DataTypeStructure,
Descriptor: dataDescriptorBillingStatus,
})
if err != nil {
return nil, err
}
be := store.NewBlobEntry(hint, data)
return &be, nil
}
// billingStatusDecode decodes a BlobEntry into a BillingStatusChange.
func billingStatusDecode(be store.BlobEntry) (*pi.BillingStatusChange, error) {
// Decode and validate data hint
b, err := base64.StdEncoding.DecodeString(be.DataHint)
if err != nil {
return nil, fmt.Errorf("decode DataHint: %v", err)
}
var dd store.DataDescriptor
err = json.Unmarshal(b, &dd)
if err != nil {
return nil, fmt.Errorf("unmarshal DataHint: %v", err)
}
if dd.Descriptor != dataDescriptorBillingStatus {
return nil, fmt.Errorf("unexpected data descriptor: got %v, "+
"want %v", dd.Descriptor, dataDescriptorBillingStatus)
}
// Decode data
b, err = base64.StdEncoding.DecodeString(be.Data)
if err != nil {
return nil, fmt.Errorf("decode Data: %v", err)
}
digest, err := hex.DecodeString(be.Digest)
if err != nil {
return nil, fmt.Errorf("decode digest: %v", err)
}
if !bytes.Equal(util.Digest(b), digest) {
return nil, fmt.Errorf("data is not coherent; got %x, want %x",
util.Digest(b), digest)
}
var bsc pi.BillingStatusChange
err = json.Unmarshal(b, &bsc)
if err != nil {
return nil, fmt.Errorf("unmarshal AuthDetails: %v", err)
}
return &bsc, nil
}