-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
604 lines (535 loc) · 17 KB
/
main.go
File metadata and controls
604 lines (535 loc) · 17 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
package main
import (
"context"
"crypto/ecdsa"
"crypto/rand"
"flag"
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/MultiAdaptive/multiAdaptive-cli/bindings"
"github.com/consensys/gnark-crypto/ecc/bn254/fr/kzg"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
kzgsdk "github.com/multiAdaptive/kzg-sdk"
"log"
"math/big"
"strings"
"time"
)
const (
dataSize = 5 * 1024 * 1024
cmManagerAddress = "0xb945872cbF327DA5CBEb6aE7286ccEE6CAaBA3B2"
nodeManagerAddress = "0xed592c8F0B13bb8A761BFFb6140720D89552999B"
storageManagerAddress = "0x44214b40b88BeD3424b2684bE6b102fD3BCA4a09"
chainID = 11155111
ethUrl = "https://eth-sepolia.public.blastapi.io"
)
var privateKey *ecdsa.PrivateKey
var addr common.Address
func main() {
privateKeyHey := flag.String("privateKey", "", "Please enter privateKey")
isTrue := flag.Bool("advanced", false, "Is it advanced mode?")
flag.Parse()
if len(*privateKeyHey) == 0 {
log.Fatalf("PrivateKey not set")
}
privateKey, addr = privateKeyToAddress(*privateKeyHey)
if !*isTrue {
generalTest()
} else {
// Prompt user to select an action
action := getAction()
// Execute the selected action
executeAction(action)
}
}
// Display a prompt to select an action
func getAction() string {
var action string
actionPrompt := &survey.Select{
Message: "What do you want to do?",
Options: []string{
"View Broadcast Node Information",
"View Storage Node Information",
"Register NodeGroup",
"Register NameSpace",
"General test",
"Advanced test",
"Register as a broadcast node",
"Register as a storage node",
},
PageSize: 8,
}
err := survey.AskOne(actionPrompt, &action)
if err != nil {
log.Fatal(err.Error())
}
return action
}
// Execute the selected action based on the user input
func executeAction(action string) {
switch action {
case "View Broadcast Node Information":
displayNodeInfo(viewBroadcastNodeInfo)
case "View Storage Node Information":
displayNodeInfo(viewStorageNodeInfo)
case "Register NodeGroup":
key := registerNodeGroup()
log.Printf("nodeGroupKeys: %s", key.Hex())
case "Register NameSpace":
key := registerNameSpace()
log.Printf("nameSpaceKey: %s", key.Hex())
case "General test":
generalTest()
case "Advanced test":
advancedTest()
case "Register as a broadcast node":
registerBroadcastNode()
case "Register as a storage node":
registerStorageNode()
default:
fmt.Println("Unknown action")
}
}
// View information of broadcasting nodes
func viewBroadcastNodeInfo() ([]bindings.NodeManagerNodeInfo, error) {
_, instance, err := getNodeManagerInstance()
if err != nil {
return nil, err
}
nodeList, err := instance.GetBroadcastingNodes(nil)
if err != nil {
return nil, err
}
return filterNodes(nodeList), nil
}
// View information of storage nodes
func viewStorageNodeInfo() ([]bindings.NodeManagerNodeInfo, error) {
_, instance, err := getNodeManagerInstance()
if err != nil {
return nil, err
}
nodeList, err := instance.GetStorageNodes(nil)
if err != nil {
return nil, err
}
return filterNodes(nodeList), nil
}
// Register a new node group
func registerNodeGroup() common.Hash {
// Get user input for node addresses and required signatures
addresses := getCommaSeparatedInput("Enter a list of broadcast node addresses separated by commas:\n")
addressList := parseAddresses(addresses)
requiredAmountOfSignatures := getIntInput("Please enter the minimum number of signatures: \n")
// Get instance of StorageManager contract
client, instance, auth, address := getStorageManagerInstance()
if client == nil || instance == nil || auth == nil || address == nil {
return common.Hash{}
}
// Get node group key
nodeGroupKey := getNodeGroupKey(instance, address, addressList, big.NewInt(requiredAmountOfSignatures))
nodegroup, err := instance.NODEGROUP(&bind.CallOpts{
Pending: false,
From: *address,
}, nodeGroupKey)
if err != nil || nodeGroupKey.Cmp(common.Hash{}) == 0 {
log.Fatal(err)
}
// Check if the node group is already registered
if len(nodegroup.Addrs) > 0 {
log.Println("The nodeGroup has been registered and can be used directly.")
return nodeGroupKey
}
// Register the node group
tx := registerNodeGroupTransaction(instance, auth, big.NewInt(requiredAmountOfSignatures), addressList)
waitForTransaction(tx, client)
return nodeGroupKey
}
// Register a new namespace
func registerNameSpace() common.Hash {
// Get user input for node addresses
addresses := getCommaSeparatedInput("Enter a list of storage node addresses separated by commas:\n")
addressList := parseAddresses(addresses)
// Get user input for node addresses
client, instance, auth, address := getStorageManagerInstance()
if client == nil || instance == nil || auth == nil || address == nil {
return common.Hash{}
}
// Get namespace key
nameSpaceKey := getNameSpaceKey(instance, address, addressList)
nameSpace, err := instance.NAMESPACE(&bind.CallOpts{
Pending: false,
From: *address,
}, nameSpaceKey)
if err != nil || nameSpaceKey.Cmp(common.Hash{}) == 0 {
log.Fatal(err)
}
// Check if the namespace is already registered
if len(nameSpace.Addr) > 0 {
log.Println("The nodeGroup has been registered and can be used directly.")
return nameSpaceKey
}
// Register the namespace
tx := registerNameSpaceTransaction(instance, auth, addressList)
waitForTransaction(tx, client)
return nameSpaceKey
}
// Perform a general test with simulated data
func generalTest() {
fmt.Println("Running Parameter Test...")
const nodeGroupKeyStr = "8af361a6d746c89b15a8bce2f9be881e6638b4b17ab7375a89ead3474e341687"
nameSpaceKey := common.HexToHash("0x00")
for {
sendDA(nodeGroupKeyStr, nameSpaceKey)
time.Sleep(5 * time.Minute)
}
}
// Perform an advanced test with user inputs
func advancedTest() {
var nodeGroupKeyStr string
nodeGroupKeyInput := &survey.Input{
Message: "Please enter NodeGroupKey:\n",
}
err := survey.AskOne(nodeGroupKeyInput, &nodeGroupKeyStr)
if err != nil || nodeGroupKeyStr == "" {
log.Fatal("NodeGroupKey cannot be empty")
}
var nameSpaceKeyStr string
nameSpaceKeyInput := &survey.Input{
Message: "Please enter NameSpaceKey (press Enter if empty):\n",
}
err = survey.AskOne(nameSpaceKeyInput, &nameSpaceKeyStr)
if err != nil {
log.Fatal(err.Error())
}
var timerInt int
timerInput := &survey.Input{
Message: "Please enter the sending interval (seconds):\n",
}
err = survey.AskOne(timerInput, &timerInt)
if err != nil {
log.Fatal("Please enter a valid time interval")
}
nameSpaceKey := common.HexToHash(nameSpaceKeyStr)
for {
sendDA(nodeGroupKeyStr, nameSpaceKey)
time.Sleep(time.Duration(timerInt) * time.Second)
}
}
func registerBroadcastNode() {
url, name, location, stakedTokens, maxStorageSpace := getRegisterNodeInfo()
client, instance, err := getNodeManagerInstance()
if err != nil {
log.Fatalf("cant create contract address err: %s", err)
}
auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(chainID))
if err != nil {
log.Fatal(err)
}
tx, err := instance.RegisterBroadcastNode(auth, bindings.NodeManagerNodeInfo{
Url: url,
Name: name,
StakedTokens: big.NewInt(stakedTokens),
Location: location,
MaxStorageSpace: big.NewInt(maxStorageSpace),
Addr: addr,
})
if err != nil {
log.Fatal(err.Error())
return
}
waitForTransaction(tx, client)
}
func registerStorageNode() {
url, name, location, stakedTokens, maxStorageSpace := getRegisterNodeInfo()
client, instance, err := getNodeManagerInstance()
if err != nil {
log.Fatalf("cant create contract address err: %s", err)
}
auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(chainID))
if err != nil {
log.Fatal(err)
}
tx, err := instance.RegisterStorageNode(auth, bindings.NodeManagerNodeInfo{
Url: url,
Name: name,
StakedTokens: big.NewInt(stakedTokens),
Location: location,
MaxStorageSpace: big.NewInt(maxStorageSpace),
Addr: addr,
})
if err != nil {
log.Fatal(err.Error())
return
}
waitForTransaction(tx, client)
}
// Register a node group transaction
func registerNodeGroupTransaction(instance *bindings.StorageManager, auth *bind.TransactOpts, requiredAmountOfSignatures *big.Int, addressList []common.Address) *types.Transaction {
tx, err := instance.RegisterNodeGroup(auth, requiredAmountOfSignatures, addressList)
if err != nil {
log.Fatal(err)
}
return tx
}
// Register a namespace transaction
func registerNameSpaceTransaction(instance *bindings.StorageManager, auth *bind.TransactOpts, addressList []common.Address) *types.Transaction {
tx, err := instance.RegisterNameSpace(auth, addressList)
if err != nil {
log.Fatal(err)
}
return tx
}
// Wait for the transaction to be mined
func waitForTransaction(tx *types.Transaction, client *ethclient.Client) {
log.Printf("tx sent: %s", tx.Hash().Hex())
_, err := bind.WaitMined(context.Background(), client, tx)
if err != nil {
log.Fatal(err)
}
log.Println("tx confirmed")
}
// Send DA with simulated data
func sendDA(nodeGroupKeyStr string, nameSpaceKey [32]byte) {
sdk, err := kzgsdk.InitMultiAdaptiveSdk("./srs")
if err != nil {
log.Fatalf("kzgsdk Error: %s", err)
}
data := simulatedData()
cm, proof, err := sdk.GenerateDataCommitAndProof(data)
if err != nil {
log.Fatalf("kzgsdk Error: %s", err)
}
nodeGroupKey := common.HexToHash(nodeGroupKeyStr)
index, err := getIndex(addr)
if err != nil {
log.Fatalf("getIndex Error: %s", err)
}
ti := time.Now()
timeout := ti.Add(10 * time.Hour).Unix()
signatures, err := GetSignature(nodeGroupKey, addr, index, uint64(len(data)), cm.Marshal(), data, proof.H.Marshal(), proof.ClaimedValue.Marshal(), uint64(timeout))
if err != nil {
log.Printf("GetSignature Error: %s", err)
}
SendCommitToL1(uint64(len(data)), nodeGroupKey, signatures, cm, nameSpaceKey, timeout)
}
// Generate simulated data
func simulatedData() []byte {
data := make([]byte, dataSize)
rand.Read(data)
return data
}
func getIndex(sender common.Address) (uint64, error) {
_, instance, err := getCommitmentManagerInstance()
if err != nil {
return 0, err
}
index, err := instance.Indices(nil, sender)
if err != nil {
return 0, err
}
return index.Uint64(), nil
}
func GetSignature(nodeGroupKey common.Hash, sender common.Address, index, length uint64, commitment, data, proof, claimedValue []byte, timeout uint64) (signatures [][]byte, err error) {
client, err := ethclient.Dial(ethUrl)
if err != nil {
return nil, err
}
storageManager, err := bindings.NewStorageManager(common.HexToAddress(storageManagerAddress), client)
if err != nil {
return nil, err
}
nodeManager, err := bindings.NewNodeManager(common.HexToAddress(nodeManagerAddress), client)
if err != nil {
return nil, err
}
nodeGroup, err := storageManager.NODEGROUP(nil, nodeGroupKey)
if err != nil {
return nil, err
}
for _, add := range nodeGroup.Addrs {
info, err := nodeManager.BroadcastingNodes(nil, add)
if err != nil {
signatures = append(signatures, nil)
continue
}
sign, err := signature(info.Url, sender, index, length, commitment, data, nodeGroupKey, proof, claimedValue, timeout, nil)
if err != nil {
log.Println(err.Error())
signatures = append(signatures, nil)
continue
}
signatures = append(signatures, sign)
}
return signatures, nil
}
func signature(url string, sender common.Address, index, length uint64, commitment, data []byte, nodeGroupKey [32]byte, proof, claimedValue []byte, timeout uint64, extraData []byte) ([]byte, error) {
client, err := ethclient.Dial(url)
if err != nil {
return nil, err
}
ctx := context.Background()
var result []byte
err = client.Client().CallContext(ctx, &result, "mta_sendDAByParams", sender, index, length, commitment, data, nodeGroupKey, proof, claimedValue, timeout, extraData)
return result, err
}
func SendCommitToL1(length uint64, dasKey [32]byte, sign [][]byte, commit kzg.Digest, nameSpaceId [32]byte, timeout int64) {
client, instance, err := getCommitmentManagerInstance()
if err != nil {
log.Fatalf("cant create contract address err: %s", err)
}
auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(chainID))
if err != nil {
log.Fatal(err)
}
commitData := bindings.PairingG1Point{
X: new(big.Int).SetBytes(commit.X.Marshal()),
Y: new(big.Int).SetBytes(commit.Y.Marshal()),
}
tx, err := instance.SubmitCommitment(auth, big.NewInt(int64(length)), big.NewInt(timeout), nameSpaceId, dasKey, sign, commitData)
if err != nil {
log.Printf(err.Error())
return
}
waitForTransaction(tx, client)
}
// Display node information by calling the respective function
func displayNodeInfo(fn func() ([]bindings.NodeManagerNodeInfo, error)) {
list, err := fn()
if err != nil {
log.Printf(err.Error())
return
}
for i, info := range list {
log.Printf("%d Url:%s Address:%s Name:%s Location:%s StakedTokens:%s MaxStorageSpace:%s", i, info.Url, info.Addr, info.Name, info.Location, info.StakedTokens, info.MaxStorageSpace)
}
}
// Filter nodes based on registration and expiry times
func filterNodes(nodeList []bindings.NodeManagerNodeInfo) []bindings.NodeManagerNodeInfo {
var filtered []bindings.NodeManagerNodeInfo
for _, info := range nodeList {
if info.StakedTokens.Cmp(big.NewInt(0)) != 0 {
filtered = append(filtered, info)
}
}
return filtered
}
// Get NodeManager instance
func getNodeManagerInstance() (*ethclient.Client, *bindings.NodeManager, error) {
client, err := ethclient.Dial(ethUrl)
if err != nil {
return nil, nil, err
}
instance, err := bindings.NewNodeManager(common.HexToAddress(nodeManagerAddress), client)
if err != nil {
return nil, nil, err
}
return client, instance, nil
}
func getCommitmentManagerInstance() (*ethclient.Client, *bindings.CommitmentManager, error) {
client, err := ethclient.Dial(ethUrl)
if err != nil {
return nil, nil, err
}
instance, err := bindings.NewCommitmentManager(common.HexToAddress(cmManagerAddress), client)
if err != nil {
return nil, nil, err
}
return client, instance, nil
}
// Get StorageManager instance
func getStorageManagerInstance() (*ethclient.Client, *bindings.StorageManager, *bind.TransactOpts, *common.Address) {
client, err := ethclient.Dial(ethUrl)
if err != nil {
log.Fatal(err)
return nil, nil, nil, nil
}
auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(chainID))
if err != nil {
log.Fatal(err)
return nil, nil, nil, nil
}
instance, err := bindings.NewStorageManager(common.HexToAddress(storageManagerAddress), client)
if err != nil {
log.Fatalf("cant create contract address err: %v", err)
return nil, nil, nil, nil
}
return client, instance, auth, &addr
}
func getRegisterNodeInfo() (url, name, location string, stakedTokens, maxStorageSpace int64) {
url = getCommaSeparatedInput("url")
name = getCommaSeparatedInput("name")
location = getCommaSeparatedInput("location")
stakedTokens = getIntInput("stakedTokens")
maxStorageSpace = getIntInput("maxStorageSpace")
return url, name, location, stakedTokens, maxStorageSpace
}
// Get comma-separated input from the user
func getCommaSeparatedInput(prompt string) string {
var input string
addressesInput := &survey.Input{
Message: prompt,
}
err := survey.AskOne(addressesInput, &input)
if err != nil {
log.Fatal(err.Error())
}
return input
}
// Get integer input from the user
func getIntInput(prompt string) int64 {
var input int64
inputPrompt := &survey.Input{
Message: prompt,
}
err := survey.AskOne(inputPrompt, &input)
if err != nil {
log.Fatal(err.Error())
}
return input
}
// Parse addresses from a comma-separated string
func parseAddresses(addresses string) []common.Address {
addressList := strings.Split(addresses, ",")
var commonAddresses []common.Address
for _, addr := range addressList {
trimmedAddr := strings.TrimSpace(addr)
if !common.IsHexAddress(trimmedAddr) {
log.Fatalf("Invalid address: %s", trimmedAddr)
}
commonAddresses = append(commonAddresses, common.HexToAddress(trimmedAddr))
}
return commonAddresses
}
func privateKeyToAddress(privateKeyHex string) (*ecdsa.PrivateKey, common.Address) {
private, err := crypto.HexToECDSA(privateKeyHex)
if err != nil {
log.Println(privateKeyHex)
log.Fatalf("Invalid private key: %v", err)
}
address := crypto.PubkeyToAddress(private.PublicKey)
return private, address
}
func getNodeGroupKey(instance *bindings.StorageManager, address *common.Address, addressList []common.Address, requiredAmountOfSignatures *big.Int) common.Hash {
nodeGroupKey, err := instance.GetNodeGroupKey(&bind.CallOpts{
Pending: false,
From: *address,
}, addressList, requiredAmountOfSignatures)
if err != nil {
return common.Hash{}
}
return nodeGroupKey
}
func getNameSpaceKey(instance *bindings.StorageManager, address *common.Address, addressList []common.Address) common.Hash {
nameSpaceKey, err := instance.GetNameSpaceKey(&bind.CallOpts{
Pending: false,
From: *address,
}, addressList)
if err != nil {
return common.Hash{}
}
return nameSpaceKey
}