/
proposals.go
2009 lines (1736 loc) · 51.3 KB
/
proposals.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2017-2019 The Bitum developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/bitum-project/bitumtime/merkle"
"github.com/bitum-project/politeia/bitumplugin"
pd "github.com/bitum-project/politeia/politeiad/api/v1"
"github.com/bitum-project/politeia/politeiad/api/v1/identity"
"github.com/bitum-project/politeia/politeiad/cache"
www "github.com/bitum-project/politeia/politeiawww/api/www/v1"
"github.com/bitum-project/politeia/politeiawww/user"
"github.com/bitum-project/politeia/util"
)
const (
// indexFile contains the file name of the index file
indexFile = "index.md"
// mdStream* indicate the metadata stream used for various types
mdStreamGeneral = 0 // General information for this proposal
mdStreamChanges = 2 // Changes to record
// Note that 14 is in use by the bitum plugin
// Note that 15 is in use by the bitum plugin
VersionMDStreamChanges = 1
BackendProposalMetadataVersion = 1
)
type MDStreamChanges struct {
Version uint `json:"version"` // Version of the struct
AdminPubKey string `json:"adminpubkey"` // Identity of the administrator
NewStatus pd.RecordStatusT `json:"newstatus"` // NewStatus
StatusChangeMessage string `json:"statuschangemessage,omitempty"` // Status change message
Timestamp int64 `json:"timestamp"` // Timestamp of the change
}
type BackendProposalMetadata struct {
Version uint64 `json:"version"` // BackendProposalMetadata version
Timestamp int64 `json:"timestamp"` // Last update of proposal
Name string `json:"name"` // Generated proposal name
PublicKey string `json:"publickey"` // Key used for signature.
Signature string `json:"signature"` // Signature of merkle root
}
// proposalStats is used to provide a summary of the number of proposals
// grouped by proposal status.
type proposalsSummary struct {
Invalid int
NotReviewed int
Censored int
Public int
UnreviewedChanges int
Abandoned int
}
// proposalsFilter is used to pass filtering parameters into the filterProps
// function.
type proposalsFilter struct {
After string
Before string
UserID string
StateMap map[www.PropStateT]bool
}
type VoteDetails struct {
AuthorizeVote www.AuthorizeVote // Authorize vote
AuthorizeVoteReply www.AuthorizeVoteReply // Authorize vote reply
StartVote www.StartVote // Start vote
StartVoteReply www.StartVoteReply // Start vote reply
}
// encodeBackendProposalMetadata encodes BackendProposalMetadata into a JSON
// byte slice.
func encodeBackendProposalMetadata(md BackendProposalMetadata) ([]byte, error) {
b, err := json.Marshal(md)
if err != nil {
return nil, err
}
return b, nil
}
// decodeBackendProposalMetadata decodes a JSON byte slice into a
// BackendProposalMetadata.
func decodeBackendProposalMetadata(payload []byte) (*BackendProposalMetadata, error) {
var md BackendProposalMetadata
err := json.Unmarshal(payload, &md)
if err != nil {
return nil, err
}
return &md, nil
}
// encodeMDStreamChanges encodes an MDStreamChanges into a JSON byte slice.
func encodeMDStreamChanges(m MDStreamChanges) ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
return b, nil
}
// decodeMDStreamChanges decodes a JSON byte slice into a slice of
// MDStreamChanges.
func decodeMDStreamChanges(payload []byte) ([]MDStreamChanges, error) {
var msc []MDStreamChanges
d := json.NewDecoder(strings.NewReader(string(payload)))
for {
var m MDStreamChanges
err := d.Decode(&m)
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
msc = append(msc, m)
}
return msc, nil
}
// validateVoteBit ensures that bit is a valid vote bit.
func validateVoteBit(vote www.Vote, bit uint64) error {
if len(vote.Options) == 0 {
return fmt.Errorf("vote corrupt")
}
if bit == 0 {
return fmt.Errorf("invalid bit 0x%x", bit)
}
if vote.Mask&bit != bit {
return fmt.Errorf("invalid mask 0x%x bit 0x%x",
vote.Mask, bit)
}
for _, v := range vote.Options {
if v.Bits == bit {
return nil
}
}
return fmt.Errorf("bit not found 0x%x", bit)
}
// validateProposal ensures that a submitted proposal hashes, merkle and
// signarures are valid.
func validateProposal(np www.NewProposal, u *user.User) error {
log.Tracef("validateProposal")
// Obtain signature
sig, err := util.ConvertSignature(np.Signature)
if err != nil {
return www.UserError{
ErrorCode: www.ErrorStatusInvalidSignature,
}
}
// Verify public key
id, err := checkPublicKey(u, np.PublicKey)
if err != nil {
return err
}
pk, err := identity.PublicIdentityFromBytes(id[:])
if err != nil {
return err
}
// Check for at least 1 markdown file with a non-empty payload.
if len(np.Files) == 0 || np.Files[0].Payload == "" {
return www.UserError{
ErrorCode: www.ErrorStatusProposalMissingFiles,
}
}
// verify if there are duplicate names
filenames := make(map[string]int, len(np.Files))
// Check that the file number policy is followed.
var (
numMDs, numImages, numIndexFiles int
mdExceedsMaxSize, imageExceedsMaxSize bool
hashes []*[sha256.Size]byte
)
for _, v := range np.Files {
filenames[v.Name]++
var (
data []byte
err error
)
if strings.HasPrefix(v.MIME, "image/") {
numImages++
data, err = base64.StdEncoding.DecodeString(v.Payload)
if err != nil {
return err
}
if len(data) > www.PolicyMaxImageSize {
imageExceedsMaxSize = true
}
} else {
numMDs++
if v.Name == indexFile {
numIndexFiles++
}
data, err = base64.StdEncoding.DecodeString(v.Payload)
if err != nil {
return err
}
if len(data) > www.PolicyMaxMDSize {
mdExceedsMaxSize = true
}
}
// Append digest to array for merkle root calculation
digest := util.Digest(data)
var d [sha256.Size]byte
copy(d[:], digest)
hashes = append(hashes, &d)
}
// verify duplicate file names
if len(np.Files) > 1 {
var repeated []string
for name, count := range filenames {
if count > 1 {
repeated = append(repeated, name)
}
}
if len(repeated) > 0 {
return www.UserError{
ErrorCode: www.ErrorStatusProposalDuplicateFilenames,
ErrorContext: repeated,
}
}
}
// we expect one index file
if numIndexFiles == 0 {
return www.UserError{
ErrorCode: www.ErrorStatusProposalMissingFiles,
ErrorContext: []string{indexFile},
}
}
if numMDs > www.PolicyMaxMDs {
return www.UserError{
ErrorCode: www.ErrorStatusMaxMDsExceededPolicy,
}
}
if numImages > www.PolicyMaxImages {
return www.UserError{
ErrorCode: www.ErrorStatusMaxImagesExceededPolicy,
}
}
if mdExceedsMaxSize {
return www.UserError{
ErrorCode: www.ErrorStatusMaxMDSizeExceededPolicy,
}
}
if imageExceedsMaxSize {
return www.UserError{
ErrorCode: www.ErrorStatusMaxImageSizeExceededPolicy,
}
}
// proposal title validation
name, err := getProposalName(np.Files)
if err != nil {
return err
}
if !util.IsValidProposalName(name) {
return www.UserError{
ErrorCode: www.ErrorStatusProposalInvalidTitle,
ErrorContext: []string{util.CreateProposalNameRegex()},
}
}
// Note that we need validate the string representation of the merkle
mr := merkle.Root(hashes)
if !pk.VerifyMessage([]byte(hex.EncodeToString(mr[:])), sig) {
return www.UserError{
ErrorCode: www.ErrorStatusInvalidSignature,
}
}
return nil
}
// voteIsAuthorized returns whether the author of the proposal has authorized
// an admin to start the voting period for the proposal.
func voteIsAuthorized(avr www.AuthorizeVoteReply) bool {
if avr.Receipt == "" {
// Vote has not been authorized yet
return false
} else if avr.Action == www.AuthVoteActionRevoke {
// Vote authorization was revoked
return false
}
return true
}
// getVoteStatus returns the status for the provided vote.
func getVoteStatus(avr www.AuthorizeVoteReply, svr www.StartVoteReply, bestBlock uint64) www.PropVoteStatusT {
if svr.StartBlockHeight == "" {
// Vote has not started. Check if it's been authorized yet.
if voteIsAuthorized(avr) {
return www.PropVoteStatusAuthorized
} else {
return www.PropVoteStatusNotAuthorized
}
}
// Vote has at least been started. Check if it has finished.
ee, err := strconv.ParseUint(svr.EndHeight, 10, 64)
if err != nil {
// This should not happen
log.Errorf("getVoteStatus: ParseUint failed on '%v': %v",
svr.EndHeight, err)
return www.PropVoteStatusInvalid
}
if bestBlock >= ee {
return www.PropVoteStatusFinished
}
return www.PropVoteStatusStarted
}
func voteStatusFromVoteSummary(r bitumplugin.VoteSummaryReply, bestBlock uint64) www.PropVoteStatusT {
switch {
case !r.Authorized:
return www.PropVoteStatusNotAuthorized
case r.EndHeight == "":
return www.PropVoteStatusAuthorized
default:
endHeight, err := strconv.ParseUint(r.EndHeight, 10, 64)
if err != nil {
// This should not happen
log.Errorf("voteStatusFromVoteSummary: ParseUint "+
"failed on '%v': %v", r.EndHeight, err)
}
if bestBlock < endHeight {
return www.PropVoteStatusStarted
}
return www.PropVoteStatusFinished
}
}
// getProposalName returns the proposal name based on the index markdown file.
func getProposalName(files []www.File) (string, error) {
for _, file := range files {
if file.Name == indexFile {
return util.GetProposalName(file.Payload)
}
}
return "", nil
}
// convertWWWPropCreditFromDatabasePropCredit coverts a database proposal
// credit to a v1 proposal credit.
func convertWWWPropCreditFromDatabasePropCredit(credit user.ProposalCredit) www.ProposalCredit {
return www.ProposalCredit{
PaywallID: credit.PaywallID,
Price: credit.Price,
DatePurchased: credit.DatePurchased,
TxID: credit.TxID,
}
}
// getProp gets the most recent verions of the given proposal from the cache
// then fills in any missing fields before returning the proposal.
func (p *politeiawww) getProp(token string) (*www.ProposalRecord, error) {
log.Tracef("getProp: %v", token)
r, err := p.cache.Record(token)
if err != nil {
return nil, err
}
pr := convertPropFromCache(*r)
// Find the number of comments for the proposal
dc, err := p.bitumGetComments(token)
if err != nil {
log.Errorf("getProp: bitumGetComments failed "+
"for token %v", token)
}
pr.NumComments = uint(len(dc))
p.RLock()
defer p.RUnlock()
// Fill in proposal author info
userID, ok := p.userPubkeys[pr.PublicKey]
if !ok {
log.Errorf("getProp: userID lookup failed for "+
"token:%v pubkey:%v", token, pr.PublicKey)
}
pr.UserId = userID
pr.Username = p.getUsernameById(userID)
return &pr, nil
}
// getPropVersion gets a specific version of a proposal from the cache then
// fills in any misssing fields before returning the proposal.
func (p *politeiawww) getPropVersion(token, version string) (*www.ProposalRecord, error) {
log.Tracef("getPropVersion: %v %v", token, version)
r, err := p.cache.RecordVersion(token, version)
if err != nil {
return nil, err
}
pr := convertPropFromCache(*r)
// Fetch number of comments for proposal from cache
dc, err := p.bitumGetComments(token)
if err != nil {
log.Errorf("getPropVersion: bitumGetComments "+
"failed for token %v", token)
}
pr.NumComments = uint(len(dc))
p.RLock()
defer p.RUnlock()
// Fill in proposal author info
userID, ok := p.userPubkeys[pr.PublicKey]
if !ok {
log.Errorf("getPropVersion: user not found for "+
"pubkey:%v token:%v", pr.PublicKey, token)
}
pr.UserId = userID
pr.Username = p.getUsernameById(userID)
return &pr, nil
}
// getAllProps gets the latest version of all proposals from the cache then
// fills any missing fields before returning the proposals.
func (p *politeiawww) getAllProps() ([]www.ProposalRecord, error) {
log.Tracef("getAllProps")
// Get proposals from cache
records, err := p.cache.Inventory()
if err != nil {
return nil, err
}
// Fill in the number of comments for each proposal
props := make([]www.ProposalRecord, 0, len(records))
for _, v := range records {
pr := convertPropFromCache(v)
dc, err := p.bitumGetComments(pr.CensorshipRecord.Token)
if err != nil {
log.Errorf("getAllProps: bitumGetComments failed "+
"for token %v", pr.CensorshipRecord.Token)
}
pr.NumComments = uint(len(dc))
props = append(props, pr)
}
p.RLock()
defer p.RUnlock()
// Fill in author info for each proposal. Cache usernames to
// prevent duplicate database lookups.
usernames := make(map[string]string, len(props)) // [userID]username
for i, pr := range props {
userID, ok := p.userPubkeys[pr.PublicKey]
if !ok {
log.Errorf("getAllProps: userID lookup failed for "+
"token:%v pubkey:%v", pr.CensorshipRecord.Token,
pr.PublicKey)
}
pr.UserId = userID
u, ok := usernames[userID]
if !ok {
u = p.getUsernameById(userID)
usernames[userID] = u
}
pr.Username = u
props[i] = pr
}
return props, nil
}
// filterProps filters the given proposals according to the filtering
// parameters specified by the passed in proposalsFilter. filterProps will
// only return a single page of proposals regardless of how many proposals are
// passed in.
func filterProps(filter proposalsFilter, all []www.ProposalRecord) []www.ProposalRecord {
log.Tracef("filterProps")
sort.Slice(all, func(i, j int) bool {
// Sort by older timestamp first, if timestamps are different
// from each other
if all[i].Timestamp != all[j].Timestamp {
return all[i].Timestamp < all[j].Timestamp
}
// Otherwise sort by token
return all[i].CensorshipRecord.Token >
all[j].CensorshipRecord.Token
})
// pageStarted stores whether or not it's okay to start adding
// proposals to the array. If the after or before parameter is
// supplied, we must find the beginning (or end) of the page first.
pageStarted := (filter.After == "" && filter.Before == "")
beforeIdx := -1
proposals := make([]www.ProposalRecord, 0, len(all))
// Iterate in reverse order because they're sorted by oldest
// timestamp first.
for i := len(all) - 1; i >= 0; i-- {
proposal := all[i]
// Filter by user if it's provided.
if (filter.UserID != "") && (filter.UserID != proposal.UserId) {
continue
}
// Filter by the state.
if val, ok := filter.StateMap[proposal.State]; !ok || !val {
continue
}
if pageStarted {
proposals = append(proposals, proposal)
if len(proposals) >= www.ProposalListPageSize {
break
}
} else if filter.After != "" {
// The beginning of the page has been found, so
// the next public proposal is added.
pageStarted = proposal.CensorshipRecord.Token == filter.After
} else if filter.Before != "" {
// The end of the page has been found, so we'll
// have to iterate in the other direction to
// add the proposals; save the current index.
if proposal.CensorshipRecord.Token == filter.Before {
beforeIdx = i
break
}
}
}
// If beforeIdx is set, the caller is asking for vetted proposals
// whose last result is before the provided proposal.
if beforeIdx >= 0 {
for _, proposal := range all[beforeIdx+1:] {
// Filter by user if it's provided.
if (filter.UserID != "") && (filter.UserID != proposal.UserId) {
continue
}
// Filter by the state.
if val, ok := filter.StateMap[proposal.State]; !ok || !val {
continue
}
// The iteration direction is oldest -> newest,
// so proposals are prepended to the array so
// the result will be newest -> oldest.
proposals = append([]www.ProposalRecord{proposal},
proposals...)
if len(proposals) >= www.ProposalListPageSize {
break
}
}
}
return proposals
}
// getUserProps gets the latest version of all proposals from the cache and
// then filters the proposals according to the specified proposalsFilter, which
// is required to contain a userID. In addition to a page of filtered user
// proposals, this function also returns summary statistics for all of the
// proposals that the user has submitted grouped by proposal status.
func (p *politeiawww) getUserProps(filter proposalsFilter) ([]www.ProposalRecord, *proposalsSummary, error) {
log.Tracef("getUserProps: %v", filter.UserID)
if filter.UserID == "" {
return nil, nil, fmt.Errorf("filter missing userID")
}
// Get the latest version of all proposals from the cache
all, err := p.getAllProps()
if err != nil {
return nil, nil, fmt.Errorf("getAllProps: %v", err)
}
// Find proposal summary statistics for the user. This
// includes statistics on ALL of the proposals that the user
// has submitted. Not just the single page of proposals that
// is going to be returned.
var ps proposalsSummary
for _, v := range all {
if v.UserId != filter.UserID {
continue
}
switch v.Status {
case www.PropStatusNotReviewed:
ps.NotReviewed++
case www.PropStatusCensored:
ps.Censored++
case www.PropStatusPublic:
ps.Public++
case www.PropStatusUnreviewedChanges:
ps.UnreviewedChanges++
case www.PropStatusAbandoned:
ps.Abandoned++
default:
ps.Invalid++
}
}
// Filter proposals according to the proposalsFilter. Only
// a single page of proposals will be returned.
filtered := filterProps(filter, all)
return filtered, &ps, nil
}
func (p *politeiawww) getPropComments(token string) ([]www.Comment, error) {
log.Tracef("getPropComments: %v", token)
dc, err := p.bitumGetComments(token)
if err != nil {
return nil, fmt.Errorf("bitumGetComments: %v", err)
}
p.RLock()
defer p.RUnlock()
// Fill in politeiawww data. Cache usernames to reduce
// database lookups.
comments := make([]www.Comment, 0, len(dc))
usernames := make(map[string]string, len(dc)) // [userID]username
for _, v := range dc {
c := convertCommentFromBitum(v)
// Fill in author info
userID, ok := p.userPubkeys[c.PublicKey]
if !ok {
log.Errorf("getPropComments: userID lookup failed "+
"pubkey:%v token:%v comment:%v", c.PublicKey,
c.Token, c.CommentID)
}
u, ok := usernames[userID]
if !ok && userID != "" {
u = p.getUsernameById(userID)
usernames[userID] = u
}
c.UserID = userID
c.Username = u
// Fill in result votes
score, ok := p.commentScores[c.Token+c.CommentID]
if !ok {
log.Errorf("getPropComments: comment score lookup failed"+
"pubkey:%v token:%v comment:%v", c.PublicKey, c.Token,
c.CommentID)
}
c.ResultVotes = score
comments = append(comments, c)
}
return comments, nil
}
// processNewProposal tries to submit a new proposal to politeiad.
func (p *politeiawww) processNewProposal(np www.NewProposal, user *user.User) (*www.NewProposalReply, error) {
log.Tracef("processNewProposal")
if !p.HasUserPaid(user) {
return nil, www.UserError{
ErrorCode: www.ErrorStatusUserNotPaid,
}
}
if !p.UserHasProposalCredits(user) {
return nil, www.UserError{
ErrorCode: www.ErrorStatusNoProposalCredits,
}
}
err := validateProposal(np, user)
if err != nil {
return nil, err
}
// Assemble metadata record
name, err := getProposalName(np.Files)
if err != nil {
return nil, err
}
md, err := encodeBackendProposalMetadata(BackendProposalMetadata{
Version: BackendProposalMetadataVersion,
Timestamp: time.Now().Unix(),
Name: name,
PublicKey: np.PublicKey,
Signature: np.Signature,
})
if err != nil {
return nil, err
}
// Setup politeiad request
challenge, err := util.Random(pd.ChallengeSize)
if err != nil {
return nil, err
}
n := pd.NewRecord{
Challenge: hex.EncodeToString(challenge),
Metadata: []pd.MetadataStream{{
ID: mdStreamGeneral,
Payload: string(md),
}},
Files: convertPropFilesFromWWW(np.Files),
}
// Send politeiad request
responseBody, err := p.makeRequest(http.MethodPost,
pd.NewRecordRoute, n)
if err != nil {
return nil, err
}
log.Infof("Submitted proposal name: %v", name)
for k, f := range n.Files {
log.Infof("%02v: %v %v", k, f.Name, f.Digest)
}
// Handle response
var pdReply pd.NewRecordReply
err = json.Unmarshal(responseBody, &pdReply)
if err != nil {
return nil, fmt.Errorf("Unmarshal NewProposalReply: %v", err)
}
err = util.VerifyChallenge(p.cfg.Identity, challenge, pdReply.Response)
if err != nil {
return nil, err
}
cr := convertPropCensorFromPD(pdReply.CensorshipRecord)
// Deduct proposal credit from user account
err = p.SpendProposalCredit(user, cr.Token)
if err != nil {
return nil, err
}
// Fire off new proposal event
p.fireEvent(EventTypeProposalSubmitted,
EventDataProposalSubmitted{
CensorshipRecord: &cr,
ProposalName: name,
User: user,
},
)
return &www.NewProposalReply{
CensorshipRecord: cr,
}, nil
}
// processProposalDetails fetches a specific proposal version from the records
// cache and returns it.
func (p *politeiawww) processProposalDetails(propDetails www.ProposalsDetails, user *user.User) (*www.ProposalDetailsReply, error) {
log.Tracef("processProposalDetails")
// Version is an optional query param. Fetch latest version
// when query param is not specified.
var prop *www.ProposalRecord
var err error
if propDetails.Version == "" {
prop, err = p.getProp(propDetails.Token)
} else {
prop, err = p.getPropVersion(propDetails.Token, propDetails.Version)
}
if err != nil {
if err == cache.ErrRecordNotFound {
err = www.UserError{
ErrorCode: www.ErrorStatusProposalNotFound,
}
}
return nil, err
}
// Setup reply
reply := www.ProposalDetailsReply{
Proposal: *prop,
}
// Vetted proposals are viewable by everyone. The contents of
// an unvetted proposal is only viewable by admins and the
// proposal author. Unvetted proposal metadata is viewable by
// everyone.
if prop.State == www.PropStateUnvetted {
var isAuthor bool
var isAdmin bool
// This is a public route so a user may not exist
if user != nil {
isAdmin = user.Admin
isAuthor = (prop.UserId == user.ID.String())
}
// Strip the non-public proposal contents if user is
// not the author or an admin
if !isAuthor && !isAdmin {
reply.Proposal.Name = ""
reply.Proposal.Files = make([]www.File, 0)
}
}
return &reply, nil
}
// verifyStatusChange verifies that the proposal status change is a valid
// status transition. This only applies to manual status transitions that are
// initiated by an admin. It does not apply to status changes that are caused
// by editing a proposal.
func verifyStatusChange(current, next www.PropStatusT) error {
var err error
switch {
case current == www.PropStatusNotReviewed &&
(next == www.PropStatusCensored ||
next == www.PropStatusPublic):
// allowed; continue
case current == www.PropStatusUnreviewedChanges &&
(next == www.PropStatusCensored ||
next == www.PropStatusPublic):
// allowed; continue
case current == www.PropStatusPublic &&
next == www.PropStatusAbandoned:
// allowed; continue
default:
err = www.UserError{
ErrorCode: www.ErrorStatusInvalidPropStatusTransition,
}
}
return err
}
// processSetProposalStatus changes the status of an existing proposal.
func (p *politeiawww) processSetProposalStatus(sps www.SetProposalStatus, u *user.User) (*www.SetProposalStatusReply, error) {
log.Tracef("processSetProposalStatus %v", sps.Token)
// Ensure the status change message is not blank if the
// proposal is being censored or abandoned.
if sps.StatusChangeMessage == "" &&
(sps.ProposalStatus == www.PropStatusCensored ||
sps.ProposalStatus == www.PropStatusAbandoned) {
return nil, www.UserError{
ErrorCode: www.ErrorStatusChangeMessageCannotBeBlank,
}
}
// Validate public key
if u.PublicKey() != sps.PublicKey {
return nil, www.UserError{
ErrorCode: www.ErrorStatusInvalidSigningKey,
}
}
// Validate signature
msg := sps.Token + strconv.Itoa(int(sps.ProposalStatus)) +
sps.StatusChangeMessage
err := checkSignature(u.ActiveIdentity().Key[:], sps.Signature, msg)
if err != nil {
return nil, err
}
// Get proposal from cache
pr, err := p.getProp(sps.Token)
if err != nil {
if err == cache.ErrRecordNotFound {
err = www.UserError{
ErrorCode: www.ErrorStatusProposalNotFound,
}
}
return nil, err
}
// The only time admins are allowed to change the status of
// their own proposals is on testnet
if !p.cfg.TestNet {
authorID, ok := p.getUserIDByPubKey(pr.PublicKey)
if !ok {
return nil, fmt.Errorf("user not found for public key %v for "+
"proposal %v", pr.PublicKey, pr.CensorshipRecord.Token)
}
if authorID == u.ID.String() {
return nil, www.UserError{
ErrorCode: www.ErrorStatusReviewerAdminEqualsAuthor,
}
}
}
// Create change record
newStatus := convertPropStatusFromWWW(sps.ProposalStatus)
blob, err := json.Marshal(MDStreamChanges{
Version: VersionMDStreamChanges,
Timestamp: time.Now().Unix(),
NewStatus: newStatus,
AdminPubKey: u.PublicKey(),
StatusChangeMessage: sps.StatusChangeMessage,
})
if err != nil {
return nil, err
}
// Create challenge
challenge, err := util.Random(pd.ChallengeSize)
if err != nil {
return nil, err
}
// Ensure status change is allowed
err = verifyStatusChange(pr.Status, sps.ProposalStatus)
if err != nil {
return nil, err
}
var challengeResponse string
switch {
case pr.State == www.PropStateUnvetted:
// Unvetted status change
// Setup request
sus := pd.SetUnvettedStatus{
Token: sps.Token,
Status: newStatus,
Challenge: hex.EncodeToString(challenge),
MDAppend: []pd.MetadataStream{
{
ID: mdStreamChanges,
Payload: string(blob),
},
},
}
// Send unvetted status change request
responseBody, err := p.makeRequest(http.MethodPost,
pd.SetUnvettedStatusRoute, sus)
if err != nil {
return nil, err
}
var susr pd.SetUnvettedStatusReply
err = json.Unmarshal(responseBody, &susr)
if err != nil {
return nil, fmt.Errorf("could not unmarshal "+
"SetUnvettedStatusReply: %v", err)
}
challengeResponse = susr.Response
case pr.State == www.PropStateVetted:
// Vetted status change
// Ensure voting has not been started or authorized yet
vdr, err := p.bitumVoteDetails(pr.CensorshipRecord.Token)
if err != nil {
return nil, fmt.Errorf("bitumVoteDetails: %v", err)
}
vd := convertVoteDetailsReplyFromBitum(*vdr)