-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathblockchain.go
More file actions
1486 lines (1314 loc) · 50.1 KB
/
Copy pathblockchain.go
File metadata and controls
1486 lines (1314 loc) · 50.1 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"
"os"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/functionland/go-fula/common"
wifi "github.com/functionland/go-fula/wap/pkg/wifi"
ipfsClusterClientApi "github.com/ipfs-cluster/ipfs-cluster/api"
"github.com/ipfs/go-cid"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/peer"
)
var apiError struct {
Message string `json:"message"`
Description string `json:"description"`
}
const (
FxBlockchainProtocolID = "/fx.land/blockchain/0.0.1"
actionAuth = "auth"
)
var (
_ Blockchain = (*FxBlockchain)(nil)
log = logging.Logger("fula/blockchain")
)
type Config struct {
StoreDir string `yaml:"storeDir"`
// other fields
}
type (
FxBlockchain struct {
*options
c *http.Client // P2P client for mobile->device calls (nil on device side)
ch *http.Client // normal http client for blockchain API calls
proxyServer *http.Server // TCP proxy server for kubo-forwarded requests
pingServer *http.Server // TCP ping server for kubo-forwarded ping requests
authorizedPeers map[peer.ID]struct{}
authorizedPeersLock sync.RWMutex
bufPool *sync.Pool
reqPool *sync.Pool
keyStorer KeyStorer
members map[peer.ID]common.MemberStatus
membersLock sync.RWMutex
lastFetchTime time.Time
fetchInterval time.Duration
fetchCheckTicker *time.Ticker
fetchCheckStop chan struct{}
stopFetchUsersAfterJoinChan chan struct{}
cachedAccount string
isAccountCached bool
fetchMutex sync.Mutex
isFetching bool
}
authorizationRequest struct {
Subject peer.ID `json:"id"`
Allow bool `json:"allow"`
}
)
func NewFxBlockchain(keyStorer KeyStorer, o ...Option) (*FxBlockchain, error) {
opts, err := newOptions(o...)
if err != nil {
return nil, err
}
bl := &FxBlockchain{
options: opts,
ch: &http.Client{
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
},
},
authorizedPeers: make(map[peer.ID]struct{}),
bufPool: &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
},
reqPool: &sync.Pool{
New: func() interface{} {
return new(http.Request)
},
},
keyStorer: keyStorer,
lastFetchTime: time.Now(),
fetchInterval: opts.fetchFrequency,
fetchCheckStop: make(chan struct{}),
}
if bl.authorizer != "" && bl.selfPeerID != "" {
if err := bl.SetAuth(context.Background(), bl.selfPeerID, bl.authorizer, true); err != nil {
return nil, err
}
}
bl.startFetchCheck()
return bl, nil
}
// SetP2PClient sets the HTTP client used for outgoing P2P calls (mobile client side).
// On the device side this is not called; the device only receives requests via the TCP proxy.
// If a signing key was configured via WithRequestSigning, the client's transport is
// automatically wrapped with signingTransport to add authenticated headers.
func (bl *FxBlockchain) SetP2PClient(c *http.Client) {
if bl.signingKey != nil && c != nil {
transport := c.Transport
if transport == nil {
transport = http.DefaultTransport
}
c = &http.Client{
Transport: &signingTransport{
base: transport,
privKey: bl.signingKey,
peerID: bl.selfPeerID,
},
Timeout: c.Timeout,
}
}
bl.c = c
}
// doP2PRequest sends an HTTP request via the P2P client. Returns an error if
// the P2P client has not been set via SetP2PClient (i.e. device-side only mode).
func (bl *FxBlockchain) doP2PRequest(req *http.Request) (*http.Response, error) {
if bl.c == nil {
return nil, fmt.Errorf("P2P client not configured: call SetP2PClient first (this method is only available on mobile client)")
}
return bl.c.Do(req)
}
func (bl *FxBlockchain) startFetchCheck() {
internal := 2 * time.Minute
bl.fetchCheckTicker = time.NewTicker(internal) // check every hour, adjust as needed
if bl.wg != nil {
// Increment the WaitGroup counter before starting the goroutine
log.Debug("called wg.Add in blockchain startFetchCheck")
bl.wg.Add(1)
}
// Periodic fetch is no longer needed with EVM chain integration
// Pool membership is determined during startup and doesn't change frequently
go func() {
if bl.wg != nil {
log.Debug("called wg.Done in startFetchCheck ticker")
defer bl.wg.Done()
}
defer log.Debug("startFetchCheck ticker go routine is ending")
for {
select {
case <-bl.fetchCheckTicker.C:
// No-op: periodic fetching disabled for production optimization
log.Debugw("Periodic fetch skipped - using EVM chain integration")
case <-bl.fetchCheckStop:
bl.fetchCheckTicker.Stop()
return
}
}
}()
}
func (bl *FxBlockchain) Start(ctx context.Context) error {
// Start the TCP proxy server for kubo-forwarded requests
if err := bl.StartProxy(ctx); err != nil {
return err
}
// Start the ping server for kubo-forwarded ping requests
return bl.StartPingProxy(ctx)
}
func (bl *FxBlockchain) putBuf(buf *bytes.Buffer) {
buf.Reset()
bl.bufPool.Put(buf)
}
func (bl *FxBlockchain) putReq(req *http.Request) {
*req = http.Request{}
bl.reqPool.Put(req)
}
func prependProtocol(addr string) string {
if strings.HasPrefix(addr, "localhost") || strings.HasPrefix(addr, "127.0.0.1") || strings.HasPrefix(addr, "192.168.") || strings.HasPrefix(addr, "10.") {
return "http://" + addr
}
return "https://" + addr
}
// checkHealth checks the health of the blockchain by querying the /health endpoint.
// It returns an error if the blockchain is currently syncing.
func (bl *FxBlockchain) checkHealth(ctx context.Context) error {
// Removed Health check as it is not needed
return nil
}
func (bl *FxBlockchain) callBlockchain(ctx context.Context, method string, action string, p interface{}) ([]byte, int, error) {
// Check blockchain health before proceeding
if err := bl.checkHealth(ctx); err != nil {
return nil, http.StatusFailedDependency, err // Use 424 as the status code for a syncing blockchain
}
endpoint := prependProtocol(bl.blockchainEndPoint)
addr := endpoint + "/" + strings.Replace(action, "-", "/", -1)
// Use the bufPool and reqPool to reuse bytes.Buffer and http.Request objects
buf := bl.bufPool.Get().(*bytes.Buffer)
req := bl.reqPool.Get().(*http.Request)
defer func() {
bl.putBuf(buf)
bl.putReq(req)
}()
preparedRequest := bl.PlugSeedIfNeeded(ctx, action, p)
if err := json.NewEncoder(buf).Encode(preparedRequest); err != nil {
return nil, 0, err
}
req, err := http.NewRequestWithContext(ctx, method, addr, buf)
if err != nil {
return nil, 0, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := bl.ch.Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
var bufRes bytes.Buffer
_, err = io.Copy(&bufRes, resp.Body)
if err != nil {
return nil, resp.StatusCode, err
}
b := bufRes.Bytes()
return b, resp.StatusCode, nil
}
// ChainConfig represents the configuration for an EVM chain
type ChainConfig struct {
Name string
ChainID int64
RPC string
BackupRPC string
Contract string
}
// GetChainConfigs returns the available chain configurations
func GetChainConfigs() map[string]ChainConfig {
return map[string]ChainConfig{
"base": {
Name: "base",
ChainID: 8453,
RPC: "https://base-rpc.publicnode.com",
BackupRPC: "https://1rpc.io/base",
Contract: "0xb093fF4B3B3B87a712107B26566e0cCE5E752b4D",
},
"skale": {
Name: "skale",
ChainID: 2046399126,
RPC: "https://mainnet.skalenodes.com/v1/elated-tan-skat",
Contract: "0xf9176Ffde541bF0aa7884298Ce538c471Ad0F015",
},
}
}
// callEVMChain makes calls to EVM-compatible chains (Base/Skale) using JSON-RPC
func (bl *FxBlockchain) callEVMChain(ctx context.Context, chainName string, method string, params []interface{}) ([]byte, int, error) {
chainConfigs := GetChainConfigs()
chainConfig, exists := chainConfigs[chainName]
if !exists {
return nil, http.StatusBadRequest, fmt.Errorf("unsupported chain: %s", chainName)
}
// Prepare JSON-RPC request
rpcRequest := map[string]interface{}{
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": 1,
}
// Use the bufPool and reqPool to reuse bytes.Buffer and http.Request objects
buf := bl.bufPool.Get().(*bytes.Buffer)
req := bl.reqPool.Get().(*http.Request)
defer func() {
bl.putBuf(buf)
bl.putReq(req)
}()
if err := json.NewEncoder(buf).Encode(rpcRequest); err != nil {
return nil, 0, fmt.Errorf("failed to encode JSON-RPC request: %w", err)
}
// Try primary RPC first
rpcURL := chainConfig.RPC
httpReq, err := http.NewRequestWithContext(ctx, "POST", rpcURL, buf)
if err != nil {
return nil, 0, fmt.Errorf("failed to create HTTP request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := bl.ch.Do(httpReq)
if err != nil && chainConfig.BackupRPC != "" {
// Try backup RPC if primary fails
log.Debugw("Primary RPC failed, trying backup", "chain", chainName, "error", err)
buf.Reset()
if err := json.NewEncoder(buf).Encode(rpcRequest); err != nil {
return nil, 0, fmt.Errorf("failed to encode JSON-RPC request for backup: %w", err)
}
httpReq, err = http.NewRequestWithContext(ctx, "POST", chainConfig.BackupRPC, buf)
if err != nil {
return nil, 0, fmt.Errorf("failed to create backup HTTP request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err = bl.ch.Do(httpReq)
if err != nil {
return nil, 0, fmt.Errorf("both primary and backup RPC failed: %w", err)
}
} else if err != nil {
return nil, 0, fmt.Errorf("RPC call failed: %w", err)
}
defer resp.Body.Close()
var bufRes bytes.Buffer
_, err = io.Copy(&bufRes, resp.Body)
if err != nil {
return nil, resp.StatusCode, fmt.Errorf("failed to read response: %w", err)
}
return bufRes.Bytes(), resp.StatusCode, nil
}
// callEVMChainWithRetry calls EVM chain with retry logic and graceful error handling
func (bl *FxBlockchain) callEVMChainWithRetry(ctx context.Context, chainName string, method string, params []interface{}, maxRetries int) ([]byte, int, error) {
var lastErr error
for attempt := 1; attempt <= maxRetries; attempt++ {
response, statusCode, err := bl.callEVMChain(ctx, chainName, method, params)
if err == nil {
return response, statusCode, nil
}
lastErr = err
log.Debugw("EVM chain call failed, retrying", "chain", chainName, "attempt", attempt, "maxRetries", maxRetries, "error", err)
if attempt < maxRetries {
// Exponential backoff with jitter
backoff := time.Duration(attempt*attempt) * time.Second
select {
case <-ctx.Done():
return nil, 0, ctx.Err()
case <-time.After(backoff):
// Continue to next attempt
}
}
}
return nil, 0, fmt.Errorf("failed after %d attempts: %w", maxRetries, lastErr)
}
func (bl *FxBlockchain) PlugSeedIfNeeded(ctx context.Context, action string, req interface{}) interface{} {
switch action {
case actionSeeded, actionAccountExists, actionAccountFund, actionPoolCreate, actionPoolCancelJoin, actionPoolVote, actionManifestUpload, actionManifestStore, actionManifestRemove, actionManifestRemoveStorer, actionManifestRemoveStored, actionManifestBatchUpload, actionManifestBatchStore, actionTransferToMumbai, actionTransferToGoerli:
seed, err := bl.keyStorer.LoadKey(ctx)
if err != nil {
log.Errorw("seed is empty", "err", err)
seed = ""
}
log.Debugf("seed is %s", seed)
log.Debugf("request is %v", req)
// Make sure we are dealing with a pointer to a struct
val := reflect.ValueOf(req)
if val.Kind() != reflect.Ptr || val.Elem().Kind() != reflect.Struct {
log.Error("req is not a pointer to a struct")
log.Errorf("Invalid req type: %T", req)
return req
}
// Create a new struct based on the req's type and then set the Seed field
reqVal := val.Elem()
seededReqType := reflect.StructOf([]reflect.StructField{
{
Name: "Seed",
Type: reflect.TypeOf(""),
Tag: `json:"seed"`,
},
})
seededReqVal := reflect.New(seededReqType).Elem()
seededReqVal.FieldByName("Seed").SetString(seed)
// Create a new struct that is a combination of the request struct and the Seed field
combinedReqType := reflect.StructOf(append(reflect.VisibleFields(reqVal.Type()), seededReqVal.Type().Field(0)))
combinedReq := reflect.New(combinedReqType).Elem()
// Copy the request struct fields to the new combined struct
for i := 0; i < reqVal.NumField(); i++ {
combinedReq.Field(i).Set(reqVal.Field(i))
}
// Set the Seed field
combinedReq.FieldByName("Seed").SetString(seed)
log.Debugf("seeded request is %v", combinedReq.Interface())
return combinedReq.Interface()
default:
return req
}
}
func convertMobileRequestToFullRequest(mobileReq *ManifestBatchUploadMobileRequest) *ManifestBatchUploadRequest {
manifestMetadata := make([]ManifestMetadata, len(mobileReq.Cid))
for i, cid := range mobileReq.Cid {
manifestMetadata[i] = ManifestMetadata{
Job: ManifestJob{
Work: "Storage",
Engine: "IPFS",
Uri: cid,
},
}
}
replicationFactor := make([]int, len(mobileReq.Cid))
for i := range replicationFactor {
replicationFactor[i] = mobileReq.ReplicationFactor
}
return &ManifestBatchUploadRequest{
Cid: mobileReq.Cid,
PoolID: mobileReq.PoolID,
ReplicationFactor: replicationFactor,
ManifestMetadata: manifestMetadata,
}
}
// dispatch routes an authenticated request to the appropriate handler.
// Called by serveProxy (TCP proxy) after verifying signed headers.
func (bl *FxBlockchain) dispatch(from peer.ID, action string, w http.ResponseWriter, r *http.Request) {
// Define a map of functions with the same signature as handleAction
actionMap := map[string]func(peer.ID, http.ResponseWriter, *http.Request){
actionSeeded: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionSeeded, from, w, r)
},
actionAccountExists: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionAccountExists, from, w, r)
},
actionAssetsBalance: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionAssetsBalance, from, w, r)
},
actionTransferToGoerli: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionTransferToGoerli, from, w, r)
},
actionTransferToMumbai: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionTransferToMumbai, from, w, r)
},
actionPoolCreate: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
//TODO: We should check if from owns the blox
bl.handleAction(http.MethodPost, actionPoolCreate, from, w, r)
},
actionPoolJoin: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.HandlePoolJoin(http.MethodPost, actionPoolJoin, from, w, r)
},
actionPoolCancelJoin: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.HandlePoolCancelJoin(http.MethodPost, actionPoolCancelJoin, from, w, r)
},
actionPoolRequests: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodGet, actionPoolRequests, from, w, r)
},
actionPoolList: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodGet, actionPoolList, from, w, r)
},
actionPoolVote: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionPoolVote, from, w, r)
},
actionPoolLeave: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.HandlePoolLeave(http.MethodPost, actionPoolLeave, from, w, r)
},
actionManifestUpload: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionManifestUpload, from, w, r)
},
actionManifestStore: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionManifestStore, from, w, r)
},
actionManifestAvailable: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionManifestAvailable, from, w, r)
},
actionManifestBatchStore: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionManifestBatchStore, from, w, r)
},
actionManifestBatchUpload: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
// Decode the original mobile request
var mobileReq ManifestBatchUploadMobileRequest
if err := json.NewDecoder(r.Body).Decode(&mobileReq); err != nil {
log.Debug("cannot parse request body: %v", err)
http.Error(w, "", http.StatusBadRequest)
return
}
// Convert to the full request format
fullReq := convertMobileRequestToFullRequest(&mobileReq)
bl.handleActionManifestBatchUpload(http.MethodPost, actionManifestBatchUpload, from, w, r, fullReq)
},
actionManifestRemove: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionManifestRemove, from, w, r)
},
actionManifestRemoveStorer: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionManifestRemoveStorer, from, w, r)
},
actionManifestRemoveStored: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAction(http.MethodPost, actionManifestRemoveStored, from, w, r)
},
actionReplicateInPool: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleReplicateInPool(http.MethodPost, actionReplicateInPool, from, w, r)
},
actionAuth: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAuthorization(from, w, r)
},
actionBloxFreeSpace: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleBloxFreeSpace(from, w, r)
},
actionWifiRemoveall: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleWifiRemoveall(r.Context(), from, w, r)
},
actionReboot: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleReboot(r.Context(), from, w, r)
},
actionPartition: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePartition(r.Context(), from, w, r)
},
actionDeleteFulaConfig: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleDeleteFulaConfig(r.Context(), from, w, r)
},
actionDeleteWifi: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleDeleteWifi(r.Context(), from, w, r)
},
actionDisconnectWifi: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleDisconnectWifi(r.Context(), from, w, r)
},
actionGetAccount: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
// To be removed
},
actionEraseBlData: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleEraseBlData(r.Context(), from, w, r)
},
actionFetchContainerLogs: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleFetchContainerLogs(r.Context(), from, w, r)
},
actionChatWithAI: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleChatWithAI(r.Context(), from, w, r)
},
actionFindBestAndTargetInLogs: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleFindBestAndTargetInLogs(r.Context(), from, w, r)
},
actionGetFolderSize: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleGetFolderSize(r.Context(), from, w, r)
},
actionGetDatastoreSize: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleGetDatastoreSize(r.Context(), from, w, r)
},
actionGetDockerImageBuildDates: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleGetDockerImageBuildDates(from, w, r)
},
actionGetClusterInfo: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleGetClusterInfo(from, w, r)
},
// Plugin actions
actionListPlugins: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePluginAction(r.Context(), from, w, r, actionListPlugins)
},
actionListActivePlugins: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePluginAction(r.Context(), from, w, r, actionListActivePlugins)
},
actionInstallPlugin: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePluginAction(r.Context(), from, w, r, actionInstallPlugin)
},
actionUninstallPlugin: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePluginAction(r.Context(), from, w, r, actionUninstallPlugin)
},
actionShowPluginStatus: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePluginAction(r.Context(), from, w, r, actionShowPluginStatus)
},
actionGetInstallOutput: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePluginAction(r.Context(), from, w, r, actionGetInstallOutput)
},
actionGetInstallStatus: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePluginAction(r.Context(), from, w, r, actionGetInstallStatus)
},
actionUpdatePlugin: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handlePluginAction(r.Context(), from, w, r, actionUpdatePlugin)
},
// Auto-pin actions
actionAutoPinPair: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAutoPinPair(from, w, r)
},
actionAutoPinRefresh: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAutoPinRefresh(from, w, r)
},
actionAutoPinUnpair: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleAutoPinUnpair(from, w, r)
},
}
// Look up the function in the map and call it
handleActionFunc, ok := actionMap[action]
if !ok {
log.Errorw("action not found", "from", from, "action", action)
http.Error(w, "", http.StatusNotFound)
return
}
handleActionFunc(from, w, r)
}
func (bl *FxBlockchain) handleAction(method string, action string, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", action, "from", from)
req := reflect.New(requestTypes[action]).Interface()
res := reflect.New(responseTypes[action]).Interface()
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
}
//TODO: Ensure it is optimized for long-running calls
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 {
log.Error("failed to call blockchain: %v", err)
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
}
// If status code is not 200, attempt to format the response as JSON
if statusCode != http.StatusOK {
w.WriteHeader(statusCode)
var errMsg map[string]interface{}
if jsonErr := json.Unmarshal(response, &errMsg); jsonErr == nil {
// If it's already a JSON, write it as is
w.Write(response)
} else {
// If it's not JSON, wrap the response in the expected format
errMsg = map[string]interface{}{
"message": "Error",
"description": string(response),
}
json.NewEncoder(w).Encode(errMsg)
}
return
}
w.WriteHeader(http.StatusAccepted)
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) handleReplicateInPool(method string, action string, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", action, "from", from)
log.Debug("Processing replicate request")
var req ReplicateRequest
var res ReplicateResponse
var poolRes []string
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, "cannot parse request body", http.StatusBadRequest)
return
}
log.Debugw("Decoded replicate request", "req", req)
//TODO: Ensure it is optimized for long-running calls
ctx, cancel := context.WithTimeout(r.Context(), time.Second*time.Duration(bl.timeout))
defer cancel()
response, statusCode, err := bl.callBlockchain(ctx, method, actionManifestAvailableBatch, req)
if err != nil {
log.Errorw("failed to call blockchain", "err", err)
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
}
// If status code is not 200, attempt to format the response as JSON
if statusCode != http.StatusOK {
log.Errorw("failed to call blockchain", "statusCode", statusCode)
w.WriteHeader(statusCode)
var errMsg map[string]interface{}
if jsonErr := json.Unmarshal(response, &errMsg); jsonErr == nil {
// If it's already a JSON, write it as is
w.Write(response)
} else {
// If it's not JSON, wrap the response in the expected format
errMsg = map[string]interface{}{
"message": "Error",
"description": string(response),
}
json.NewEncoder(w).Encode(errMsg)
}
return
}
if jsonErr := json.Unmarshal(response, &res); jsonErr != nil {
log.Errorw("failed to call blockchain", "jsonErr", jsonErr)
// If the response isn't JSON or can't be parsed, use a generic message
w.WriteHeader(http.StatusFailedDependency)
errMsg := map[string]interface{}{
"message": "An error occurred",
"description": jsonErr.Error(),
}
json.NewEncoder(w).Encode(errMsg)
return
}
log.Debugw("Received replicate response from chain", "res", res)
if len(res.Manifests) == 0 {
log.Errorw("no uploadable manifests could be found", "res.Manifests", res.Manifests)
w.WriteHeader(http.StatusNoContent)
errMsg := map[string]interface{}{
"message": "An error occurred",
"description": "no uploadable manifests could be found",
}
json.NewEncoder(w).Encode(errMsg)
return
}
poolInt, err := strconv.Atoi(bl.topicName)
if err != nil {
log.Errorw("failed to call blockchain poolInt", "err", err)
w.WriteHeader(http.StatusFailedDependency)
errMsg := map[string]interface{}{
"message": "An error occurred",
"description": "endpoint is not a member of valid pool",
}
json.NewEncoder(w).Encode(errMsg)
return
}
log.Debugw("Pool in replicate is", "poolInt", poolInt)
if req.PoolID != poolInt {
log.Errorw("Endpoint is not a member of requested replication pool", "req.PoolID", req.PoolID, "poolInt", poolInt)
w.WriteHeader(http.StatusFailedDependency)
errMsg := map[string]interface{}{
"message": "An error occurred",
"description": "Endpoint is not a member of requested replication pool",
}
json.NewEncoder(w).Encode(errMsg)
return
}
if bl.ipfsClusterApi == nil {
log.Errorw("ipfs cluster API is nil", "bl.ipfsClusterApi", bl.ipfsClusterApi)
w.WriteHeader(http.StatusFailedDependency)
errMsg := map[string]interface{}{
"message": "An error occurred",
"description": "ipfs cluster API is nil",
}
json.NewEncoder(w).Encode(errMsg)
return
}
pCtx, pCancel := context.WithTimeout(r.Context(), time.Second*time.Duration(bl.timeout))
defer pCancel()
pinOptions := ipfsClusterClientApi.PinOptions{
Mode: 0,
}
for i := 0; i < len(res.Manifests); i++ {
c, err := cid.Decode(res.Manifests[i].Cid)
if err != nil {
log.Errorw("Error decoding CID:", "err", err)
continue // Or handle the error appropriately
}
replicationRes, err := bl.ipfsClusterApi.Pin(pCtx, ipfsClusterClientApi.NewCid(c), pinOptions)
if err != nil {
log.Errorw("Error pinning CID:", "err", err)
continue
}
poolRes = append(poolRes, replicationRes.Cid.Cid.String())
}
w.WriteHeader(http.StatusAccepted)
if err := json.NewEncoder(w).Encode(poolRes); err != nil {
log.Error("failed to write response: %v", err)
}
}
func (bl *FxBlockchain) handleAuthorization(from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionAuth, "from", from)
defer r.Body.Close()
b, err := io.ReadAll(r.Body)
if err != nil {
log.Errorw("failed to read request body", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
var a authorizationRequest
if err := json.Unmarshal(b, &a); err != nil {
log.Debugw("cannot parse request body", "err", err)
http.Error(w, "", http.StatusBadRequest)
return
}
bl.authorizedPeersLock.Lock()
if a.Allow {
bl.authorizedPeers[a.Subject] = struct{}{}
} else {
delete(bl.authorizedPeers, a.Subject)
}
bl.authorizedPeersLock.Unlock()
w.WriteHeader(http.StatusOK)
}
func (bl *FxBlockchain) handleBloxFreeSpace(from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionBloxFreeSpace, "from", from)
out, err := wifi.GetBloxFreeSpace()
if err != nil {
log.Error("failed to getBloxFreeSpace: %v", err)
out = wifi.BloxFreeSpaceResponse{
DeviceCount: 0,
Size: 0,
Used: 0,
Avail: 0,
UsedPercentage: 0,
}
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}
}
func (bl *FxBlockchain) handleEraseBlData(ctx context.Context, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionEraseBlData, "from", from)
out := wifi.EraseBlData(ctx)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}
}
func (bl *FxBlockchain) handleWifiRemoveall(ctx context.Context, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionWifiRemoveall, "from", from)
out := wifi.WifiRemoveall(ctx)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}
}
func (bl *FxBlockchain) handleReboot(ctx context.Context, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionReboot, "from", from)
out := wifi.Reboot(ctx)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}
}
func (bl *FxBlockchain) handlePartition(ctx context.Context, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionPartition, "from", from)
out := wifi.Partition(ctx)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}
}
func (bl *FxBlockchain) handleDeleteFulaConfig(ctx context.Context, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionDeleteFulaConfig, "from", from)
out := wifi.DeleteFulaConfig(ctx)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}
}
func (bl *FxBlockchain) handleDeleteWifi(ctx context.Context, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionDeleteWifi, "from", from)
// Parse the JSON body of the request into the DeleteWifiRequest struct
var req wifi.DeleteWifiRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Error("failed to decode request: %v", err)
http.Error(w, "failed to decode request", http.StatusBadRequest)
return
}
log.Debugw("handleDeleteWifi received", "req", req)
out := wifi.DeleteWifi(ctx, req)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}
}
func (bl *FxBlockchain) handleDisconnectWifi(ctx context.Context, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionDisconnectWifi, "from", from)
// Parse the JSON body of the request into the DeleteWifiRequest struct
var req wifi.DeleteWifiRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Error("failed to decode request: %v", err)
http.Error(w, "failed to decode request", http.StatusBadRequest)
return
}
log.Debugw("handleDisconnectWifi received", "req", req)
out := wifi.DisconnectNamedWifi(ctx, req)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}
}
func (bl *FxBlockchain) SetAuth(ctx context.Context, on peer.ID, subject peer.ID, allow bool) error {
// Only local auth is supported now (no libp2p host for remote calls)
if on != bl.selfPeerID {
log.Warnw("Remote SetAuth not supported without libp2p host", "on", on, "subject", subject)
return fmt.Errorf("remote SetAuth not supported: target %s is not local peer %s", on, bl.selfPeerID)
}