init.go 2.3 KB
Newer Older
1 2 3 4 5 6 7
package main

import (
	"encoding/base64"
	"errors"
	"os"

8 9
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/gonuts/flag"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/commander"
10
	config "github.com/jbenet/go-ipfs/config"
11 12
	ci "github.com/jbenet/go-ipfs/crypto"
	identify "github.com/jbenet/go-ipfs/identify"
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
	u "github.com/jbenet/go-ipfs/util"
)

var cmdIpfsInit = &commander.Command{
	UsageLine: "init",
	Short:     "Initialize ipfs local configuration",
	Long: `ipfs init

	Initializes ipfs configuration files and generates a
	new keypair.
`,
	Run:  initCmd,
	Flag: *flag.NewFlagSet("ipfs-init", flag.ExitOnError),
}

func init() {
	cmdIpfsInit.Flag.Int("b", 4096, "number of bits for keypair")
	cmdIpfsInit.Flag.String("p", "", "passphrase for encrypting keys")
	cmdIpfsInit.Flag.Bool("f", false, "force overwrite of existing config")
}

func initCmd(c *commander.Command, inp []string) error {
35 36 37 38 39
	filename, err := config.Filename(config.DefaultConfigFilePath)
	if err != nil {
		return errors.New("Couldn't get home directory path")
	}
	fi, err := os.Lstat(filename)
40
	force := c.Flag.Lookup("f").Value.Get().(bool)
41
	if fi != nil || (err != nil && !os.IsNotExist(err)) && !force {
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
		return errors.New("ipfs configuration file already exists!\nReinitializing would overwrite your keys.\n(use -f to force overwrite)")
	}
	cfg := new(config.Config)

	cfg.Datastore = new(config.Datastore)
	dspath, err := u.TildeExpansion("~/.go-ipfs/datastore")
	if err != nil {
		return err
	}
	cfg.Datastore.Path = dspath
	cfg.Datastore.Type = "leveldb"

	cfg.Identity = new(config.Identity)
	// This needs thought
	// cfg.Identity.Address = ""

	nbits := c.Flag.Lookup("b").Value.Get().(int)
	if nbits < 1024 {
		return errors.New("Bitsize less than 1024 is considered unsafe.")
	}
62 63

	sk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)
64 65 66 67 68
	if err != nil {
		return err
	}

	// pretend to encrypt key, then store it unencrypted
69 70 71 72 73
	skbytes, err := sk.Bytes()
	if err != nil {
		return err
	}
	cfg.Identity.PrivKey = base64.StdEncoding.EncodeToString(skbytes)
74

75
	id, err := identify.IdFromPubKey(pk)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
	if err != nil {
		return err
	}
	cfg.Identity.PeerID = id.Pretty()

	path, err := u.TildeExpansion(config.DefaultConfigFilePath)
	if err != nil {
		return err
	}
	err = config.WriteConfigFile(path, cfg)
	if err != nil {
		return err
	}
	return nil
}