init.go 7.29 KB
Newer Older
1
package main
Matt Bell's avatar
Matt Bell committed
2 3

import (
4
	"bytes"
Matt Bell's avatar
Matt Bell committed
5
	"encoding/base64"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
6
	"fmt"
Matt Bell's avatar
Matt Bell committed
7
	"os"
8
	"path"
Matt Bell's avatar
Matt Bell committed
9 10 11 12
	"path/filepath"

	cmds "github.com/jbenet/go-ipfs/commands"
	config "github.com/jbenet/go-ipfs/config"
13
	core "github.com/jbenet/go-ipfs/core"
Matt Bell's avatar
Matt Bell committed
14
	ci "github.com/jbenet/go-ipfs/crypto"
15 16
	imp "github.com/jbenet/go-ipfs/importer"
	chunk "github.com/jbenet/go-ipfs/importer/chunk"
Matt Bell's avatar
Matt Bell committed
17 18
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
19
	"github.com/jbenet/go-ipfs/util/debugerror"
Matt Bell's avatar
Matt Bell committed
20 21
)

22 23
const nBitsForKeypairDefault = 4096

Matt Bell's avatar
Matt Bell committed
24
var initCmd = &cmds.Command{
25 26 27 28
	Helptext: cmds.HelpText{
		Tagline:          "Initializes IPFS config file",
		ShortDescription: "Initializes IPFS configuration files and generates a new keypair.",
	},
29

Matt Bell's avatar
Matt Bell committed
30
	Options: []cmds.Option{
31
		cmds.IntOption("bits", "b", "Number of bits to use in the generated RSA private key (defaults to 4096)"),
32 33 34
		cmds.StringOption("passphrase", "p", "Passphrase for encrypting the private key"),
		cmds.BoolOption("force", "f", "Overwrite existing config (if it exists)"),
		cmds.StringOption("datastore", "d", "Location for the IPFS data store"),
35 36 37 38 39

		// TODO need to decide whether to expose the override as a file or a
		// directory. That is: should we allow the user to also specify the
		// name of the file?
		// TODO cmds.StringOption("event-logs", "l", "Location for machine-readable event logs"),
Matt Bell's avatar
Matt Bell committed
40
	},
41
	Run: func(req cmds.Request) (interface{}, error) {
42

43
		dspathOverride, _, err := req.Option("d").String() // if !found it's okay. Let == ""
44 45
		if err != nil {
			return nil, err
46 47
		}

48
		force, _, err := req.Option("f").Bool() // if !found, it's okay force == false
49 50
		if err != nil {
			return nil, err
51 52
		}

53
		nBitsForKeypair, bitsOptFound, err := req.Option("b").Int()
54 55 56
		if err != nil {
			return nil, err
		}
57
		if !bitsOptFound {
58
			nBitsForKeypair = nBitsForKeypairDefault
59 60
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
		return doInit(req.Context().ConfigRoot, dspathOverride, force, nBitsForKeypair)
62 63
	},
}
Matt Bell's avatar
Matt Bell committed
64

Brian Tiger Chow's avatar
Brian Tiger Chow committed
65
var errCannotInitConfigExists = debugerror.New(`ipfs configuration file already exists!
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
Reinitializing would overwrite your keys.
(use -f to force overwrite)
`)

var welcomeMsg = `Hello and Welcome to IPFS!

██╗██████╗ ███████╗███████╗
██║██╔══██╗██╔════╝██╔════╝
██║██████╔╝█████╗  ███████╗
██║██╔═══╝ ██╔══╝  ╚════██║
██║██║     ██║     ███████║
╚═╝╚═╝     ╚═╝     ╚══════╝

If you're seeing this, you have successfully installed
IPFS and are now interfacing with the ipfs merkledag!

For a short demo of what you can do, enter 'ipfs tour'
`

85 86
func initWithDefaults(configRoot string) error {
	_, err := doInit(configRoot, "", false, nBitsForKeypairDefault)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
87
	return debugerror.Wrap(err)
88 89
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
func doInit(configRoot string, dspathOverride string, force bool, nBitsForKeypair int) (interface{}, error) {
91

92
	u.POut("initializing ipfs node at %s\n", configRoot)
93 94

	configFilename, err := config.Filename(configRoot)
95
	if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
96
		return nil, debugerror.New("Couldn't get home directory path")
97 98
	}

99 100
	if u.FileExists(configFilename) && !force {
		return nil, errCannotInitConfigExists
101
	}
Matt Bell's avatar
Matt Bell committed
102

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
	conf, err := initConfig(configFilename, dspathOverride, nBitsForKeypair)
104
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105
		return nil, err
106
	}
107

Brian Tiger Chow's avatar
fix  
Brian Tiger Chow committed
108
	err = addTheWelcomeFile(conf)
109 110 111 112 113 114 115 116 117
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// addTheWelcomeFile adds a file containing the welcome message to the newly
// minted node. On success, it calls onSuccess
Brian Tiger Chow's avatar
fix  
Brian Tiger Chow committed
118
func addTheWelcomeFile(conf *config.Config) error {
119
	// TODO extract this file creation operation into a function
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120
	nd, err := core.NewIpfsNode(conf, false)
121
	if err != nil {
122
		return err
123 124 125 126
	}
	defer nd.Close()

	// Set up default file
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127
	reader := bytes.NewBufferString(welcomeMsg)
128 129 130

	defnd, err := imp.BuildDagFromReader(reader, nd.DAG, nd.Pinning.GetManual(), chunk.DefaultSplitter)
	if err != nil {
131
		return err
132 133
	}

134 135
	k, err := defnd.Key()
	if err != nil {
136
		return fmt.Errorf("failed to write test file: %s", err)
137
	}
Brian Tiger Chow's avatar
fix  
Brian Tiger Chow committed
138
	fmt.Printf("\nto get started, enter: ipfs cat %s\n", k)
139
	return nil
Matt Bell's avatar
Matt Bell committed
140
}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
141 142 143 144 145 146 147 148 149 150 151 152 153

func datastoreConfig(dspath string) (config.Datastore, error) {
	ds := config.Datastore{}
	if len(dspath) == 0 {
		var err error
		dspath, err = config.DataStorePath("")
		if err != nil {
			return ds, err
		}
	}
	ds.Path = dspath
	ds.Type = "leveldb"

154 155
	err := initCheckDir(dspath)
	if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
156
		return ds, debugerror.Errorf("datastore: %s", err)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
157 158 159 160
	}

	return ds, nil
}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
161

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163 164 165 166 167
func initConfig(configFilename string, dspathOverride string, nBitsForKeypair int) (*config.Config, error) {
	ds, err := datastoreConfig(dspathOverride)
	if err != nil {
		return nil, err
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
168
	identity, err := identityConfig(nBitsForKeypair)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169 170 171 172
	if err != nil {
		return nil, err
	}

173 174 175 176 177
	logConfig, err := initLogs("") // TODO allow user to override dir
	if err != nil {
		return nil, err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178 179 180 181
	conf := &config.Config{

		// setup the node addresses.
		Addresses: config.Addresses{
182 183 184 185 186
			Swarm: []string{
				"/ip4/0.0.0.0/tcp/4001",
				"/ip4/0.0.0.0/udp/4002/utp",
			},
			API: "/ip4/127.0.0.1/tcp/5001",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187 188 189 190 191 192 193 194 195 196 197 198
		},

		Bootstrap: []*config.BootstrapPeer{
			&config.BootstrapPeer{ // Use these hardcoded bootstrap peers for now.
				// mars.i.ipfs.io
				PeerID:  "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ",
				Address: "/ip4/104.131.131.82/tcp/4001",
			},
		},

		Datastore: ds,

199 200
		Logs: logConfig,

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
		Identity: identity,

		// setup the node mount points.
		Mounts: config.Mounts{
			IPFS: "/ipfs",
			IPNS: "/ipns",
		},

		// tracking ipfs version used to generate the init folder and adding
		// update checker default setting.
		Version: config.VersionDefaultValue(),
	}

	if err := config.WriteConfigFile(configFilename, conf); err != nil {
		return nil, err
	}

	return conf, nil
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
221 222
// identityConfig initializes a new identity.
func identityConfig(nbits int) (config.Identity, error) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
223 224 225
	// TODO guard higher up
	ident := config.Identity{}
	if nbits < 1024 {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
226
		return ident, debugerror.New("Bitsize less than 1024 is considered unsafe.")
Brian Tiger Chow's avatar
Brian Tiger Chow committed
227 228
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
229
	fmt.Printf("generating key pair...")
Brian Tiger Chow's avatar
Brian Tiger Chow committed
230 231 232 233
	sk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)
	if err != nil {
		return ident, err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
234
	fmt.Printf("done\n")
Brian Tiger Chow's avatar
Brian Tiger Chow committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248

	// currently storing key unencrypted. in the future we need to encrypt it.
	// TODO(security)
	skbytes, err := sk.Bytes()
	if err != nil {
		return ident, err
	}
	ident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)

	id, err := peer.IDFromPubKey(pk)
	if err != nil {
		return ident, err
	}
	ident.PeerID = id.Pretty()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
249
	fmt.Printf("peer identity: %s\n", ident.PeerID)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
250 251
	return ident, nil
}
252

253 254 255 256 257
func initLogs(logpath string) (config.Logs, error) {
	if len(logpath) == 0 {
		var err error
		logpath, err = config.LogsPath("")
		if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
258
			return config.Logs{}, debugerror.Wrap(err)
259 260 261 262 263
		}
	}

	err := initCheckDir(logpath)
	if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
264
		return config.Logs{}, debugerror.Errorf("logs: %s", err)
265 266 267 268 269 270 271
	}

	return config.Logs{
		Filename: path.Join(logpath, "events.log"),
	}, nil
}

272 273 274 275 276 277 278 279 280 281 282
// initCheckDir ensures the directory exists and is writable
func initCheckDir(path string) error {
	// Construct the path if missing
	if err := os.MkdirAll(path, os.ModePerm); err != nil {
		return err
	}

	// Check the directory is writeable
	if f, err := os.Create(filepath.Join(path, "._check_writeable")); err == nil {
		os.Remove(f.Name())
	} else {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
283
		return debugerror.New("'" + path + "' is not writeable")
284 285 286
	}
	return nil
}