-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbl_pool.go
More file actions
1331 lines (1146 loc) · 42.3 KB
/
Copy pathbl_pool.go
File metadata and controls
1331 lines (1146 loc) · 42.3 KB
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 blockchain
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/functionland/go-fula/blockchain/abi"
"github.com/functionland/go-fula/common"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
)
type PingResponse struct {
Success bool `json:"Success"`
Time int64 `json:"Time"`
Text string `json:"Text"`
}
func (bl *FxBlockchain) PoolCreate(ctx context.Context, to peer.ID, r PoolCreateRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionPoolCreate, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) HandlePoolJoin(method string, action string, from peer.ID, w http.ResponseWriter, r *http.Request) {
// This handles the join request sent from client for a blox which is not part of the pool yet
log := log.With("action", action, "from", from)
var req PoolJoinRequest
var res PoolJoinResponse
defer r.Body.Close()
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Debug("cannot parse request body: %v", err)
http.Error(w, "", http.StatusBadRequest)
return
}
ctx, cancel := context.WithTimeout(r.Context(), time.Second*time.Duration(bl.timeout))
defer cancel()
poolID := req.PoolID
poolIDStr := strconv.Itoa(poolID)
chainName := req.ChainName
// If no chain name provided, determine it automatically
if chainName == "" {
log.Debugw("No chain name provided, attempting auto-discovery", "poolID", poolID)
// Try to discover which chain this pool exists on
if discoveredChain, err := bl.discoverPoolChain(ctx, uint32(poolID)); err == nil {
chainName = discoveredChain
log.Infow("Auto-discovered chain for pool", "poolID", poolID, "chain", chainName)
} else {
// Default to skale if discovery fails
chainName = "skale"
log.Warnw("Failed to discover chain, defaulting to skale", "poolID", poolID, "error", err)
}
}
// Validate that the pool exists on the specified chain
if err := bl.validatePoolOnChain(ctx, uint32(poolID), chainName); err != nil {
errMsg := map[string]interface{}{
"message": "Pool validation failed",
"description": fmt.Sprintf("Pool %d does not exist on chain %s: %s", poolID, chainName, err.Error()),
}
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(errMsg)
return
}
// Update pool name configuration
if errUpdatePool := bl.updatePoolName(poolIDStr); errUpdatePool != nil {
errMsg := map[string]interface{}{
"message": "Pool Join is submitted but Error in updating Pool Config",
"description": fmt.Sprintf("Error in updatePoolName: %s", errUpdatePool.Error()),
}
w.WriteHeader(http.StatusExpectationFailed)
json.NewEncoder(w).Encode(errMsg)
return
}
// Update chain name configuration
if errUpdateChain := bl.updateChainName(chainName); errUpdateChain != nil {
errMsg := map[string]interface{}{
"message": "Pool Join is submitted but Error in updating Chain Config",
"description": fmt.Sprintf("Error in updateChainName: %s", errUpdateChain.Error()),
}
w.WriteHeader(http.StatusExpectationFailed)
json.NewEncoder(w).Encode(errMsg)
return
}
statusCode := http.StatusAccepted
res = PoolJoinResponse{
Account: "",
PoolID: req.PoolID,
ChainName: chainName,
}
log.Infow("Pool join request processed successfully", "poolID", poolID, "chain", chainName, "from", from)
w.WriteHeader(statusCode)
if err := json.NewEncoder(w).Encode(res); err != nil {
log.Error("failed to write response: %v", err)
}
}
func (bl *FxBlockchain) PoolJoin(ctx context.Context, to peer.ID, r PoolJoinRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionPoolJoin, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) StartPingServer(ctx context.Context) error {
return bl.StartPingProxy(ctx)
}
func (bl *FxBlockchain) StopPingServer(ctx context.Context) error {
return bl.ShutdownPingProxy(ctx)
}
func (bl *FxBlockchain) PoolCancelJoin(ctx context.Context, to peer.ID, r PoolCancelJoinRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionPoolCancelJoin, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) HandlePoolCancelJoin(method string, action string, from peer.ID, w http.ResponseWriter, r *http.Request) {
// This handles the join request sent from client for a blox which is not part of the pool yet
log := log.With("action", action, "from", from)
var req PoolCancelJoinRequest
var res PoolCancelJoinResponse
defer r.Body.Close()
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Debug("cannot parse request body: %v", err)
http.Error(w, "", http.StatusBadRequest)
return
}
ctx, cancel := context.WithTimeout(r.Context(), time.Second*time.Duration(bl.timeout))
defer cancel()
response, statusCode, err := bl.callBlockchain(ctx, method, action, &req)
if err != nil {
poolID := req.PoolID
poolIDStr := strconv.Itoa(poolID)
requestSubmitted, err := bl.checkIfUserHasOpenPoolRequests(ctx, poolIDStr)
if err == nil && !requestSubmitted {
errUpdatePool := bl.updatePoolName("0")
errUpdateChain := bl.updateChainName("")
errPingServer := bl.StopPingServer(ctx)
var errorMsgs []string
if errUpdatePool != nil {
errorMsgs = append(errorMsgs, fmt.Sprintf("Error in updatePoolName: %s", errUpdatePool.Error()))
}
if errUpdateChain != nil {
errorMsgs = append(errorMsgs, fmt.Sprintf("Error in updateChainName: %s", errUpdateChain.Error()))
}
if errPingServer != nil {
errorMsgs = append(errorMsgs, fmt.Sprintf("Error in Ping server: %s", errPingServer.Error()))
}
if len(errorMsgs) > 0 {
errMsg := map[string]interface{}{
"message": "Pool Cancel Join is submitted but Error in cleanup",
"description": strings.Join(errorMsgs, ", "),
}
w.WriteHeader(http.StatusExpectationFailed)
json.NewEncoder(w).Encode(errMsg)
return
} else {
statusCode = http.StatusAccepted
err = nil
response = []byte(fmt.Sprintf("{\"account\":\"\",\"pool_id\":%d}", req.PoolID))
}
}
}
if statusCode == http.StatusOK {
statusCode = http.StatusAccepted
}
log.Debugw("callblockchain response in PoolCancelJoin", "statusCode", statusCode, "response", response, "err", err)
// If status code is not 200, attempt to format the response as JSON
if statusCode != http.StatusAccepted || err != nil {
w.WriteHeader(statusCode)
// Try to parse the error and format it as JSON
var errMsg map[string]interface{}
if jsonErr := json.Unmarshal(response, &errMsg); jsonErr != nil {
// If the response isn't JSON or can't be parsed, use a generic message
errMsg = map[string]interface{}{
"message": "An error occurred",
"description": err.Error(),
}
}
json.NewEncoder(w).Encode(errMsg)
return
}
bl.cleanLeaveJoinPool(ctx, req.PoolID)
w.WriteHeader(statusCode)
err1 := json.Unmarshal(response, &res)
if err1 != nil {
log.Error("failed to format response: %v", err1)
}
if err := json.NewEncoder(w).Encode(res); err != nil {
log.Error("failed to write response: %v", err)
}
}
func (bl *FxBlockchain) cleanLeaveJoinPool(ctx context.Context, PoolID int) {
// Reset pool configuration
if bl.updatePoolName != nil {
if err := bl.updatePoolName("0"); err != nil {
log.Errorw("Failed to reset pool name", "error", err)
}
}
// Reset chain configuration
if bl.updateChainName != nil {
if err := bl.updateChainName(""); err != nil {
log.Errorw("Failed to reset chain name", "error", err)
}
}
bl.StopPingServer(ctx)
// Announcements no longer used - pool joins handled via blockchain API
// Send a stop signal if the channel is not nil
if bl.stopFetchUsersAfterJoinChan != nil {
close(bl.stopFetchUsersAfterJoinChan)
// Reset the channel to nil to avoid closing a closed channel
bl.stopFetchUsersAfterJoinChan = nil
}
bl.clearPoolPeersFromPeerAddr(ctx, PoolID)
}
func (bl *FxBlockchain) PoolRequests(ctx context.Context, to peer.ID, r PoolRequestsRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionPoolRequests, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) PoolList(ctx context.Context, to peer.ID, r PoolListRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionPoolList, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) ReplicateInPool(ctx context.Context, to peer.ID, r ReplicateRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionReplicateInPool, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) PoolUserList(ctx context.Context, to peer.ID, r PoolUserListRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionPoolUserList, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) PoolVote(ctx context.Context, to peer.ID, r PoolVoteRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionPoolVote, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) PoolLeave(ctx context.Context, to peer.ID, r PoolLeaveRequest) ([]byte, error) {
if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionPoolLeave, &buf)
if err != nil {
return nil, err
}
resp, err := bl.doP2PRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}
func (bl *FxBlockchain) HandlePoolJoinRequest(ctx context.Context, from peer.ID, account string, topicString string, withMemberListUpdate bool) error {
// Note: withMemberListUpdate parameter is deprecated - no longer needed with EVM chain integration
// Voting logic has been removed as it's no longer required
averageDuration := float64(2000)
successCount := 0
// Check if peer exists in our local members map
status, exists := bl.GetMemberStatus(from)
if !exists {
log.Debugw("PeerID not found in local members map, this is expected with EVM integration", "peerID", from)
// With EVM integration, we don't maintain a local members list
// This method is now primarily for legacy compatibility
return nil
}
if status == common.Pending {
// Ping
/*
// Use IPFS Ping
log.Debugw("****** Pinging pending node", "from", bl.selfPeerID, "to", from)
averageDuration, successCount, err := bl.p.Ping(ctx, from)
if err != nil {
log.Errorw("An error occurred during ping", "error", err)
return err
}
if bl.maxPingTime == 0 {
//TODO: This should not happen but is happening!
bl.maxPingTime = 200
}
if bl.minPingSuccessCount == 0 {
//TODO: This should not happen but is happening!
bl.minPingSuccessCount = 3
}
*/
// Set up the request with context for timeout
ctxPing, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if bl.rpc == nil {
return fmt.Errorf("IPFS rpc is not defined")
}
// Send the ping request
res, err := bl.rpc.Request("ping", from.String()).Send(ctxPing)
if err != nil {
return fmt.Errorf("ping was unsuccessful: %s", err)
}
if res.Error != nil {
return fmt.Errorf("ping was unsuccessful: %s", res.Error)
}
// Process multiple responses using a decoder
decoder := json.NewDecoder(res.Output)
var totalTime int64
var count int
for decoder.More() {
var pingResp PingResponse
err := decoder.Decode(&pingResp)
if err != nil {
log.Errorf("error decoding JSON response: %s", err)
continue
}
if pingResp.Text == "" && pingResp.Time > 0 { // Check for empty Text field and Time
totalTime += pingResp.Time
count++
}
}
if count > 0 {
averageDuration = float64(totalTime) / float64(count) / 1e6 // Convert nanoseconds to milliseconds
successCount = count
} else {
fmt.Println("No valid ping responses received")
}
vote := int(averageDuration) <= bl.maxPingTime && successCount >= bl.minPingSuccessCount
log.Debugw("Ping result", "averageDuration", averageDuration, "successCount", successCount, "vote", vote, "bl.maxPingTime", bl.maxPingTime, "bl.minPingSuccessCount", bl.minPingSuccessCount)
// Convert topic from string to int
poolID, err := strconv.Atoi(topicString)
if err != nil {
return fmt.Errorf("invalid topic, not an integer: %s", err)
}
voteRequest := PoolVoteRequest{
PoolID: poolID,
Account: account,
PeerID: from.String(),
VoteValue: vote,
}
// Call PoolVote method
responseBody, statusCode, err := bl.callBlockchain(ctx, "POST", actionPoolVote, &voteRequest)
if err != nil {
return fmt.Errorf("blockchain call error: %w, status code: %d", err, statusCode)
}
// Check if the status code is OK; if not, handle it as an error
if statusCode != http.StatusOK && statusCode != http.StatusAccepted {
var errMsg map[string]interface{}
if jsonErr := json.Unmarshal(responseBody, &errMsg); jsonErr == nil {
return fmt.Errorf("unexpected response status: %d, message: %s, description: %s",
statusCode, errMsg["message"], errMsg["description"])
} else {
return fmt.Errorf("unexpected response status: %d, body: %s", statusCode, string(responseBody))
}
}
// Interpret the response
var voteResponse PoolVoteResponse
if err := json.Unmarshal(responseBody, &voteResponse); err != nil {
return fmt.Errorf("failed to unmarshal vote response: %w", err)
}
// Handle the response as needed
log.Infow("Vote cast successfully", "statusCode", statusCode, "voteResponse", voteResponse, "on", from, "by", bl.selfPeerID)
// Update member status to unknown
bl.membersLock.Lock()
bl.members[from] = common.Unknown
bl.membersLock.Unlock()
} else {
return fmt.Errorf("peerID does not exist in the list of pool requests: %s with status %d", from, status)
}
return nil
}
func (bl *FxBlockchain) HandlePoolList(ctx context.Context) (PoolListResponse, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*time.Duration(bl.timeout))
defer cancel()
req := PoolListRequest{}
var res PoolListResponse
response, _, err := bl.callBlockchain(ctx, "POST", actionPoolList, req)
if err != nil {
return PoolListResponse{}, err
}
err = json.Unmarshal(response, &res)
if err != nil {
log.Error("failed to format response: %v", err)
return PoolListResponse{}, err
}
return res, nil
}
// HandleEVMPoolList retrieves pool list from EVM chains (Base/Skale)
func (bl *FxBlockchain) HandleEVMPoolList(ctx context.Context, chainName string) (EVMPoolListResponse, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*time.Duration(bl.timeout))
defer cancel()
chainConfigs := GetChainConfigs()
chainConfig, exists := chainConfigs[chainName]
if !exists {
return EVMPoolListResponse{}, fmt.Errorf("unsupported chain: %s", chainName)
}
var pools []EVMPool
index := uint32(0) // Start from index 0 for poolIds enumeration
log.Debugw("Starting pool discovery using poolIds(index)", "chain", chainName, "startIndex", index)
for {
// Call the poolIds(uint256) method on the contract using index-based enumeration
callData := abi.EncodePoolIdsCall(index)
params := []interface{}{
map[string]interface{}{
"to": chainConfig.Contract,
"data": callData,
},
"latest",
}
response, statusCode, err := bl.callEVMChainWithRetry(ctx, chainName, "eth_call", params, 3)
if err != nil {
log.Debugw("Error calling poolIds - no more pools", "chain", chainName, "index", index, "error", err)
break // Stop on error - no more pools
}
if statusCode != 200 {
return EVMPoolListResponse{}, fmt.Errorf("unexpected status code %d from chain %s", statusCode, chainName)
}
// Parse JSON-RPC response
var rpcResponse struct {
Result string `json:"result"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(response, &rpcResponse); err != nil {
return EVMPoolListResponse{}, fmt.Errorf("failed to parse RPC response: %w", err)
}
if rpcResponse.Error != nil {
log.Debugw("RPC error calling poolIds - no more pools", "chain", chainName, "index", index, "error", rpcResponse.Error.Message)
break // Stop on RPC error - no more pools
}
// Check if response indicates no pool at this index (empty or revert)
if rpcResponse.Result == "0x" || len(rpcResponse.Result) <= 2 {
log.Debugw("No pool at index - stopping discovery", "chain", chainName, "index", index)
break
}
// Decode the pool ID from the response
poolID, err := abi.DecodePoolIdResponse(rpcResponse.Result)
if err != nil {
log.Debugw("Error decoding poolIds response", "chain", chainName, "index", index, "error", err)
break
}
// Skip pool 0 if it somehow appears
if poolID == 0 {
log.Debugw("Skipping pool 0 as it doesn't exist", "chain", chainName, "index", index)
index++
continue
}
log.Debugw("Found pool ID at index", "chain", chainName, "poolID", poolID, "index", index)
// Now get the full pool data using pools(uint32) method
poolCallData := abi.EncodePoolsCall(poolID)
poolParams := []interface{}{
map[string]interface{}{
"to": chainConfig.Contract,
"data": poolCallData,
},
"latest",
}
poolResponse, poolStatusCode, err := bl.callEVMChainWithRetry(ctx, chainName, "eth_call", poolParams, 3)
if err != nil {
log.Warnw("Failed to get pool data", "chain", chainName, "poolID", poolID, "error", err)
index++
continue // Skip this pool but continue with next index
}
if poolStatusCode != 200 {
log.Warnw("Unexpected status code getting pool data", "chain", chainName, "poolID", poolID, "statusCode", poolStatusCode)
index++
continue
}
// Parse pool data response
var poolRpcResponse struct {
Result string `json:"result"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(poolResponse, &poolRpcResponse); err != nil {
log.Warnw("Failed to parse pool data response", "chain", chainName, "poolID", poolID, "error", err)
index++
continue
}
if poolRpcResponse.Error != nil {
log.Warnw("RPC error getting pool data", "chain", chainName, "poolID", poolID, "error", poolRpcResponse.Error.Message)
index++
continue
}
// Decode the pool data using proper ABI decoding
poolData, err := abi.DecodePoolsResult(poolRpcResponse.Result)
if err != nil {
log.Warnw("Failed to decode pool data", "chain", chainName, "poolID", poolID, "error", err)
index++
continue
}
// Convert to EVMPool format
// IMPORTANT: Use the discovered poolID from poolIds() call, not poolData.ID which may be incorrectly parsed
pool := EVMPool{
Creator: poolData.Creator,
ID: poolID, // Use the poolID we discovered from poolIds(), not poolData.ID
MaxChallengeResponsePeriod: poolData.MaxChallengeResponsePeriod,
MemberCount: poolData.MemberCount,
MaxMembers: poolData.MaxMembers,
RequiredTokens: poolData.RequiredTokens.String(),
MinPingTime: poolData.MinPingTime.String(),
Name: poolData.Name,
Region: poolData.Region,
ChainName: chainName,
}
pools = append(pools, pool)
index++
// Safety check to prevent infinite loops
if index > 20 {
log.Warnw("Reached maximum index limit", "chain", chainName, "maxIndex", index)
break
}
}
return EVMPoolListResponse{Pools: pools}, nil
}
// HandleIsMemberOfPool checks if a peer is a member of a specific pool on a specific chain
func (bl *FxBlockchain) HandleIsMemberOfPool(ctx context.Context, req IsMemberOfPoolRequest) (IsMemberOfPoolResponse, error) {
// Pool 0 doesn't exist, return false immediately
if req.PoolID == 0 {
log.Debugw("Pool 0 doesn't exist, returning false", "chain", req.ChainName, "peerID", req.PeerID)
return IsMemberOfPoolResponse{
IsMember: false,
MemberAddress: "0x0000000000000000000000000000000000000000",
ChainName: req.ChainName,
PoolID: req.PoolID,
}, nil
}
ctx, cancel := context.WithTimeout(ctx, time.Second*time.Duration(bl.timeout))
defer cancel()
chainConfigs := GetChainConfigs()
chainConfig, exists := chainConfigs[req.ChainName]
if !exists {
return IsMemberOfPoolResponse{}, fmt.Errorf("unsupported chain: %s", req.ChainName)
}
// Convert PeerID to bytes32
peerIDBytes32, err := peerIdToBytes32(req.PeerID)
if err != nil {
return IsMemberOfPoolResponse{}, fmt.Errorf("failed to convert PeerID to bytes32: %w", err)
}
// Call isPeerIdMemberOfPool(uint32,bytes32) method using proper ABI encoding
callData := abi.EncodeIsPeerIdMemberOfPoolCall(req.PoolID, peerIDBytes32)
params := []interface{}{
map[string]interface{}{
"to": chainConfig.Contract,
"data": callData,
},
"latest",
}
response, statusCode, err := bl.callEVMChainWithRetry(ctx, req.ChainName, "eth_call", params, 3)
if err != nil {
log.Errorw("Failed to call EVM chain for membership check after retries", "chain", req.ChainName, "poolID", req.PoolID, "peerID", req.PeerID, "error", err)
return IsMemberOfPoolResponse{
IsMember: false,
MemberAddress: "0x0000000000000000000000000000000000000000",
ChainName: req.ChainName,
PoolID: req.PoolID,
}, nil // Return false instead of error for graceful degradation
}
if statusCode != 200 {
return IsMemberOfPoolResponse{}, fmt.Errorf("unexpected status code %d from chain %s", statusCode, req.ChainName)
}
// Parse JSON-RPC response
var rpcResponse struct {
Result string `json:"result"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(response, &rpcResponse); err != nil {
return IsMemberOfPoolResponse{}, fmt.Errorf("failed to parse RPC response: %w", err)
}
if rpcResponse.Error != nil {
return IsMemberOfPoolResponse{}, fmt.Errorf("RPC error: %s", rpcResponse.Error.Message)
}
// Check for contract-specific errors
if contractErr := abi.ParseContractError(rpcResponse.Result); contractErr != nil {
log.Debugw("Contract error in membership check", "chain", req.ChainName, "poolID", req.PoolID, "error", contractErr)
return IsMemberOfPoolResponse{
IsMember: false,
MemberAddress: "0x0000000000000000000000000000000000000000",
ChainName: req.ChainName,
PoolID: req.PoolID,
}, nil // Return false for contract errors (graceful degradation)
}
// Decode the result using proper ABI decoding
membershipResult, err := abi.DecodeIsMemberOfPoolResult(rpcResponse.Result)
if err != nil {
log.Errorw("Failed to decode membership result", "chain", req.ChainName, "poolID", req.PoolID, "error", err)
return IsMemberOfPoolResponse{
IsMember: false,
MemberAddress: "0x0000000000000000000000000000000000000000",
ChainName: req.ChainName,
PoolID: req.PoolID,
}, nil
}
return IsMemberOfPoolResponse{
IsMember: membershipResult.IsMember,
MemberAddress: membershipResult.MemberAddress,
ChainName: req.ChainName,
PoolID: req.PoolID,
}, nil
}
// GetPoolCreatorPeerID retrieves the creator's peer ID for a specific pool on a specific chain
func (bl *FxBlockchain) GetPoolCreatorPeerID(ctx context.Context, poolID uint32, chainName string) (string, error) {
if poolID == 0 {
return "", fmt.Errorf("invalid pool ID: %d", poolID)
}
ctx, cancel := context.WithTimeout(ctx, time.Second*time.Duration(bl.timeout))
defer cancel()
chainConfigs := GetChainConfigs()
chainConfig, exists := chainConfigs[chainName]
if !exists {
return "", fmt.Errorf("unsupported chain: %s", chainName)
}
log.Debugw("Getting pool creator peer ID", "poolID", poolID, "chain", chainName)
// Step 1: Get pool information to find the creator
poolCallData := abi.EncodePoolsCall(poolID)
poolParams := []interface{}{
map[string]interface{}{
"to": chainConfig.Contract,
"data": poolCallData,
},
"latest",
}
poolResponse, statusCode, err := bl.callEVMChainWithRetry(ctx, chainName, "eth_call", poolParams, 3)
if err != nil {
log.Errorw("Failed to get pool information", "chain", chainName, "poolID", poolID, "error", err)
return "", fmt.Errorf("failed to get pool information: %w", err)
}
if statusCode != 200 {
return "", fmt.Errorf("unexpected status code %d from chain %s", statusCode, chainName)
}