-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexample_test.go
955 lines (867 loc) · 28.2 KB
/
example_test.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
package fulamobile_test
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/functionland/go-fula/blox"
"github.com/functionland/go-fula/exchange"
fulamobile "github.com/functionland/go-fula/mobile"
"github.com/ipfs/go-cid"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
)
var log = logging.Logger("fula/fulamobile")
// requestLoggerMiddleware logs the details of each request
func requestLoggerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Log the request
body, _ := io.ReadAll(r.Body)
log.Debugw("Received request", "url", r.URL.Path, "method", r.Method, "body", string(body))
if r.URL.Path == "/fula/pool/vote" {
fmt.Printf("Voted on QmUg1bGBZ1rSNt3LZR7kKf9RDy3JtJLZZDZGKrzSP36TMe %s", string(body))
}
// Create a new io.Reader from the read body as the original body is now drained
r.Body = io.NopCloser(bytes.NewBuffer(body))
// Call the next handler
next.ServeHTTP(w, r)
})
}
func startMockServer(addr string) *http.Server {
handler := http.NewServeMux()
handler.HandleFunc("/fula/pool/join", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"pool_id": 1,
"account": "12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q",
}
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/fula/pool/cancel_join", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"pool_id": 1,
"account": "12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q",
}
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/fula/pool/poolrequests", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"poolrequests": []map[string]interface{}{
{
"pool_id": 1,
"account": "12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q",
"voted": []string{},
"positive_votes": 0,
"peer_id": "12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q",
},
},
}
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/fula/pool/all", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"pools": []map[string]interface{}{
{
"pool_id": 1,
"creator": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"pool_name": "PoolTest1",
"region": "Ontario",
"parent": nil,
"participants": []string{
"12D3KooWQfGkPUkoLDEeJE3H3ZTmu9BZvAdbJpmhha8WpjeSLKMM",
"12D3KooWH9swjeCyuR6utzKU1UspiW5RDGzAFvNDwqkT5bUHwuxX",
"12D3KooWRde3N9rHE8vEyzTiPMVBvs1RpjS4oaWjVkfAt17412vX",
},
},
},
}
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/fula/pool/users", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"users": []map[string]interface{}{
{
"account": "12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q",
"pool_id": nil,
"request_pool_id": 1,
"peer_id": "12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q",
},
{
"account": "12D3KooWQfGkPUkoLDEeJE3H3ZTmu9BZvAdbJpmhha8WpjeSLKMM",
"pool_id": 1,
"request_pool_id": nil,
"peer_id": "12D3KooWQfGkPUkoLDEeJE3H3ZTmu9BZvAdbJpmhha8WpjeSLKMM",
},
{
"account": "12D3KooWH9swjeCyuR6utzKU1UspiW5RDGzAFvNDwqkT5bUHwuxX",
"pool_id": 1,
"request_pool_id": nil,
"peer_id": "12D3KooWH9swjeCyuR6utzKU1UspiW5RDGzAFvNDwqkT5bUHwuxX",
},
{
"account": "12D3KooWRde3N9rHE8vEyzTiPMVBvs1RpjS4oaWjVkfAt17412vX",
"pool_id": 1,
"request_pool_id": nil,
"peer_id": "12D3KooWRde3N9rHE8vEyzTiPMVBvs1RpjS4oaWjVkfAt17412vX",
},
},
}
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/account/seeded", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"seed": "0xf78b1faa75bb6b33b3207de64867c1465a151ae5ebb2793309b87260dca9ff62",
"account": "5GEottBB4kGzpN6imRwpnhyVDtKMTSYHYZvT4Rq93dchjN45",
}
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/fula/pool/vote", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"pool_id": 1,
"account": "12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q",
}
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/fula/manifest/available", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"manifests": []map[string]interface{}{
{
"pool_id": 1,
"manifest_metadata": map[string]interface{}{
"job": map[string]string{
"engine": "IPFS",
"uri": "bafyreidulpo7on77a6pkq7c6da5mlj4n2p3av2zjomrpcpeht5zqgafc34",
"work": "Storage",
},
},
"replication_available": 2,
},
{
"pool_id": 1,
"manifest_metadata": map[string]interface{}{
"job": map[string]string{
"engine": "IPFS",
"uri": "bafyreibzsetfhqrayathm5tkmm7axuljxcas3pbqrncrosx2fiky4wj5gy",
"work": "Storage",
},
},
"replication_available": 1,
},
},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/fula/pool/leave", func(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"pool_id": 1,
"account": "12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q",
}
json.NewEncoder(w).Encode(response)
})
handler.HandleFunc("/fula/manifest/batch_storage", func(w http.ResponseWriter, r *http.Request) {
var reqBody struct {
CIDs []string `json:"cid"`
PoolID int `json:"pool_id"`
}
// Decode the JSON body of the request
if err := json.NewDecoder(r.Body).Decode(&reqBody); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Make sure to close the request body
defer r.Body.Close()
// Use the CIDs from the request in the response
response := map[string]interface{}{
"pool_id": reqBody.PoolID,
"cid": reqBody.CIDs,
}
// Encode the response as JSON
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
// Wrap the handlers with the logging middleware
loggedHandler := requestLoggerMiddleware(handler)
// Create an HTTP server
server := &http.Server{
Addr: addr,
Handler: loggedHandler,
}
// Start the server in a new goroutine
go func() {
if err := server.ListenAndServe(); err != http.ErrServerClosed {
panic(err) // Handle the error as you see fit
}
}()
// Give the server a moment to start
time.Sleep(time.Millisecond * 100)
return server
}
func generateIdentity(id int) crypto.PrivKey {
var pid crypto.PrivKey
switch id {
case 1: //12D3KooWQfGkPUkoLDEeJE3H3ZTmu9BZvAdbJpmhha8WpjeSLKMM
key1 := "CAESQJ5GGDgYMGs8eWNCSotGC/qnuw3pfwtG6XcAumHc4CR33IrywkIsmSlMOK7RdP78RgFmYgyrZxz7fP1xux0I88w="
km1, err := base64.StdEncoding.DecodeString(key1)
if err != nil {
panic(err)
}
pid, err = crypto.UnmarshalPrivateKey(km1)
if err != nil {
panic(err)
}
case 2: //12D3KooWH9swjeCyuR6utzKU1UspiW5RDGzAFvNDwqkT5bUHwuxX
key2 := "CAESQHSuiy3FbrTSh7MzXI6coF52bTXrtx3ZorFzIbKnZeBAbQGC6PMp90hKgAiM4yW5/TkRBQhqgPN99AwdiLOS27Q="
km2, err := base64.StdEncoding.DecodeString(key2)
if err != nil {
panic(err)
}
pid, err = crypto.UnmarshalPrivateKey(km2)
if err != nil {
panic(err)
}
case 3: //12D3KooWRde3N9rHE8vEyzTiPMVBvs1RpjS4oaWjVkfAt17412vX
key3 := "CAESQHAfwsoKLRHraOpYeV6DBjWeG4B9PpSWLyMym2modqej6vuMoMJ5FiA1ivOyihgJxeqKsVue/9cjKlxSNoMQCrQ="
km3, err := base64.StdEncoding.DecodeString(key3)
if err != nil {
panic(err)
}
pid, err = crypto.UnmarshalPrivateKey(km3)
if err != nil {
panic(err)
}
case 4: //12D3KooWRTzN7HfmjoUBHokyRZuKdyohVVSGqKBMF24ZC3tGK78Q
key4 := "CAESQCKbGJG9XDbfUEMjie3vZYVk9RgXHXCLjTMeBidltp396IK4gNRCMmGbjZeG+ZN4FC+yCLDNB1Vzbg66DaeHvCU="
km4, err := base64.StdEncoding.DecodeString(key4)
if err != nil {
panic(err)
}
pid, err = crypto.UnmarshalPrivateKey(km4)
if err != nil {
panic(err)
}
}
return pid
}
func updatePoolName(newPoolName string) error {
return nil
}
func Example_poolExchangeDagBetweenClientBlox() {
server := startMockServer("127.0.0.1:4004")
defer func() {
// Shutdown the server after test
if err := server.Shutdown(context.Background()); err != nil {
log.Error("Error happened in server.Shutdown")
panic(err) // Handle the error as you see fit
}
}()
const poolName = "1"
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// Elevate log level to show internal communications.
if err := logging.SetLogLevel("*", "debug"); err != nil {
log.Error("Error happened in logging.SetLogLevel")
panic(err)
}
// Use a deterministic random generator to generate deterministic
// output for the example.
// Instantiate the first node in the pool
h1, err := libp2p.New(libp2p.Identity(generateIdentity(1)))
if err != nil {
log.Errorw("Error happened in libp2p.New", "err", err)
panic(err)
}
n1, err := blox.New(
blox.WithHost(h1),
blox.WithPoolName("1"),
blox.WithUpdatePoolName(updatePoolName),
blox.WithBlockchainEndPoint("127.0.0.1:4004"),
blox.WithPingCount(5),
blox.WithExchangeOpts(
exchange.WithIpniGetEndPoint("http://127.0.0.1:4004/cid/"),
),
)
if err != nil {
log.Errorw("Error happened in blox.New", "err", err)
panic(err)
}
if err := n1.Start(ctx); err != nil {
log.Errorw("Error happened in n1.Start", "err", err)
panic(err)
}
defer n1.Shutdown(ctx)
fmt.Printf("Instantiated node in pool %s with ID: %s\n", poolName, h1.ID().String())
mcfg := fulamobile.NewConfig()
mcfg.AllowTransientConnection = true
bloxAddrString := ""
if len(h1.Addrs()) > 0 {
// Convert the first multiaddr to a string
bloxAddrString = h1.Addrs()[0].String()
log.Infow("blox multiadddr is", "addr", bloxAddrString, "peerID", h1.ID().String())
} else {
log.Errorw("Error happened in h1.Addrs", "err", "No addresses in slice")
panic("No addresses in slice")
}
mcfg.BloxAddr = bloxAddrString + "/p2p/" + h1.ID().String()
mcfg.PoolName = "1"
mcfg.Exchange = bloxAddrString
mcfg.BlockchainEndpoint = "127.0.0.1:4004"
log.Infow("bloxAdd string created", "addr", bloxAddrString+"/p2p/"+h1.ID().String())
c1, err := fulamobile.NewClient(mcfg)
if err != nil {
log.Errorw("Error happened in fulamobile.NewClient", "err", err)
panic(err)
}
// Authorize exchange between the two nodes
mobilePeerIDString := c1.ID()
log.Infof("first client created with ID: %s", mobilePeerIDString)
mpid, err := peer.Decode(mobilePeerIDString)
if err != nil {
log.Errorw("Error happened in peer.Decode", "err", err)
panic(err)
}
if err := n1.SetAuth(ctx, h1.ID(), mpid, true); err != nil {
log.Error("Error happened in n1.SetAuth")
panic(err)
}
err = c1.ConnectToBlox()
if err != nil {
log.Errorw("Error happened in c1.ConnectToBlox", "err", err)
panic(err)
}
_, err = c1.BloxFreeSpace()
if err != nil {
panic(err)
}
rawData := []byte("some raw data")
fmt.Printf("Original Val is: %s\n", string(rawData))
rawCodec := int64(0x55)
linkBytes, err := c1.Put(rawData, rawCodec)
if err != nil {
fmt.Printf("Error storing the raw data: %v", err)
return
}
c, err := cid.Cast(linkBytes)
if err != nil {
fmt.Printf("Error casting bytes to CID: %v", err)
return
}
fmt.Printf("Stored raw data link: %s\n", c.String())
log.Infof("Stored raw data link: %s", c.String())
recentCids, err := c1.ListRecentCidsAsStringWithChildren()
if err != nil {
log.Errorw("Error happened in ListRecentCidsAsStringWithChildre", "err", err)
panic(err)
}
for recentCids.HasNext() {
cid, err := recentCids.Next()
if err != nil {
fmt.Printf("Error retrieving next CID: %v", err)
log.Errorf("Error retrieving next CID: %v", err)
// Decide if you want to break or continue based on your error handling strategy
break
}
fmt.Printf("recentCid link: %s\n", cid) // Print each CID
log.Infof("recentCid link: %s", cid)
}
fmt.Print("Waiting for 5 seconds\n")
time.Sleep(5 * time.Second)
fmt.Printf("Now fetching the link %x\n", linkBytes)
log.Infof("Now fetching the link %x", linkBytes)
c2, err := fulamobile.NewClient(mcfg)
if err != nil {
log.Errorw("Error happened in fulamobile.NewClient2", "err", err)
panic(err)
}
mobilePeerIDString2 := c2.ID()
log.Infof("second client created with ID: %s", mobilePeerIDString2)
mpid2, err := peer.Decode(mobilePeerIDString2)
if err != nil {
log.Errorw("Error happened in peer.Decode2", "err", err)
panic(err)
}
if err := n1.SetAuth(ctx, h1.ID(), mpid2, true); err != nil {
log.Errorw("Error happened in n1.SetAuth2", "err", err)
panic(err)
}
err = c2.ConnectToBlox()
if err != nil {
log.Errorw("Error happened in c2.ConnectToBlox", "err", err)
panic(err)
}
/*
//If you uncomment this section, it just fetches the cid that blox stored and not with the key that mobile has
ct, err := cid.Decode("bafyreibcwjmj25zyylzw36xaglokmmcbk7c4tqtouaz7qmw6nskx5iqgqi")
if err != nil {
fmt.Println("Error decoding CID:", err)
return
}
linkBytes = ct.Bytes()
//
*/
val, err := c2.Get(linkBytes)
if err != nil {
log.Errorw("Error happened in c2.Get", "err", err)
panic(err)
}
fmt.Printf("Fetched Val is: %s\n", string(val))
log.Infof("Fetched Val is: %v", val)
log.Infof("Original Val is: %v", rawData)
if !bytes.Equal(val, rawData) {
panic(fmt.Sprintf("Original data is not equal to fetched data: [original] %s != [fetch] %s", string(val), string(rawData)))
}
// Output:
// Instantiated node in pool 1 with ID: 12D3KooWQfGkPUkoLDEeJE3H3ZTmu9BZvAdbJpmhha8WpjeSLKMM
// Original Val is: some raw data
// Stored raw data link: bafkr4ifmwbmdrkxep3mci37ionvgturlylvganap4ch7ouia2ui5tmr4iy
// recentCid link: bafkr4ifmwbmdrkxep3mci37ionvgturlylvganap4ch7ouia2ui5tmr4iy
// Waiting for 5 seconds
// Now fetching the link 01551e20acb05838aae47ed8246fe8736a69d22bc2ea60340fe08ff75100d511d9b23c46
// Fetched Val is: some raw data
}
func Example_listRecentCidsWithChildren() {
// Elevate log level to show internal communications.
if err := logging.SetLogLevel("*", "debug"); err != nil {
log.Error("Error happened in logging.SetLogLevel")
panic(err)
}
mcfg := fulamobile.NewConfig()
mcfg.AllowTransientConnection = true
mcfg.BloxAddr = ""
mcfg.PoolName = "1"
mcfg.Exchange = "noop"
mcfg.BlockchainEndpoint = ""
c1, err := fulamobile.NewClient(mcfg)
if err != nil {
log.Errorw("Error happened in fulamobile.NewClient", "err", err)
panic(err)
}
// Authorize exchange between the two nodes
mobilePeerIDString := c1.ID()
log.Infof("first client created with ID: %s", mobilePeerIDString)
mpid, err := peer.Decode(mobilePeerIDString)
if err != nil {
log.Errorw("Error happened in peer.Decode", "err", err)
panic(err)
}
log.Infof("mpid is %s", mpid)
rawData := []byte("some raw data")
fmt.Printf("Original Val is: %s\n", string(rawData))
rawCodec := int64(0x55)
linkBytes, err := c1.Put(rawData, rawCodec)
if err != nil {
fmt.Printf("Error storing the raw data: %v", err)
return
}
c, err := cid.Cast(linkBytes)
if err != nil {
fmt.Printf("Error casting bytes to CID: %v", err)
return
}
fmt.Printf("Stored raw data link: %s\n", c.String())
log.Infof("Stored raw data link: %s", c.String())
recentCids, err := c1.ListRecentCidsAsStringWithChildren()
if err != nil {
log.Errorw("Error happened in ListRecentCidsAsStringWithChildren", "err", err)
panic(err)
}
for recentCids.HasNext() {
cid, err := recentCids.Next()
if err != nil {
fmt.Printf("Error retrieving next CID: %v", err)
log.Errorf("Error retrieving next CID: %v", err)
// Decide if you want to break or continue based on your error handling strategy
break
}
fmt.Printf("recentCid link: %s\n", cid) // Print each CID
log.Infof("recentCid link: %s", cid)
}
// Output:
// Original Val is: some raw data
// Stored raw data link: bafkr4ifmwbmdrkxep3mci37ionvgturlylvganap4ch7ouia2ui5tmr4iy
// recentCid link: bafkr4ifmwbmdrkxep3mci37ionvgturlylvganap4ch7ouia2ui5tmr4iy
}
func Example_poolExchangeLargeDagBetweenClientBlox() {
server := startMockServer("127.0.0.1:4004")
defer func() {
// Shutdown the server after test
if err := server.Shutdown(context.Background()); err != nil {
log.Error("Error happened in server.Shutdown")
panic(err) // Handle the error as you see fit
}
}()
const poolName = "1"
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// Elevate log level to show internal communications.
if err := logging.SetLogLevel("*", "debug"); err != nil {
log.Error("Error happened in logging.SetLogLevel")
panic(err)
}
// Use a deterministic random generator to generate deterministic
// output for the example.
// Instantiate the first node in the pool
h1, err := libp2p.New(libp2p.Identity(generateIdentity(1)))
if err != nil {
log.Errorw("Error happened in libp2p.New", "err", err)
panic(err)
}
n1, err := blox.New(
blox.WithHost(h1),
blox.WithPoolName("1"),
blox.WithUpdatePoolName(updatePoolName),
blox.WithBlockchainEndPoint("127.0.0.1:4004"),
blox.WithPingCount(5),
blox.WithExchangeOpts(
exchange.WithIpniGetEndPoint("http://127.0.0.1:4004/cid/"),
),
)
if err != nil {
log.Errorw("Error happened in blox.New", "err", err)
panic(err)
}
if err := n1.Start(ctx); err != nil {
log.Errorw("Error happened in n1.Start", "err", err)
panic(err)
}
defer n1.Shutdown(ctx)
fmt.Printf("Instantiated node in pool %s with ID: %s\n", poolName, h1.ID().String())
mcfg := fulamobile.NewConfig()
mcfg.AllowTransientConnection = true
bloxAddrString := ""
if len(h1.Addrs()) > 0 {
// Convert the first multiaddr to a string
bloxAddrString = h1.Addrs()[0].String()
log.Infow("blox multiadddr is", "addr", bloxAddrString, "peerID", h1.ID().String())
} else {
log.Errorw("Error happened in h1.Addrs", "err", "No addresses in slice")
panic("No addresses in slice")
}
mcfg.BloxAddr = bloxAddrString + "/p2p/" + h1.ID().String()
mcfg.PoolName = "1"
mcfg.Exchange = bloxAddrString
mcfg.AllowTransientConnection = true
mcfg.DisableResourceManger = false
mcfg.StaticRelays = []string{}
mcfg.BlockchainEndpoint = "127.0.0.1:4004"
log.Infow("bloxAdd string created", "addr", bloxAddrString+"/p2p/"+h1.ID().String())
c1, err := fulamobile.NewClient(mcfg)
if err != nil {
log.Errorw("Error happened in fulamobile.NewClient", "err", err)
panic(err)
}
// Authorize exchange between the two nodes
mobilePeerIDString := c1.ID()
log.Infof("first client created with ID: %s", mobilePeerIDString)
mpid, err := peer.Decode(mobilePeerIDString)
if err != nil {
log.Errorw("Error happened in peer.Decode", "err", err)
panic(err)
}
if err := n1.SetAuth(ctx, h1.ID(), mpid, true); err != nil {
log.Error("Error happened in n1.SetAuth")
panic(err)
}
err = c1.ConnectToBlox()
if err != nil {
log.Errorw("Error happened in c1.ConnectToBlox", "err", err)
panic(err)
}
_, err = c1.BloxFreeSpace()
if err != nil {
panic(err)
}
rawCodec := int64(0x55)
const totalSize = 200 * 1024 * 1024 // 50MB
const chunkSize = 256 * 1024 // 256KB
data := make([]byte, totalSize) // replace with actual data if needed
// Fill the data with random values (or use actual data)
rand.Read(data)
var links [][]byte
var chunkedData [][]byte
for i := 0; i < totalSize; i += chunkSize {
end := i + chunkSize
if end > totalSize {
end = totalSize
}
chunk := data[i:end]
log.Debugf("Storing chunk %d to %d...\n", i, end)
linkBytes, err := c1.Put(chunk, rawCodec)
if err != nil {
log.Errorf("Error storing chunk: %v\n", err)
return
}
links = append(links, linkBytes)
chunkedData = append(chunkedData, chunk)
}
fmt.Printf("Stored %d chunks\n", len(links))
log.Infof("Stored %d chunks\n", len(links))
recentCids, err := c1.ListRecentCidsAsString()
if err != nil {
log.Errorw("Error happened in ListRecentCidsAsString", "err", err)
panic(err)
}
var count = 0
for recentCids.HasNext() {
count = count + 1
}
log.Infof("recentCids count: %d", count)
fmt.Printf("recentCids count: %d\n", count) // Print each CID
if count != len(links) {
panic("recent cids count is not equal to put links count")
}
fmt.Print("Waiting for 5 seconds\n")
time.Sleep(5 * time.Second)
fmt.Printf("Now fetching the links\n")
log.Infof("Now fetching the links")
c2, err := fulamobile.NewClient(mcfg)
if err != nil {
log.Errorw("Error happened in fulamobile.NewClient2", "err", err)
panic(err)
}
mobilePeerIDString2 := c2.ID()
log.Infof("second client created with ID: %s", mobilePeerIDString2)
mpid2, err := peer.Decode(mobilePeerIDString2)
if err != nil {
log.Errorw("Error happened in peer.Decode2", "err", err)
panic(err)
}
if err := n1.SetAuth(ctx, h1.ID(), mpid2, true); err != nil {
log.Errorw("Error happened in n1.SetAuth2", "err", err)
panic(err)
}
err = c2.ConnectToBlox()
if err != nil {
log.Errorw("Error happened in c2.ConnectToBlox", "err", err)
panic(err)
}
/*
//If you uncomment this section, it just fetches the cid that blox stored and not with the key that mobile has
ct, err := cid.Decode("bafyreibcwjmj25zyylzw36xaglokmmcbk7c4tqtouaz7qmw6nskx5iqgqi")
if err != nil {
fmt.Println("Error decoding CID:", err)
return
}
linkBytes = ct.Bytes()
//
*/
count = 0
for _, link := range links {
log.Debugf("Fetching link: %s\n", link)
val, err := c2.Get(link)
if err != nil {
log.Fatal("Error fetching link", err)
panic(err)
}
log.Debugf("Fetched chunk size: %d\n", len(val))
if !bytes.Equal(val, chunkedData[count]) {
c, err := cid.Cast(link)
if err != nil {
log.Errorf("Error casting bytes to CID: %v\n", err)
panic(err)
}
panic(fmt.Sprintf("Original data is not equal to fetched data for count: %d for cid: %s: original data size:%d, retrieved data size:%d", count, c, len(chunkedData[count]), len(val)))
}
count = count + 1
}
fmt.Print("All chunks fetched")
// Output:
// Instantiated node in pool 1 with ID: 12D3KooWQfGkPUkoLDEeJE3H3ZTmu9BZvAdbJpmhha8WpjeSLKMM
// Stored 800 chunks
// recentCids count: 800
// Waiting for 5 seconds
// Now fetching the links
// All chunks fetched
}
func Example_blockchainCalls() {
server := startMockServer("127.0.0.1:4004")
defer func() {
// Shutdown the server after test
if err := server.Shutdown(context.Background()); err != nil {
log.Error("Error happened in server.Shutdown")
panic(err) // Handle the error as you see fit
}
}()
const poolName = "1"
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// Elevate log level to show internal communications.
if err := logging.SetLogLevel("*", "info"); err != nil {
log.Error("Error happened in logging.SetLogLevel")
panic(err)
}
// Use a deterministic random generator to generate deterministic
// output for the example.
// Instantiate the first node in the pool
h1, err := libp2p.New(libp2p.Identity(generateIdentity(1)))
if err != nil {
log.Errorw("Error happened in libp2p.New", "err", err)
panic(err)
}
n1, err := blox.New(
blox.WithHost(h1),
blox.WithPoolName("1"),
blox.WithUpdatePoolName(updatePoolName),
blox.WithBlockchainEndPoint("127.0.0.1:4004"),
blox.WithPingCount(5),
blox.WithExchangeOpts(
exchange.WithIpniGetEndPoint("http://127.0.0.1:4004/cid/"),
),
)
if err != nil {
log.Errorw("Error happened in blox.New", "err", err)
panic(err)
}
if err := n1.Start(ctx); err != nil {
log.Errorw("Error happened in n1.Start", "err", err)
panic(err)
}
defer n1.Shutdown(ctx)
fmt.Printf("Instantiated node in pool %s with ID: %s\n", poolName, h1.ID().String())
mcfg := fulamobile.NewConfig()
mcfg.AllowTransientConnection = true
bloxAddrString := ""
if len(h1.Addrs()) > 0 {
// Convert the first multiaddr to a string
bloxAddrString = h1.Addrs()[0].String()
log.Infow("blox multiadddr is", "addr", bloxAddrString, "peerID", h1.ID().String())
} else {
log.Errorw("Error happened in h1.Addrs", "err", "No addresses in slice")
panic("No addresses in slice")
}
mcfg.BloxAddr = bloxAddrString + "/p2p/" + h1.ID().String()
mcfg.PoolName = "1"
mcfg.Exchange = bloxAddrString
mcfg.BlockchainEndpoint = "127.0.0.1:4004"
log.Infow("bloxAdd string created", "addr", bloxAddrString+"/p2p/"+h1.ID().String())
c1, err := fulamobile.NewClient(mcfg)
if err != nil {
log.Errorw("Error happened in fulamobile.NewClient", "err", err)
panic(err)
}
// Authorize exchange between the two nodes
mobilePeerIDString := c1.ID()
log.Infof("first client created with ID: %s", mobilePeerIDString)
mpid, err := peer.Decode(mobilePeerIDString)
if err != nil {
log.Errorw("Error happened in peer.Decode", "err", err)
panic(err)
}
if err := n1.SetAuth(ctx, h1.ID(), mpid, true); err != nil {
log.Error("Error happened in n1.SetAuth")
panic(err)
}
err = c1.ConnectToBlox()
if err != nil {
log.Errorw("Error happened in c1.ConnectToBlox", "err", err)
panic(err)
}
account, err := c1.GetAccount()
if err != nil {
panic(err)
}
fmt.Printf("account is %s", account)
// Output:
// Instantiated node in pool 1 with ID: 12D3KooWQfGkPUkoLDEeJE3H3ZTmu9BZvAdbJpmhha8WpjeSLKMM
// account is {"account":"5GEottBB4kGzpN6imRwpnhyVDtKMTSYHYZvT4Rq93dchjN45"}
}
func Example_listPlugins() {
server := startMockServer("127.0.0.1:4004")
defer func() {
// Shutdown the server after test
if err := server.Shutdown(context.Background()); err != nil {
log.Error("Error happened in server.Shutdown")
panic(err) // Handle the error as you see fit
}
}()
const poolName = "1"
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// Elevate log level to show internal communications.
if err := logging.SetLogLevel("*", "info"); err != nil {
log.Error("Error happened in logging.SetLogLevel")
panic(err)
}
// Use a deterministic random generator to generate deterministic
// output for the example.
// Instantiate the first node in the pool
h1, err := libp2p.New(libp2p.Identity(generateIdentity(1)))
if err != nil {
log.Errorw("Error happened in libp2p.New", "err", err)
panic(err)
}
n1, err := blox.New(
blox.WithHost(h1),
blox.WithPoolName("1"),
blox.WithUpdatePoolName(updatePoolName),
blox.WithBlockchainEndPoint("127.0.0.1:4004"),
blox.WithPingCount(5),
blox.WithExchangeOpts(
exchange.WithIpniGetEndPoint("http://127.0.0.1:4004/cid/"),
),
)
if err != nil {
log.Errorw("Error happened in blox.New", "err", err)
panic(err)
}
if err := n1.Start(ctx); err != nil {
log.Errorw("Error happened in n1.Start", "err", err)
panic(err)
}
defer n1.Shutdown(ctx)
fmt.Printf("Instantiated node in pool %s with ID: %s\n", poolName, h1.ID().String())
mcfg := fulamobile.NewConfig()
mcfg.AllowTransientConnection = true
bloxAddrString := ""
if len(h1.Addrs()) > 0 {
// Convert the first multiaddr to a string
bloxAddrString = h1.Addrs()[0].String()
log.Infow("blox multiadddr is", "addr", bloxAddrString, "peerID", h1.ID().String())
} else {
log.Errorw("Error happened in h1.Addrs", "err", "No addresses in slice")
panic("No addresses in slice")
}
mcfg.BloxAddr = bloxAddrString + "/p2p/" + h1.ID().String()
mcfg.PoolName = "1"
mcfg.Exchange = bloxAddrString
mcfg.BlockchainEndpoint = "127.0.0.1:4004"
log.Infow("bloxAdd string created", "addr", bloxAddrString+"/p2p/"+h1.ID().String())
c1, err := fulamobile.NewClient(mcfg)
if err != nil {
log.Errorw("Error happened in fulamobile.NewClient", "err", err)
panic(err)
}
// Authorize exchange between the two nodes
mobilePeerIDString := c1.ID()
log.Infof("first client created with ID: %s", mobilePeerIDString)
mpid, err := peer.Decode(mobilePeerIDString)
if err != nil {
log.Errorw("Error happened in peer.Decode", "err", err)
panic(err)
}
if err := n1.SetAuth(ctx, h1.ID(), mpid, true); err != nil {
log.Error("Error happened in n1.SetAuth")
panic(err)
}
err = c1.ConnectToBlox()
if err != nil {
log.Errorw("Error happened in c1.ConnectToBlox", "err", err)
panic(err)
}
plugins, err := c1.ListPlugins()
if err != nil {
panic(err)
}
fmt.Printf("account is %v", plugins)
// Output:
// Instantiated node in pool 1 with ID: 12D3KooWQfGkPUkoLDEeJE3H3ZTmu9BZvAdbJpmhha8WpjeSLKMM
// account is {"account":"5GEottBB4kGzpN6imRwpnhyVDtKMTSYHYZvT4Rq93dchjN45"}
}