-
Notifications
You must be signed in to change notification settings - Fork 1
/
census.go
1489 lines (1425 loc) · 53.4 KB
/
census.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
package main
import (
"context"
"encoding/csv"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/vocdoni/vote-frame/alfafrens"
"github.com/vocdoni/vote-frame/farcasterapi"
"github.com/vocdoni/vote-frame/farcasterapi/neynar"
"github.com/vocdoni/vote-frame/helpers"
"github.com/vocdoni/vote-frame/mongo"
"go.vocdoni.io/dvote/api"
"go.vocdoni.io/dvote/apiclient"
"go.vocdoni.io/dvote/httprouter"
"go.vocdoni.io/dvote/httprouter/apirest"
"go.vocdoni.io/dvote/log"
"go.vocdoni.io/dvote/types"
"go.vocdoni.io/dvote/vochain/state"
)
const (
devMaxElectionSize = 5000
stageMaxElectionSize = 100000
defaultMaxElectionSize = 200000
maxNumOfCsvRecords = 10000
maxBatchParticipants = 8000
maxUsersNamesToReturn = 10000
POAP_CSV_HEADER = "ID,Collection,ENS,Minting Date,Tx Count,Power"
)
var (
// maxElectionSize is the maximum number of participants in an election
maxElectionSize = defaultMaxElectionSize
// ErrNoValidParticipants is returned when no valid participants are found
ErrNoValidParticipants = fmt.Errorf("no valid participants")
// ErrUserNotFoundInFarcaster is returned when a user is not found in the farcaster API
ErrUserNotFoundInFarcaster = fmt.Errorf("user not found in farcaster")
)
// FrameCensusType is a custom type to identify the different types of censuses.
type FrameCensusType int
const (
// FrameCensusTypeAllFarcaster is the default census type and includes all
// the users in the Farcaster network.
FrameCensusTypeAllFarcaster FrameCensusType = iota
// FrameCensusTypeCSV is a census created from a CSV file containing
// Ethereum addresses and weights.
FrameCensusTypeCSV
// FrameCensusTypeChannelGated is a census created from the users who follow
// a specific Warpcast Channel.
FrameCensusTypeChannelGated
// FrameCensusTypeFollowers is a census created from the users who follow a
// specific user in the Farcaster network.
FrameCensusTypeFollowers
// FrameCensusTypeFile is a census created from a file.
FrameCensusTypeFile
// FrameCensusTypeNFT is a census created from the token holders of an NFT
FrameCensusTypeNFT
// FrameCensusTypeERC20 is a census created from the token holders of an ERC20
FrameCensusTypeERC20
// FrameCensusTypeAlfaFrensChannel is a census created from the users who follow a specific AlfaFrens Channel
FrameCensusTypeAlfaFrensChannel
)
// CensusInfo contains the information of a census.
type CensusInfo struct {
Root types.HexBytes `json:"root"`
Url string `json:"uri"`
Size uint64 `json:"size"`
Usernames []string `json:"usernames,omitempty"`
FromTotalAddresses uint32 `json:"fromTotalAddresses,omitempty"`
FarcasterParticipantCount uint32 `json:"farcasterParticipantCount,omitempty"`
Error string `json:"-"`
Progress uint32 `json:"-"` // Progress of the census creation process (0-100)
Type FrameCensusType `json:"-"` // Type of the census
}
// FromFile loads the census information from a file.
func (c *CensusInfo) FromFile(file string) error {
log.Debugw("loading census from file", "file", file)
data, err := os.ReadFile(file)
if err != nil {
return err
}
if err := json.Unmarshal(data, c); err != nil {
return err
}
// Set the type of the census
c.Type = FrameCensusTypeFile
return nil
}
// FarcasterParticipant is a participant in the Farcaster network to be included in the census.
type FarcasterParticipant struct {
PubKey []byte `json:"pubkey"`
Weight *big.Int `json:"weight"`
Username string `json:"username"`
FID uint64 `json:"fid"`
Delegations uint32 `json:"delegations"`
}
// CreateCensus creates a new census from a list of participants.
func CreateCensus(cli *apiclient.HTTPclient, participants []*FarcasterParticipant,
censusType FrameCensusType, progress chan int,
) (*CensusInfo, error) {
censusList := api.CensusParticipants{}
for _, p := range participants {
voterID := state.NewFarcasterVoterID(p.PubKey, p.FID)
censusList.Participants = append(censusList.Participants, api.CensusParticipant{
Key: voterID.Address(),
Weight: (*types.BigInt)(p.Weight),
})
}
if len(censusList.Participants) == 0 {
return nil, ErrNoValidParticipants
}
censusID, err := cli.NewCensus(api.CensusTypeWeighted)
if err != nil {
return nil, err
}
// Add the participants to the census, if the number of participants is less
// than the maxBatchParticipants add them all at once, otherwise split them
// into batches
if len(censusList.Participants) < maxBatchParticipants {
if err := cli.CensusAddParticipants(censusID, &censusList); err != nil {
return nil, err
}
} else {
log.Debugw("max batch participants exceeded", "participants", len(censusList.Participants))
// Split the participants into batches
idxBatch := 0
for i := 0; i < len(censusList.Participants); i += maxBatchParticipants {
to := i + maxBatchParticipants
if to > len(censusList.Participants) {
to = len(censusList.Participants)
}
batch := api.CensusParticipants{Participants: censusList.Participants[i:to]}
if err := cli.CensusAddParticipants(censusID, &batch); err != nil {
return nil, err
}
idxBatch++
log.Debugw("census batch added, sleeping 100ms...", "index", idxBatch, "from", i, "to", to)
time.Sleep(100 * time.Millisecond)
if progress != nil {
progress <- 100 * i / len(censusList.Participants)
}
}
}
// increase the http client timeout to 5 minutes to allow to publish large
// censuses
cli.SetTimeout(5 * time.Minute)
root, url, err := cli.CensusPublish(censusID)
if err != nil {
log.Warnw("failed to publish census", "censusID", censusID, "error", err, "participants", len(censusList.Participants))
return nil, err
}
cli.SetTimeout(apiclient.DefaultTimeout)
size, err := cli.CensusSize(censusID)
if err != nil {
log.Warnw("failed to get census size", "censusID", censusID, "error", err, "participants", len(censusList.Participants))
return nil, err
}
return &CensusInfo{
Root: root,
Url: url,
Size: size,
Type: censusType,
}, nil
}
// censusFromDatabaseByElectionID retrieves a census from the database by its election ID.
func (v *vocdoniHandler) censusFromDatabaseByElectionID(_ *apirest.APIdata, ctx *httprouter.HTTPContext) error {
eID, err := hex.DecodeString(ctx.URLParam("electionID"))
if err != nil {
return err
}
census, err := v.db.CensusFromElection(eID)
if err != nil {
return ctx.Send(nil, http.StatusNotFound)
}
data, err := json.Marshal(census)
if err != nil {
return err
}
return ctx.Send(data, http.StatusOK)
}
// censusFromDatabaseByRoot retrieves a census from the database by its root.
func (v *vocdoniHandler) censusFromDatabaseByRoot(_ *apirest.APIdata, ctx *httprouter.HTTPContext) error {
root, err := hex.DecodeString(ctx.URLParam("root"))
if err != nil {
return err
}
census, err := v.db.CensusFromRoot(root)
if err != nil {
return ctx.Send(nil, http.StatusNotFound)
}
data, err := json.Marshal(census)
if err != nil {
return err
}
return ctx.Send(data, http.StatusOK)
}
type UniqueParticipants map[string]struct {
Weight *big.Int
Participation uint32
}
func (p UniqueParticipants) Add(username string, weight *big.Int, participation uint32) {
if participant, ok := p[username]; ok {
// Create a new big.Int to hold the sum to avoid modifying the original weight.
newWeight := new(big.Int).Add(participant.Weight, weight)
participant.Weight = newWeight
participant.Participation = participation
p[username] = participant // Reassign the modified struct back to the map
} else {
// Make a copy of the weight to avoid sharing the same instance
newWeight := new(big.Int).Set(weight)
p[username] = struct {
Weight *big.Int
Participation uint32
}{Weight: newWeight, Participation: participation}
}
}
// censusCSV creates a new census from a CSV file containing Ethereum addresses and weights.
// It builds the census async and returns the census ID.
func (v *vocdoniHandler) censusCSV(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
censusID, err := v.cli.NewCensus(api.CensusTypeWeighted)
if err != nil {
return err
}
v.backgroundQueue.Store(censusID.String(), CensusInfo{})
userFID, err := v.db.UserFromAuthToken(msg.AuthToken)
if err != nil {
return fmt.Errorf("cannot get user from auth token: %w", err)
}
if err := v.db.AddCensus(censusID, userFID); err != nil {
return fmt.Errorf("cannot add census to database: %w", err)
}
totalCSVaddresses := uint32(0)
go func() {
startTime := time.Now()
log.Debugw("building census from csv", "censusID", censusID)
var participants []*FarcasterParticipant
var err error
v.trackStepProgress(censusID, 1, 2, func(progress chan int) {
participants, totalCSVaddresses, err = v.farcasterCensusFromEthereumCSV(msg.Data, progress)
})
if err != nil {
log.Warnw("failed to build census from ethereum csv", "err", err.Error())
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
var ci *CensusInfo
v.trackStepProgress(censusID, 2, 2, func(progress chan int) {
ci, err = CreateCensus(v.cli, participants, FrameCensusTypeCSV, progress)
})
if err != nil {
log.Errorw(err, "failed to create census")
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
// since each participant can have multiple signers, we need to get the unique usernames
uniqueParticipantsMap := make(UniqueParticipants, len(participants))
totalWeight := new(big.Int).SetUint64(0)
totalParticipants := uint32(0) // including delegations
for _, p := range participants {
if _, ok := uniqueParticipantsMap[p.Username]; ok {
// if the username is already in the map, continue
continue
}
uniqueParticipantsMap.Add(p.Username, p.Weight, p.Delegations+1)
totalWeight.Add(totalWeight, p.Weight)
totalParticipants += p.Delegations + 1
}
uniqueParticipants := []string{}
for k := range uniqueParticipantsMap {
uniqueParticipants = append(uniqueParticipants, k)
}
ci.Usernames = uniqueParticipants
ci.FarcasterParticipantCount = totalParticipants
ci.FromTotalAddresses = totalCSVaddresses
log.Infow("census created from CSV",
"censusID", censusID.String(),
"size", len(ci.Usernames),
"totalWeight", totalWeight.String(),
"duration", time.Since(startTime),
"fromTotalAddresses", totalCSVaddresses,
"fromTotalParticipants", totalParticipants,
)
// store the census info in the map
v.backgroundQueue.Store(censusID.String(), *ci)
// add participants to the census in the database
if err := v.db.AddParticipantsToCensus(censusID, uniqueParticipantsMap, ci.FromTotalAddresses, ci.Url); err != nil {
log.Errorw(err, fmt.Sprintf("failed to add participants to census %s", censusID.String()))
}
}()
data, err := json.Marshal(map[string]string{"censusId": censusID.String()})
if err != nil {
return err
}
return ctx.Send(data, http.StatusOK)
}
// censusChannelExists checks if a Warpcast Channel exists. It returns a NotFound
// error if the channel does not exist. If the channelID is not provided, it
// returns a BadRequest error. If the channel exists, it returns a 200 OK.
func (v *vocdoniHandler) censusChannelExists(_ *apirest.APIdata, ctx *httprouter.HTTPContext) error {
channelID := ctx.URLParam("channelID")
if channelID == "" {
return ctx.Send([]byte("channelID is required"), http.StatusBadRequest)
}
exists, err := v.fcapi.ChannelExists(ctx.Request.Context(), channelID)
if err != nil {
return err
}
if !exists {
return ctx.Send(nil, http.StatusNotFound)
}
return ctx.Send(nil, http.StatusOK)
}
// censusChannel creates a new census that includes the users who follow a
// specific Warpcast Channel. It builds the census async and returns the census
// ID. If no channelID is provided, it returns a BadRequest error. If the
// channel does not exist, it returns a NotFound error. The process of creating
// the census includes fetching the users FIDs from the farcaster API and
// querying the database to get the users signer keys. The census is created
// from the participants and the progress is updated in the queue.
func (v *vocdoniHandler) censusChannel(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// extract userFID from auth token
userFID, err := v.db.UserFromAuthToken(msg.AuthToken)
if err != nil {
return fmt.Errorf("cannot get user from auth token: %w", err)
}
// check if channelID is provided, it is required so if it's not provided
// return a BadRequest error
channelID := ctx.URLParam("channelID")
if channelID == "" {
return ctx.Send([]byte("channelID is required"), http.StatusBadRequest)
}
// check if the channel exists, if not return a NotFound error. If something
// fails when checking the channel existence, return the error.
exists, err := v.fcapi.ChannelExists(ctx.Request.Context(), channelID)
if err != nil {
return err
}
if !exists {
return ctx.Send([]byte("channel not found"), http.StatusNotFound)
}
// create a censusID for the queue and store into it
data, err := v.censusWarpcastChannel(channelID, userFID, nil)
if err != nil {
log.Warnf("error creating census for the chanel: %s: %v", channelID, err)
return ctx.Send([]byte("error creating channel census"), http.StatusInternalServerError)
}
return ctx.Send(data, http.StatusOK)
}
func (v *vocdoniHandler) censusFollowersHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
req := struct {
Profile FarcasterProfile `json:"profile"`
}{}
if err := json.Unmarshal(msg.Data, &req); err != nil {
return err
}
// check if userFid is provided, it is required so if it's not provided
// return a BadRequest error
strUserFid := ctx.URLParam("userFid")
if strUserFid == "" {
return ctx.Send([]byte("userFid is required"), http.StatusBadRequest)
}
userFID, err := strconv.ParseUint(strUserFid, 10, 64)
if err != nil {
return ctx.Send([]byte("invalid userFid"), http.StatusBadRequest)
}
// create the census from the followers of the user and return the data as
// response
data, err := v.censusFollowers(userFID, nil)
if err != nil {
return err
}
return ctx.Send(data, http.StatusOK)
}
// censusAlfafrensChannelHandler creates a new census from the users who follow the AlfaFrens channel of the user
// making the request.
func (v *vocdoniHandler) censusAlfafrensChannelHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// extract userFID from auth token
userFID, err := v.db.UserFromAuthToken(msg.AuthToken)
if err != nil {
return fmt.Errorf("cannot get user from auth token: %w", err)
}
// create a censusID for the queue and store into it
censusID, err := v.cli.NewCensus(api.CensusTypeWeighted)
if err != nil {
return err
}
data, err := v.censusAlfafrensChannel(censusID, userFID)
if err != nil {
log.Warnf("error creating census for alfafrens channel of user: %d: %v", userFID, err)
return ctx.Send([]byte("error creating channel census"), http.StatusInternalServerError)
}
return ctx.Send(data, http.StatusOK)
}
// censusCommunity creates a new census from a community. The census of the
// community can be of type channel, NFT, or ERC20. If the community is a
// channel, the census is created from the users who follow the channel, and
// the process is async. If the community is an NFT or ERC20, the census is
// created from the token holders of the token addresses in the community, using
// the AirStack API. The process is sync and the census is created in the same
// request. The census is created from the participants and the progress is
// updated in the queue.
func (v *vocdoniHandler) censusCommunity(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// extract userFID from auth token
userFID, err := v.db.UserFromAuthToken(msg.AuthToken)
if err != nil {
return fmt.Errorf("cannot get user from auth token: %w", err)
}
req := struct {
CommunityID string `json:"communityID"`
}{}
if err := json.Unmarshal(msg.Data, &req); err != nil {
return err
}
// get the community from the database
community, err := v.db.Community(req.CommunityID)
if err != nil {
return ctx.Send([]byte("error getting community"), http.StatusInternalServerError)
}
if community == nil {
return ctx.Send([]byte("community not found"), http.StatusNotFound)
}
// check if the user is admin of the community
if !v.db.IsCommunityAdmin(userFID, req.CommunityID) {
return fmt.Errorf("user is not an admin of the community")
}
// check if the community is ready (soft check, if it fails, continue)
ready, _, err := v.CommunityStatus(community)
if err != nil {
log.Warnw("error getting community status", "err", err, "community", community.ID)
}
// if the community is not ready, return a PreconditionFailed error
if !ready {
return ctx.Send([]byte("community not ready"), http.StatusPreconditionFailed)
}
// getting the delegations of the community to build the census taking into
// account them
delegations, err := v.db.DelegationsByCommunity(req.CommunityID, true, false)
if err != nil {
return err
}
// check the type to create it from the correct source (channel, airstak
// (nft/erc20) or user followers) and in the correct way (async or sync)
switch community.Census.Type {
case mongo.TypeCommunityCensusFollowers:
// if the census type is followers, create the census from the users who
// follow the user, the process is async so return add the censusID to the
// queue and return it to the client
data, err := v.censusFollowers(userFID, delegations)
if err != nil {
log.Warnf("error creating census for the user: %d: %v", userFID, err)
return ctx.Send([]byte("error creating user followers census"), http.StatusInternalServerError)
}
return ctx.Send(data, http.StatusOK)
case mongo.TypeCommunityCensusChannel:
// if the census type is a channel, create the census from the users who
// follow the channel, the process is async so return add the censusID
// to the queue and return it to the client
data, err := v.censusWarpcastChannel(community.Census.Channel, userFID, delegations)
if err != nil {
log.Warnf("error creating census for the chanel: %s: %v", community.Census.Channel, err)
return ctx.Send([]byte("error creating channel census"), http.StatusInternalServerError)
}
return ctx.Send(data, http.StatusOK)
case mongo.TypeCommunityCensusNFT, mongo.TypeCommunityCensusERC20:
// create the census from the token holders
data, err := v.tokenBasedCensus(community.Census.Strategy, community.Census.Type, userFID, delegations)
if err != nil {
return fmt.Errorf("cannot create erc20/nft based census: %w", err)
}
return ctx.Send(data, http.StatusOK)
default:
return ctx.Send([]byte("invalid census type"), http.StatusBadRequest)
}
}
// censusQueueInfo returns the status of the census creation process.
// Returns 204 if the census is not yet ready or not found.
func (v *vocdoniHandler) censusQueueInfo(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
var censusID types.HexBytes
var err error
censusID, err = hex.DecodeString(ctx.URLParam("censusID"))
if err != nil {
return err
}
iCensusInfo, ok := v.backgroundQueue.Load(censusID.String())
if !ok {
return ctx.Send(nil, http.StatusNotFound)
}
censusInfo, ok := iCensusInfo.(CensusInfo)
if !ok {
return ctx.Send(nil, http.StatusNotFound)
}
if censusInfo.Error != "" {
return ctx.Send([]byte(censusInfo.Error), http.StatusInternalServerError)
}
if len(censusInfo.Usernames) > maxUsersNamesToReturn {
censusInfo.Usernames = nil
}
if censusInfo.Root == nil {
data, err := json.Marshal(map[string]uint32{
"progress": censusInfo.Progress,
})
if err != nil {
return err
}
return ctx.Send(data, http.StatusAccepted)
}
if err = v.db.SetRootForCensus(censusID, censusInfo.Root); err != nil {
return fmt.Errorf("cannot set root for census: %w", err)
}
data, err := json.Marshal(censusInfo)
if err != nil {
return err
}
return ctx.Send(data, http.StatusOK)
}
// tokenBasedCensusBlockchains returns the supported blockchains for token
// based censuses, it queries the census3 API to get the supported blockchains.
func (v *vocdoniHandler) tokenBasedCensusBlockchains(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
info, err := v.census3.Info()
if err != nil {
return ctx.Send([]byte(fmt.Sprintf("error getting blockchains: %v", err)), http.StatusInternalServerError)
}
var blockchains []string
for _, b := range info.SupportedChains {
blockchains = append(blockchains, b.ShortName)
}
data, err := json.Marshal(map[string][]string{"blockchains": blockchains})
if err != nil {
return ctx.Send([]byte(fmt.Sprintf("error encoding blockchains: %v", err)), http.StatusInternalServerError)
}
return ctx.Send(data, http.StatusOK)
}
const (
MAXNFTTokens = 3
MAXERC20Tokens = 1
)
// tokenBasedCensus method creates a new census from the token holders of a
// group of NFTs or a single ERC20 token. The census is created by the census
// strategy ID in Census3 service. The process is async and returns the json
// encoded censusID. It updates the progress in the queue and the result when
// it's ready.
func (v *vocdoniHandler) tokenBasedCensus(strategyID uint64, tokenType string, createdByFID uint64, delegations []*mongo.Delegation) ([]byte, error) {
if v.census3 == nil {
return nil, fmt.Errorf("census3 client not available")
}
censusID, err := v.cli.NewCensus(api.CensusTypeWeighted)
if err != nil {
return nil, err
}
if err := v.db.AddCensus(censusID, createdByFID); err != nil {
return nil, fmt.Errorf("cannot add census to database: %w", err)
}
v.backgroundQueue.Store(censusID.String(), CensusInfo{})
log.Debugw("building token based census", "censusID", censusID)
go func() {
startTime := time.Now()
// get holders for each token
var holders [][]string
var err error
v.trackStepProgress(censusID, 1, 3, func(progress chan int) {
log.Debugw("getting holders from census3", "strategyID", strategyID)
rawHolders, err := v.census3.AllHoldersByStrategy(strategyID, true)
if err != nil {
log.Warnw("failed to build token based census, cannot get holders", "err", err.Error())
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
log.Debugw("holders received from census3", "count", len(rawHolders))
for address, balance := range rawHolders {
holders = append(holders, []string{address.Hex(), balance.String()})
}
})
if err != nil {
log.Warnw("failed to build census, cannot get holders", "err", err.Error())
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
// create census from token holders
var participants []*FarcasterParticipant
v.trackStepProgress(censusID, 2, 3, func(progress chan int) {
log.Debugw("processing holders", "count", len(holders))
participants, _, err = v.processCensusRecords(holders, delegations, progress)
})
if err != nil {
log.Warnw("failed to build census", "err", err.Error())
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
var ci *CensusInfo
v.trackStepProgress(censusID, 3, 3, func(progress chan int) {
if tokenType == mongo.TypeCommunityCensusERC20 {
ci, err = CreateCensus(v.cli, participants, FrameCensusTypeERC20, progress)
} else if tokenType == mongo.TypeCommunityCensusNFT {
ci, err = CreateCensus(v.cli, participants, FrameCensusTypeNFT, progress)
}
})
if err != nil {
log.Errorw(err, "failed to create census")
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
// since each participant can have multiple signers, we need to get the unique usernames
uniqueParticipantsMap := make(UniqueParticipants, len(participants))
totalWeight := new(big.Int).SetUint64(0)
totalParticipants := uint32(0) // including delegations
for _, p := range participants {
if _, ok := uniqueParticipantsMap[p.Username]; ok {
// if the username is already in the map, continue
continue
}
uniqueParticipantsMap.Add(p.Username, p.Weight, p.Delegations+1)
totalWeight.Add(totalWeight, p.Weight)
totalParticipants += p.Delegations + 1
}
uniqueParticipants := []string{}
for k := range uniqueParticipantsMap {
uniqueParticipants = append(uniqueParticipants, k)
}
ci.Usernames = uniqueParticipants
ci.FromTotalAddresses = uint32(len(holders))
ci.FarcasterParticipantCount = totalParticipants
log.Infow("token census based created",
"censusID", censusID.String(),
"size", len(ci.Usernames),
"totalWeight", totalWeight.String(),
"duration", time.Since(startTime),
"totalAddresses", ci.FromTotalAddresses,
"participants", len(ci.Usernames),
"totalParticipants", totalParticipants,
)
// store the census info in the memory map
v.backgroundQueue.Store(censusID.String(), *ci)
// add participants to the census in the database
if err := v.db.AddParticipantsToCensus(
censusID,
uniqueParticipantsMap,
ci.FromTotalAddresses,
ci.Url,
); err != nil {
log.Errorw(err, fmt.Sprintf("failed to add participants to census %s", censusID.String()))
}
}()
// return the censusID to the client
data, err := json.Marshal(map[string]string{"censusId": censusID.String()})
if err != nil {
return nil, err
}
return data, nil
}
// censusWarpcastChannel helper method creates a new census from a Warpcast
// Channel. The process is async and returns the json encoded censusID. It
// updates the progress in the queue and the result when it's ready.
func (v *vocdoniHandler) censusWarpcastChannel(channelID string, authorFID uint64, delegations []*mongo.Delegation) ([]byte, error) {
// create a censusID for the queue and store into it
censusID, err := v.cli.NewCensus(api.CensusTypeWeighted)
if err != nil {
return nil, err
}
v.backgroundQueue.Store(censusID.String(), CensusInfo{})
if err := v.db.AddCensus(censusID, authorFID); err != nil {
return nil, fmt.Errorf("cannot add census to database: %w", err)
}
// run a goroutine to create the census, update the queue with the progress,
// and update the queue result when it's ready
go func() {
internalCtx, cancel := context.WithCancel(context.Background())
defer cancel()
var err error
// get the fids of the users in the channel from neynar farcaster API, if
// the channel does not exist, return a NotFound error
var users []uint64
v.trackStepProgress(censusID, 1, 3, func(progress chan int) {
users, err = v.fcapi.ChannelFIDs(internalCtx, channelID, progress)
})
if err != nil {
log.Errorw(err, "failed to get channel fids from farcaster API")
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
if len(users) == 0 {
log.Errorw(fmt.Errorf("no valid participants found for the channel %s", channelID), "")
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: "no valid participants found for the channel"})
return
}
// create the participants from the database users using the fids
var participants []*FarcasterParticipant
v.trackStepProgress(censusID, 2, 3, func(progress chan int) {
participants = v.farcasterCensusFromFids(users, delegations, progress)
})
if len(participants) == 0 {
log.Errorw(fmt.Errorf("no valid participant signers found for the channel %s", channelID), "")
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: "no valid participant signers found for the channel"})
return
}
// create the census from the participants
var censusInfo *CensusInfo
v.trackStepProgress(censusID, 3, 3, func(progress chan int) {
censusInfo, err = CreateCensus(v.cli, participants, FrameCensusTypeChannelGated, progress)
})
if err != nil {
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
uniqueParticipantsMap := make(UniqueParticipants, len(participants))
totalParticipants := uint32(0) // including delegations
for _, p := range participants {
if _, ok := uniqueParticipantsMap[p.Username]; !ok {
uniqueParticipantsMap.Add(p.Username, new(big.Int).SetUint64(1), p.Delegations+1)
totalParticipants += p.Delegations + 1
}
}
// only return the username list if it's less than the maxUsersNamesToReturn
if len(uniqueParticipantsMap) < maxUsersNamesToReturn {
for username := range uniqueParticipantsMap {
censusInfo.Usernames = append(censusInfo.Usernames, username)
}
}
censusInfo.FromTotalAddresses = uint32(len(users))
censusInfo.FarcasterParticipantCount = totalParticipants
v.backgroundQueue.Store(censusID.String(), *censusInfo)
// add participants to the census in the database
if err := v.db.AddParticipantsToCensus(
censusID,
uniqueParticipantsMap,
censusInfo.FromTotalAddresses,
censusInfo.Url,
); err != nil {
log.Errorw(err, fmt.Sprintf("failed to add participants to census %s", censusID.String()))
}
log.Infow("census created from channel",
"channelID", channelID,
"participants", len(censusInfo.Usernames))
}()
// return the censusID to the client
return json.Marshal(map[string]string{"censusId": censusID.String()})
}
// censusFollowers helper creates a new census from the followers of a user.
// The process is async and returns the json encoded censusID. It updates the
// progress in the queue and the result when it's ready. If something fails
// during the process, it returns an error or the error is stored in the queue
// if it's async.
func (v *vocdoniHandler) censusFollowers(userFID uint64, delegations []*mongo.Delegation) ([]byte, error) {
// create a censusID for the queue and store into it
censusID, err := v.cli.NewCensus(api.CensusTypeWeighted)
if err != nil {
return nil, err
}
// store the censusID in the database and the queue
if err := v.db.AddCensus(censusID, userFID); err != nil {
return nil, fmt.Errorf("cannot add census to database: %w", err)
}
v.backgroundQueue.Store(censusID.String(), CensusInfo{})
// run a goroutine to create the census, update the queue with the progress,
// and update the queue result when it's ready
go func() {
internalCtx, cancel := context.WithCancel(context.Background())
defer cancel()
users, err := v.fcapi.UserFollowers(internalCtx, userFID)
if err != nil {
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
// include poll author in the census
users = append(users, userFID)
// create the participants from the database users using the fids
var participants []*FarcasterParticipant
v.trackStepProgress(censusID, 1, 2, func(progress chan int) {
participants = v.farcasterCensusFromFids(users, delegations, progress)
})
if len(participants) == 0 {
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: "no valid participants"})
return
}
// create the census from the participants
var censusInfo *CensusInfo
v.trackStepProgress(censusID, 2, 2, func(progress chan int) {
censusInfo, err = CreateCensus(v.cli, participants, FrameCensusTypeFollowers, progress)
})
if err != nil {
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
uniqueParticipantsMap := make(UniqueParticipants, len(participants))
totalWeight := new(big.Int).SetUint64(0)
totalParticipants := uint32(0) // including delegations
for _, p := range participants {
if _, ok := uniqueParticipantsMap[p.Username]; ok {
// if the username is already in the map, continue
continue
}
uniqueParticipantsMap.Add(p.Username, p.Weight, p.Delegations+1)
totalWeight.Add(totalWeight, p.Weight)
totalParticipants += p.Delegations + 1
}
// only return the username list if it's less than the maxUsersNamesToReturn
if len(uniqueParticipantsMap) < maxUsersNamesToReturn {
for u := range uniqueParticipantsMap {
censusInfo.Usernames = append(censusInfo.Usernames, u)
}
}
// store the census info in the database
if err := v.db.AddParticipantsToCensus(
censusID,
uniqueParticipantsMap,
uint32(len(users)),
censusInfo.Url,
); err != nil {
log.Errorw(err, fmt.Sprintf("failed to add participants to census %s", censusID.String()))
}
censusInfo.FromTotalAddresses = uint32(len(users))
censusInfo.FarcasterParticipantCount = totalParticipants
v.backgroundQueue.Store(censusID.String(), *censusInfo)
log.Infow("census created from user followers",
"fid", userFID,
"participants", len(censusInfo.Usernames),
"totalParticipants", totalParticipants,
)
}()
// return the censusID to the client
return json.Marshal(map[string]string{"censusId": censusID.String()})
}
// censusAlfafrensChannel creates a new census from an AlfaFrens Channel.
func (v *vocdoniHandler) censusAlfafrensChannel(censusID types.HexBytes, ownerFID uint64) ([]byte, error) {
v.backgroundQueue.Store(censusID.String(), CensusInfo{})
if err := v.db.AddCensus(censusID, ownerFID); err != nil {
return nil, fmt.Errorf("cannot add census to database: %w", err)
}
// get the channel address from the alfafrens API
channelAddr, err := alfafrens.ChannelByFid(ownerFID)
if err != nil {
return nil, fmt.Errorf("cannot get alfafrens channel address for user %d: %w", ownerFID, err)
}
// run a goroutine to create the census, update the queue with the progress,
// and update the queue result when it's ready
go func() {
var err error
var users []uint64
// get the fids of the users in the channel from neynar farcaster API, if
// the channel does not exist, return a NotFound error
v.trackStepProgress(censusID, 1, 3, func(progress chan int) {
progress <- 10
users, err = alfafrens.ChannelFids(channelAddr)
progress <- 100
})
if err != nil {
log.Errorw(err, "failed to get channel fids from farcaster API")
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
if len(users) == 0 {
log.Errorw(fmt.Errorf("no valid participants found for alfafrens channel %s", channelAddr.String()), "")
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: "no valid participants found for the channel"})
return
}
// create the participants from the database users using the fids
var participants []*FarcasterParticipant
v.trackStepProgress(censusID, 1, 2, func(progress chan int) {
participants = v.farcasterCensusFromFids(users, nil, progress)
})
if len(participants) == 0 {
log.Errorw(fmt.Errorf("no valid participant signers found for alfafrens channel %s", channelAddr.String()), "")
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: "no valid participant signers found for the channel"})
return
}
// create the census from the participants
var censusInfo *CensusInfo
v.trackStepProgress(censusID, 2, 2, func(progress chan int) {
censusInfo, err = CreateCensus(v.cli, participants, FrameCensusTypeAlfaFrensChannel, progress)
})
if err != nil {
v.backgroundQueue.Store(censusID.String(), CensusInfo{Error: err.Error()})
return
}
uniqueParticipantsMap := make(UniqueParticipants, len(participants))
for _, p := range participants {
if _, ok := uniqueParticipantsMap[p.Username]; !ok {
uniqueParticipantsMap.Add(p.Username, new(big.Int).SetUint64(1), p.Delegations)
}
}
for username := range uniqueParticipantsMap {
censusInfo.Usernames = append(censusInfo.Usernames, username)
}
censusInfo.FromTotalAddresses = uint32(len(users))
censusInfo.FarcasterParticipantCount = uint32(len(uniqueParticipantsMap))
v.backgroundQueue.Store(censusID.String(), *censusInfo)
// add participants to the census in the database
if err := v.db.AddParticipantsToCensus(
censusID,
uniqueParticipantsMap,
censusInfo.FromTotalAddresses,
censusInfo.Url,
); err != nil {
log.Errorw(err, fmt.Sprintf("failed to add participants to census %s", censusID.String()))
}
log.Infow("census created for alfafrens channel",
"channelID", channelAddr.String(),
"participants", len(censusInfo.Usernames))
}()
// return the censusID to the client
return json.Marshal(map[string]string{"censusId": censusID.String()})
}
func (v *vocdoniHandler) checkERC20ContractHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// TODO: It should receive CheckCensusSource instance
return ctx.Send([]byte("ok"), http.StatusOK)
}
func (v *vocdoniHandler) checkNFTContractHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// TODO: It should receive CheckCensusSource instance
return ctx.Send([]byte("ok"), http.StatusOK)
}
func (v *vocdoniHandler) farcasterCensusFromEthereumCSV(csv []byte, progress chan int) ([]*FarcasterParticipant, uint32, error) {
records, err := ParseCSV(csv)
if err != nil {
return nil, 0, err
}
return v.processCensusRecords(records, nil, progress)
}
// farcasterCensusFromFids creates a list of Farcaster participants from a list
// of FIDs. It queries the database to get the users signer keys and creates the
// participants from them. It returns the list of participants and a map of the
// FIDs that failed to get the users from the database or decoding the keys.
func (v *vocdoniHandler) farcasterCensusFromFids(fids []uint64, delegations []*mongo.Delegation, progress chan int) []*FarcasterParticipant {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// get participants from the users fids, quering the database and to get the
// users public keys
totalFids := len(fids)
var wg sync.WaitGroup
participants := []*FarcasterParticipant{}
participantsCh := make(chan *FarcasterParticipant)
concurrencyLimit := make(chan struct{}, 10)
var processedFids atomic.Uint32
// Start goroutines to consume data from channel
go func() {
for {
select {
case <-ctx.Done():
return
case participant, ok := <-participantsCh:
if !ok {
log.Debugw("collected valid database participants", "count", len(participants))
return
}
participants = append(participants, participant)
}
}
}()
// run database queries concurrently
for i, fid := range fids {
concurrencyLimit <- struct{}{}
wg.Add(1)