Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept a CSV with account definitions as input and fill in vesting and vault addresses #122

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 134 additions & 22 deletions cmd/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package cmd

import (
"crypto/ed25519"
"encoding/csv"
"encoding/hex"
"fmt"
"log"
"os"
"strconv"

"github.com/spacemeshos/economics/constants"
"github.com/spacemeshos/go-spacemesh/common/types"
Expand Down Expand Up @@ -54,10 +57,10 @@ var verifyCmd = &cobra.Command{
}

// next collect multisig params
m := uint8(1)
requiredSignatures := uint8(1)
if len(keys) > 1 {
fmt.Printf("Enter number of required signatures (between 1 and %d): ", len(keys))
_, err := fmt.Scanln(&m)
_, err := fmt.Scanln(&requiredSignatures)
cobra.CheckErr(err)
}

Expand All @@ -68,26 +71,7 @@ var verifyCmd = &cobra.Command{
cobra.CheckErr(err)
amount *= constants.OneSmesh

// calculate keys
vestingArgs := &multisig.SpawnArguments{
Required: m,
PublicKeys: keys,
}
if int(vestingArgs.Required) > len(vestingArgs.PublicKeys) {
log.Fatalf("requires more signatures (%d) than public keys (%d) in the wallet\n",
vestingArgs.Required,
len(vestingArgs.PublicKeys),
)
}
vestingAddress := core.ComputePrincipal(vesting.TemplateAddress, vestingArgs)
vaultArgs := &vault.SpawnArguments{
Owner: vestingAddress,
TotalAmount: amount,
InitialUnlockAmount: amount / 4,
VestingStart: types.LayerID(constants.VestStart),
VestingEnd: types.LayerID(constants.VestEnd),
}
vaultAddress := core.ComputePrincipal(vault.TemplateAddress, vaultArgs)
vestingAddress, vaultAddress := generateAddresses(requiredSignatures, keys, amount)

// output addresses
fmt.Printf("Vesting address: %s\nVault address: %s\n",
Expand All @@ -96,7 +80,135 @@ var verifyCmd = &cobra.Command{
},
}

var processCSVCmd = &cobra.Command{
Use: "csv",
Short: "Process a CSV file with account definitions " +
"(name, amount, key1, key2, key3, key4, key5, required_signatures)",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC we actually support up to ten keys, although in practice I don't think anyone is using that many. Maybe worth adding to the description something like "(for an account with up to five pubkeys)"?

Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
csvFilePath, _ := cmd.Flags().GetString("file")
if csvFilePath == "" {
fmt.Println("CSV file path is required")
return
}

file, err := os.Open(csvFilePath)
if err != nil {
fmt.Printf("Failed to open CSV file: %v\n", err)
return
}
defer file.Close()

reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
fmt.Printf("Failed to read CSV file: %v\n", err)
return
}

// Process each record
for i, record := range records {
if i == 0 {
// Add new columns to the header
record = append(record, "vesting_address", "vault_address")
records[i] = record
continue
}

// Extract account details from the record
name := record[0]
amountStr := record[1]
keysStr := record[2:7]
requiredSignaturesStr := record[7]

// Convert amount and requiredSignatures to appropriate types
amount, err := strconv.ParseUint(amountStr, 10, 64)
if err != nil {
log.Fatalf("Error: amount %s for %s on line %d is invalid", amountStr, name, i)
}
amount *= constants.OneSmesh

requiredSignatures64, err := strconv.ParseUint(requiredSignaturesStr, 10, 8)
if err != nil {
log.Fatalf("Error: required signatures %s for %s on line %d is invalid", requiredSignaturesStr, name, i)
}
requiredSignatures := uint8(requiredSignatures64)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we combine this with the strconv and just read the number directly into u8?


// Collect the keys
var publicKeys []core.PublicKey
for _, keyStr := range keysStr {
if len(keyStr) == 0 {
break
}
keyBytes, err := hex.DecodeString(keyStr)
if err != nil || len(keyBytes) != ed25519.PublicKeySize {
log.Fatalf("Error: key %s for %s on line %d is unreadable", keyStr, name, i)
}
var pubKey core.PublicKey
copy(pubKey[:], keyBytes)
publicKeys = append(publicKeys, pubKey)
}

// Generate vesting and vault addresses
vestingAddress, vaultAddress := generateAddresses(requiredSignatures, publicKeys, amount)

// Append new addresses to the record
record = append(record, vestingAddress.String(), vaultAddress.String())
records[i] = record
}

// Write updated records to a new CSV file
outputFile, err := os.Create("updated_" + csvFilePath)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a little counterintuitive, I'm not sure the user will know where to find this file. I think printing to STDOUT would make more sense, then they can use shell redirect if they want to save to a new file.

if err != nil {
fmt.Printf("Failed to create output CSV file: %v\n", err)
return
}
defer outputFile.Close()

writer := csv.NewWriter(outputFile)
err = writer.WriteAll(records)
if err != nil {
fmt.Printf("Failed to write to output CSV file: %v\n", err)
return
}

fmt.Println("CSV file processed successfully")
},
}

// generateAddresses generates vesting and vault addresses based on the provided parameters.
func generateAddresses(
requiredSignatures uint8,
publicKeys []core.PublicKey,
amount uint64,
) (core.Address, core.Address) {
vestingArgs := &multisig.SpawnArguments{
Required: requiredSignatures,
PublicKeys: publicKeys,
}
if int(vestingArgs.Required) > len(vestingArgs.PublicKeys) {
log.Fatalf("requires more signatures (%d) than public keys (%d) in the wallet\n",
vestingArgs.Required,
len(vestingArgs.PublicKeys),
)
}
vestingAddress := core.ComputePrincipal(vesting.TemplateAddress, vestingArgs)
vaultArgs := &vault.SpawnArguments{
Owner: vestingAddress,
TotalAmount: amount,
InitialUnlockAmount: amount / 4,
VestingStart: types.LayerID(constants.VestStart),
VestingEnd: types.LayerID(constants.VestEnd),
}
vaultAddress := core.ComputePrincipal(vault.TemplateAddress, vaultArgs)

return vestingAddress, vaultAddress
}

func init() {
rootCmd.AddCommand(genesisCmd)
genesisCmd.AddCommand(verifyCmd)
processCSVCmd.Flags().StringP("file", "f", "",
"Path to a CSV file with headings: name, amount, key1, key2, key3, key4, key5, required_signatures")
genesisCmd.AddCommand(processCSVCmd)
}