|
| 1 | +package create |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path" |
| 8 | + |
| 9 | + "github.com/ava-labs/quarkvm/crypto/ed25519" |
| 10 | + |
| 11 | + "github.com/fatih/color" |
| 12 | + "github.com/spf13/cobra" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + privateKeyFile = ".quark-cli-pk" |
| 17 | +) |
| 18 | + |
| 19 | +func init() { |
| 20 | + cobra.EnablePrefixMatching = true |
| 21 | +} |
| 22 | + |
| 23 | +// NewCommand implements "quark-cli" command. |
| 24 | +func NewCommand() *cobra.Command { |
| 25 | + cmd := &cobra.Command{ |
| 26 | + Use: "create [options]", |
| 27 | + Short: "Creates a new key in the default location", |
| 28 | + Long: ` |
| 29 | +Creates a new key in the default location. |
| 30 | +
|
| 31 | +$ quark-cli create |
| 32 | +
|
| 33 | +`, |
| 34 | + RunE: createFunc, |
| 35 | + } |
| 36 | + return cmd |
| 37 | +} |
| 38 | + |
| 39 | +func getPKLocation() (string, error) { |
| 40 | + p, err := os.Getwd() |
| 41 | + if err != nil { |
| 42 | + return "", err |
| 43 | + } |
| 44 | + return path.Join(p, privateKeyFile), nil |
| 45 | +} |
| 46 | + |
| 47 | +// TODO: run before all functions (erroring if can't load) |
| 48 | +func LoadPK() (ed25519.PrivateKey, error) { |
| 49 | + pkLocation, err := getPKLocation() |
| 50 | + if err != nil { |
| 51 | + return nil, err |
| 52 | + } |
| 53 | + |
| 54 | + pk, err := os.ReadFile(pkLocation) |
| 55 | + if err != nil { |
| 56 | + return nil, err |
| 57 | + } |
| 58 | + return ed25519.LoadPrivateKey(pk) |
| 59 | +} |
| 60 | + |
| 61 | +func createFunc(cmd *cobra.Command, args []string) error { |
| 62 | + // Error if key already exists |
| 63 | + pkLocation, err := getPKLocation() |
| 64 | + if err != nil { |
| 65 | + return err |
| 66 | + } |
| 67 | + if _, err := os.Stat(pkLocation); err == nil { |
| 68 | + return fmt.Errorf("file already exists at %s", pkLocation) |
| 69 | + } else if !errors.Is(err, os.ErrNotExist) { |
| 70 | + return err |
| 71 | + } |
| 72 | + |
| 73 | + // Generate new key and save to disk |
| 74 | + // TODO: encrypt key |
| 75 | + pk, err := ed25519.NewPrivateKey() |
| 76 | + if err != nil { |
| 77 | + return err |
| 78 | + } |
| 79 | + if err := os.WriteFile(pkLocation, pk.Bytes(), 0644); err != nil { |
| 80 | + return err |
| 81 | + } |
| 82 | + color.Green("created address %s and saved to %s", pk.PublicKey().Address(), pkLocation) |
| 83 | + return nil |
| 84 | +} |
0 commit comments