From d71c16683531167230c5f6c4ce60bbe2e9f2b093 Mon Sep 17 00:00:00 2001 From: Brian Tiger Chow Date: Wed, 10 Sep 2014 19:38:21 -0700 Subject: [PATCH 01/14] organize imports --- bitswap/bitswap.go | 10 +++++----- bitswap/ledger.go | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/bitswap/bitswap.go b/bitswap/bitswap.go index 22f97514cf8..0484065a6a6 100644 --- a/bitswap/bitswap.go +++ b/bitswap/bitswap.go @@ -1,17 +1,17 @@ package bitswap import ( - "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto" + "time" + + proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto" + ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go" + blocks "github.com/jbenet/go-ipfs/blocks" peer "github.com/jbenet/go-ipfs/peer" routing "github.com/jbenet/go-ipfs/routing" dht "github.com/jbenet/go-ipfs/routing/dht" swarm "github.com/jbenet/go-ipfs/swarm" u "github.com/jbenet/go-ipfs/util" - - ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go" - - "time" ) // PartnerWantListMax is the bound for the number of keys we'll store per diff --git a/bitswap/ledger.go b/bitswap/ledger.go index a0f23b8d4b5..2a197f05741 100644 --- a/bitswap/ledger.go +++ b/bitswap/ledger.go @@ -1,10 +1,10 @@ package bitswap import ( + "time" + peer "github.com/jbenet/go-ipfs/peer" u "github.com/jbenet/go-ipfs/util" - - "time" ) // Ledger stores the data exchange relationship between two peers. From a910d6878d5c466b733fff6f8c749248ddc6c891 Mon Sep 17 00:00:00 2001 From: Brian Tiger Chow Date: Wed, 10 Sep 2014 19:43:23 -0700 Subject: [PATCH 02/14] privatize getLedger method --- bitswap/bitswap.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bitswap/bitswap.go b/bitswap/bitswap.go index 0484065a6a6..a808954625d 100644 --- a/bitswap/bitswap.go +++ b/bitswap/bitswap.go @@ -192,7 +192,7 @@ func (bs *BitSwap) handleMessages() { // and then if we do, check the ledger for whether or not we should send it. func (bs *BitSwap) peerWantsBlock(p *peer.Peer, want string) { u.DOut("peer [%s] wants block [%s]\n", p.ID.Pretty(), u.Key(want).Pretty()) - ledg := bs.GetLedger(p) + ledg := bs.getLedger(p) dsk := ds.NewKey(want) blk_i, err := bs.datastore.Get(dsk) @@ -239,11 +239,11 @@ func (bs *BitSwap) blockReceive(p *peer.Peer, blk *blocks.Block) { } bs.listener.Respond(string(blk.Key()), mes) - ledger := bs.GetLedger(p) + ledger := bs.getLedger(p) ledger.ReceivedBytes(len(blk.Data)) } -func (bs *BitSwap) GetLedger(p *peer.Peer) *Ledger { +func (bs *BitSwap) getLedger(p *peer.Peer) *Ledger { l, ok := bs.partners[p.Key()] if ok { return l From 182604c61f74104e713a7cab985ecc9021961641 Mon Sep 17 00:00:00 2001 From: Brian Tiger Chow Date: Wed, 10 Sep 2014 19:47:40 -0700 Subject: [PATCH 03/14] substitute with LedgerMap type --- bitswap/bitswap.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bitswap/bitswap.go b/bitswap/bitswap.go index a808954625d..d118c36877b 100644 --- a/bitswap/bitswap.go +++ b/bitswap/bitswap.go @@ -44,7 +44,7 @@ type BitSwap struct { // The Ledger has the peer.ID, and the peer connection works through net. // Ledgers of known relationships (active or inactive) stored in datastore. // Changes to the Ledger should be committed to the datastore. - partners map[u.Key]*Ledger + partners LedgerMap // haveList is the set of keys we have values for. a map for fast lookups. // haveList KeySet -- not needed. all values in datastore? From 99db07c3a4fa77a367431333680fc671950105e1 Mon Sep 17 00:00:00 2001 From: Brian Tiger Chow Date: Wed, 10 Sep 2014 20:23:39 -0700 Subject: [PATCH 04/14] hide ledger wantlist manipulation --- bitswap/bitswap.go | 15 +++++++-------- bitswap/ledger.go | 10 ++++++++++ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/bitswap/bitswap.go b/bitswap/bitswap.go index d118c36877b..a2012c3de84 100644 --- a/bitswap/bitswap.go +++ b/bitswap/bitswap.go @@ -137,7 +137,7 @@ func (bs *BitSwap) getBlock(k u.Key, p *peer.Peer, timeout time.Duration) ([]byt func (bs *BitSwap) HaveBlock(blk *blocks.Block) error { go func() { for _, ledger := range bs.partners { - if _, ok := ledger.WantList[blk.Key()]; ok { + if ledger.WantListContains(blk.Key()) { //send block to node if ledger.ShouldSend() { bs.SendBlock(ledger.Partner, blk) @@ -192,14 +192,13 @@ func (bs *BitSwap) handleMessages() { // and then if we do, check the ledger for whether or not we should send it. func (bs *BitSwap) peerWantsBlock(p *peer.Peer, want string) { u.DOut("peer [%s] wants block [%s]\n", p.ID.Pretty(), u.Key(want).Pretty()) - ledg := bs.getLedger(p) + ledger := bs.getLedger(p) dsk := ds.NewKey(want) blk_i, err := bs.datastore.Get(dsk) if err != nil { if err == ds.ErrNotFound { - // TODO: this needs to be different. We need timeouts. - ledg.WantList[u.Key(want)] = struct{}{} + ledger.Wants(u.Key(want)) } u.PErr("datastore get error: %v\n", err) return @@ -211,7 +210,7 @@ func (bs *BitSwap) peerWantsBlock(p *peer.Peer, want string) { return } - if ledg.ShouldSend() { + if ledger.ShouldSend() { u.DOut("Sending block to peer.\n") bblk, err := blocks.NewBlock(blk) if err != nil { @@ -219,7 +218,7 @@ func (bs *BitSwap) peerWantsBlock(p *peer.Peer, want string) { return } bs.SendBlock(p, bblk) - ledg.SentBytes(len(blk)) + ledger.SentBytes(len(blk)) } else { u.DOut("Decided not to send block.") } @@ -276,7 +275,7 @@ func (bs *BitSwap) Halt() { func (bs *BitSwap) SetStrategy(sf StrategyFunc) { bs.strategy = sf - for _, ledg := range bs.partners { - ledg.Strategy = sf + for _, ledger := range bs.partners { + ledger.Strategy = sf } } diff --git a/bitswap/ledger.go b/bitswap/ledger.go index 2a197f05741..2e99d2ec76e 100644 --- a/bitswap/ledger.go +++ b/bitswap/ledger.go @@ -49,3 +49,13 @@ func (l *Ledger) ReceivedBytes(n int) { l.LastExchange = time.Now() l.Accounting.BytesRecv += uint64(n) } + +// TODO: this needs to be different. We need timeouts. +func (l *Ledger) Wants(k u.Key) { + l.WantList[k] = struct{}{} +} + +func (l *Ledger) WantListContains(k u.Key) bool { + _, ok := l.WantList[k] + return ok +} From 7bae74287242b64b8d7ac61f299ca2d3387e4713 Mon Sep 17 00:00:00 2001 From: Brian Tiger Chow Date: Wed, 10 Sep 2014 20:30:08 -0700 Subject: [PATCH 05/14] privatize fields in ledger --- bitswap/ledger.go | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/bitswap/ledger.go b/bitswap/ledger.go index 2e99d2ec76e..b8b58e5a665 100644 --- a/bitswap/ledger.go +++ b/bitswap/ledger.go @@ -16,17 +16,17 @@ type Ledger struct { // Accounting tracks bytes sent and recieved. Accounting debtRatio - // FirstExchnage is the time of the first data exchange. - FirstExchange time.Time + // firstExchnage is the time of the first data exchange. + firstExchange time.Time - // LastExchange is the time of the last data exchange. - LastExchange time.Time + // lastExchange is the time of the last data exchange. + lastExchange time.Time - // Number of exchanges with this peer - ExchangeCount uint64 + // exchangeCount is the number of exchanges with this peer + exchangeCount uint64 - // WantList is a (bounded, small) set of keys that Partner desires. - WantList KeySet + // wantList is a (bounded, small) set of keys that Partner desires. + wantList KeySet Strategy StrategyFunc } @@ -39,23 +39,23 @@ func (l *Ledger) ShouldSend() bool { } func (l *Ledger) SentBytes(n int) { - l.ExchangeCount++ - l.LastExchange = time.Now() + l.exchangeCount++ + l.lastExchange = time.Now() l.Accounting.BytesSent += uint64(n) } func (l *Ledger) ReceivedBytes(n int) { - l.ExchangeCount++ - l.LastExchange = time.Now() + l.exchangeCount++ + l.lastExchange = time.Now() l.Accounting.BytesRecv += uint64(n) } // TODO: this needs to be different. We need timeouts. func (l *Ledger) Wants(k u.Key) { - l.WantList[k] = struct{}{} + l.wantList[k] = struct{}{} } func (l *Ledger) WantListContains(k u.Key) bool { - _, ok := l.WantList[k] + _, ok := l.wantList[k] return ok } From ad30333581e9050f70c64b81cff0047671949ce4 Mon Sep 17 00:00:00 2001 From: Brian Tiger Chow Date: Thu, 11 Sep 2014 01:02:52 -0700 Subject: [PATCH 06/14] fix(bitswap:ledger) race conditions https://github.com/jbenet/go-ipfs/issues/39 --- bitswap/ledger.go | 23 +++++++++++++++++++++++ bitswap/ledger_test.go | 23 +++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 bitswap/ledger_test.go diff --git a/bitswap/ledger.go b/bitswap/ledger.go index b8b58e5a665..6ddc0a71107 100644 --- a/bitswap/ledger.go +++ b/bitswap/ledger.go @@ -1,6 +1,7 @@ package bitswap import ( + "sync" "time" peer "github.com/jbenet/go-ipfs/peer" @@ -9,6 +10,7 @@ import ( // Ledger stores the data exchange relationship between two peers. type Ledger struct { + lock sync.RWMutex // Partner is the remote Peer. Partner *peer.Peer @@ -35,16 +37,25 @@ type Ledger struct { type LedgerMap map[u.Key]*Ledger func (l *Ledger) ShouldSend() bool { + l.lock.Lock() + defer l.lock.Unlock() + return l.Strategy(l) } func (l *Ledger) SentBytes(n int) { + l.lock.Lock() + defer l.lock.Unlock() + l.exchangeCount++ l.lastExchange = time.Now() l.Accounting.BytesSent += uint64(n) } func (l *Ledger) ReceivedBytes(n int) { + l.lock.Lock() + defer l.lock.Unlock() + l.exchangeCount++ l.lastExchange = time.Now() l.Accounting.BytesRecv += uint64(n) @@ -52,10 +63,22 @@ func (l *Ledger) ReceivedBytes(n int) { // TODO: this needs to be different. We need timeouts. func (l *Ledger) Wants(k u.Key) { + l.lock.Lock() + defer l.lock.Unlock() + l.wantList[k] = struct{}{} } func (l *Ledger) WantListContains(k u.Key) bool { + l.lock.RLock() + defer l.lock.RUnlock() + _, ok := l.wantList[k] return ok } + +func (l *Ledger) ExchangeCount() uint64 { + l.lock.RLock() + defer l.lock.RUnlock() + return l.exchangeCount +} diff --git a/bitswap/ledger_test.go b/bitswap/ledger_test.go new file mode 100644 index 00000000000..d651d485ff7 --- /dev/null +++ b/bitswap/ledger_test.go @@ -0,0 +1,23 @@ +package bitswap + +import ( + "sync" + "testing" +) + +func TestRaceConditions(t *testing.T) { + const numberOfExpectedExchanges = 10000 + l := new(Ledger) + var wg sync.WaitGroup + for i := 0; i < numberOfExpectedExchanges; i++ { + wg.Add(1) + go func() { + defer wg.Done() + l.ReceivedBytes(1) + }() + } + wg.Wait() + if l.ExchangeCount() != numberOfExpectedExchanges { + t.Fail() + } +} From 7f39299033dcdbefb4d6fdd743aaa84dd1abc5dd Mon Sep 17 00:00:00 2001 From: Brian Tiger Chow Date: Thu, 11 Sep 2014 11:13:07 -0700 Subject: [PATCH 07/14] chore(deps:go-multiaddr) update to b90678896b52c procedure is to execute ``` cd my/github.com/jbenet/go-multiaddr git pull cd my/github.com/jbenet/go-ipfs godep update github.com/jbenet/go-multiaddr ``` --- Godeps/Godeps.json | 4 ++-- .../src/github.com/jbenet/go-multiaddr/codec.go | 16 ++++++++++------ .../src/github.com/jbenet/go-multiaddr/index.go | 15 ++++++++++++--- .../jbenet/go-multiaddr/multiaddr_test.go | 4 ++-- .../github.com/jbenet/go-multiaddr/protocols.go | 5 ++++- 5 files changed, 30 insertions(+), 14 deletions(-) diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 0fb6cb10990..08444fe3ef2 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -55,8 +55,8 @@ }, { "ImportPath": "github.com/jbenet/go-multiaddr", - "Comment": "0.1.0-1-g99196c0", - "Rev": "99196c0d231f83eea7f6e47cf59cbb5a0b86b358" + "Comment": "0.1.2", + "Rev": "b90678896b52c3e5a4c8176805c6facc3fe3eb82" }, { "ImportPath": "github.com/jbenet/go-multihash", diff --git a/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/codec.go b/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/codec.go index ca0400a9974..527f0cb5873 100644 --- a/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/codec.go +++ b/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/codec.go @@ -8,10 +8,14 @@ import ( "strings" ) -func StringToBytes(s string) ([]byte, error) { +func stringToBytes(s string) ([]byte, error) { b := []byte{} sp := strings.Split(s, "/") + if sp[0] != "" { + return nil, fmt.Errorf("invalid multiaddr, must begin with /") + } + // consume first empty elem sp = sp[1:] @@ -22,7 +26,7 @@ func StringToBytes(s string) ([]byte, error) { } b = append(b, byte(p.Code)) - a := AddressStringToBytes(p, sp[1]) + a := addressStringToBytes(p, sp[1]) b = append(b, a...) sp = sp[2:] @@ -30,7 +34,7 @@ func StringToBytes(s string) ([]byte, error) { return b, nil } -func BytesToString(b []byte) (ret string, err error) { +func bytesToString(b []byte) (ret string, err error) { // panic handler, in case we try accessing bytes incorrectly. defer func() { if e := recover(); e != nil { @@ -49,7 +53,7 @@ func BytesToString(b []byte) (ret string, err error) { s = strings.Join([]string{s, "/", p.Name}, "") b = b[1:] - a := AddressBytesToString(p, b[:(p.Size/8)]) + a := addressBytesToString(p, b[:(p.Size/8)]) if len(a) > 0 { s = strings.Join([]string{s, "/", a}, "") } @@ -59,7 +63,7 @@ func BytesToString(b []byte) (ret string, err error) { return s, nil } -func AddressStringToBytes(p *Protocol, s string) []byte { +func addressStringToBytes(p *Protocol, s string) []byte { switch p.Code { // ipv4,6 @@ -79,7 +83,7 @@ func AddressStringToBytes(p *Protocol, s string) []byte { return []byte{} } -func AddressBytesToString(p *Protocol, b []byte) string { +func addressBytesToString(p *Protocol, b []byte) string { switch p.Code { // ipv4,6 diff --git a/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/index.go b/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/index.go index 413a971f572..df22012e926 100644 --- a/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/index.go +++ b/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/index.go @@ -5,22 +5,26 @@ import ( "strings" ) +// Multiaddr is the data structure representing a multiaddr type Multiaddr struct { Bytes []byte } +// NewMultiaddr parses and validates an input string, returning a *Multiaddr func NewMultiaddr(s string) (*Multiaddr, error) { - b, err := StringToBytes(s) + b, err := stringToBytes(s) if err != nil { return nil, err } return &Multiaddr{Bytes: b}, nil } +// String returns the string representation of a Multiaddr func (m *Multiaddr) String() (string, error) { - return BytesToString(m.Bytes) + return bytesToString(m.Bytes) } +// Protocols returns the list of protocols this Multiaddr has. func (m *Multiaddr) Protocols() (ret []*Protocol, err error) { // panic handler, in case we try accessing bytes incorrectly. @@ -44,12 +48,14 @@ func (m *Multiaddr) Protocols() (ret []*Protocol, err error) { return ps, nil } +// Encapsulate wraps a given Multiaddr, returning the resulting joined Multiaddr func (m *Multiaddr) Encapsulate(o *Multiaddr) *Multiaddr { b := make([]byte, len(m.Bytes)+len(o.Bytes)) b = append(m.Bytes, o.Bytes...) return &Multiaddr{Bytes: b} } +// Decapsulate unwraps Multiaddr up until the given Multiaddr is found. func (m *Multiaddr) Decapsulate(o *Multiaddr) (*Multiaddr, error) { s1, err := m.String() if err != nil { @@ -68,9 +74,10 @@ func (m *Multiaddr) Decapsulate(o *Multiaddr) (*Multiaddr, error) { return NewMultiaddr(s1[:i]) } +// DialArgs is a convenience function returning arguments for use in net.Dial func (m *Multiaddr) DialArgs() (string, string, error) { if !m.IsThinWaist() { - return "", "", fmt.Errorf("%s is not a 'thin waist' address.", m) + return "", "", fmt.Errorf("%s is not a 'thin waist' address", m) } str, err := m.String() @@ -84,6 +91,8 @@ func (m *Multiaddr) DialArgs() (string, string, error) { return network, host, nil } +// IsThinWaist returns whether this multiaddr includes "Thin Waist" Protocols. +// This means: /{IP4, IP6}/{TCP, UDP} func (m *Multiaddr) IsThinWaist() bool { p, err := m.Protocols() if err != nil { diff --git a/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/multiaddr_test.go b/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/multiaddr_test.go index 976e09556c5..65cb972197d 100644 --- a/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/multiaddr_test.go +++ b/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/multiaddr_test.go @@ -14,7 +14,7 @@ func TestStringToBytes(t *testing.T) { t.Error("failed to decode hex", h) } - b2, err := StringToBytes(s) + b2, err := stringToBytes(s) if err != nil { t.Error("failed to convert", s) } @@ -35,7 +35,7 @@ func TestBytesToString(t *testing.T) { t.Error("failed to decode hex", h) } - s2, err := BytesToString(b) + s2, err := bytesToString(b) if err != nil { t.Error("failed to convert", b) } diff --git a/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/protocols.go b/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/protocols.go index e08d01f0781..ed4d29f1375 100644 --- a/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/protocols.go +++ b/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/protocols.go @@ -1,5 +1,6 @@ package multiaddr +// Protocol is a Multiaddr protocol description structure. type Protocol struct { Code int Size int @@ -10,7 +11,6 @@ type Protocol struct { // 1. avoid parsing the csv // 2. ensuring errors in the csv don't screw up code. // 3. changing a number has to happen in two places. - const ( P_IP4 = 4 P_TCP = 6 @@ -20,6 +20,7 @@ const ( P_SCTP = 132 ) +// Protocols is the list of multiaddr protocols supported by this module. var Protocols = []*Protocol{ &Protocol{P_IP4, 32, "ip4"}, &Protocol{P_TCP, 16, "tcp"}, @@ -32,6 +33,7 @@ var Protocols = []*Protocol{ // {443, 0, "https"}, } +// ProtocolWithName returns the Protocol description with given string name. func ProtocolWithName(s string) *Protocol { for _, p := range Protocols { if p.Name == s { @@ -41,6 +43,7 @@ func ProtocolWithName(s string) *Protocol { return nil } +// ProtocolWithCode returns the Protocol description with given protocol code. func ProtocolWithCode(c int) *Protocol { for _, p := range Protocols { if p.Code == c { From 5059654ec4465977590f9c8310bf96187e5dfdf8 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Thu, 11 Sep 2014 13:05:59 -0700 Subject: [PATCH 08/14] config: Broke out config directory into its own const --- config/config.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/config/config.go b/config/config.go index b80ff1a2c49..76088da1f0e 100644 --- a/config/config.go +++ b/config/config.go @@ -34,12 +34,13 @@ type Config struct { Peers []*SavedPeer } -var DefaultConfigFilePath = "~/.go-ipfs/config" -var DefaultConfigFile = `{ +const DefaultPathRoot = "~/.go-ipfs" +const DefaultConfigFilePath = DefaultPathRoot + "/config" +const DefaultConfigFile = `{ "identity": {}, "datastore": { "type": "leveldb", - "path": "~/.go-ipfs/datastore" + "path": "` + DefaultPathRoot + `/datastore" } } ` From f1e088508a4ffc19f50dab86f0208c38318b5e2e Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Thu, 11 Sep 2014 13:06:51 -0700 Subject: [PATCH 09/14] config: Made WriteConfigFile create config parent directory if it doesn't exist --- config/serialize.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/config/serialize.go b/config/serialize.go index bf495a2603d..647e19e3305 100644 --- a/config/serialize.go +++ b/config/serialize.go @@ -22,6 +22,11 @@ func ReadConfigFile(filename string, cfg interface{}) error { // WriteConfigFile writes the config from `cfg` into `filename`. func WriteConfigFile(filename string, cfg interface{}) error { + err := os.MkdirAll(filepath.Dir(filename), 0775) + if err != nil { + return err + } + f, err := os.Create(filename) if err != nil { return err From fbec97982f4df17d233a02090597c491032868c9 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Thu, 11 Sep 2014 13:07:38 -0700 Subject: [PATCH 10/14] cmd/init: Fixed init checking if config exists --- cmd/ipfs/init.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cmd/ipfs/init.go b/cmd/ipfs/init.go index 77f3fb9f031..839ee2c9d1b 100644 --- a/cmd/ipfs/init.go +++ b/cmd/ipfs/init.go @@ -32,9 +32,13 @@ func init() { } func initCmd(c *commander.Command, inp []string) error { - _, err := os.Lstat(config.DefaultConfigFilePath) + filename, err := config.Filename(config.DefaultConfigFilePath) + if err != nil { + return errors.New("Couldn't get home directory path") + } + fi, err := os.Lstat(filename) force := c.Flag.Lookup("f").Value.Get().(bool) - if err != nil && !force { + if fi != nil || (err != nil && !os.IsNotExist(err)) && !force { return errors.New("ipfs configuration file already exists!\nReinitializing would overwrite your keys.\n(use -f to force overwrite)") } cfg := new(config.Config) From 7b32c11347c7018a7f2ca39d5d362065b8927194 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Thu, 11 Sep 2014 17:22:44 -0700 Subject: [PATCH 11/14] core: Refactored node initialization --- core/core.go | 59 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 24 deletions(-) diff --git a/core/core.go b/core/core.go index b369f2ffa53..4e06621f551 100644 --- a/core/core.go +++ b/core/core.go @@ -69,13 +69,32 @@ func NewIpfsNode(cfg *config.Config, online bool) (*IpfsNode, error) { return nil, err } - var swap *bitswap.BitSwap + local, err := initIdentity(cfg) + if err != nil { + return nil, err + } + + var ( + net *swarm.Swarm + // TODO: refactor so we can use IpfsRouting interface instead of being DHT-specific + route* dht.IpfsDHT + swap *bitswap.BitSwap + ) + if online { - swap, err = loadBitswap(cfg, d) + net = swarm.NewSwarm(local) + err = net.Listen() if err != nil { return nil, err } + + route = dht.NewDHT(local, net, d) + route.Start() + + swap = bitswap.NewBitSwap(local, net, d, route) swap.SetStrategy(bitswap.YesManStrategy) + + go initConnections(cfg, route) } bs, err := bserv.NewBlockService(d, swap) @@ -85,19 +104,24 @@ func NewIpfsNode(cfg *config.Config, online bool) (*IpfsNode, error) { dag := &merkledag.DAGService{Blocks: bs} - n := &IpfsNode{ + return &IpfsNode{ Config: cfg, PeerMap: &peer.Map{}, Datastore: d, Blocks: bs, DAG: dag, Resolver: &path.Resolver{DAG: dag}, - } - - return n, nil + BitSwap: swap, + Identity: local, + Routing: route, + }, nil } -func loadBitswap(cfg *config.Config, d ds.Datastore) (*bitswap.BitSwap, error) { +func initIdentity(cfg *config.Config) (*peer.Peer, error) { + if len(cfg.Identity.PeerID) == 0 { + return nil, errors.New("No peer ID in config! (was ipfs init run?)") + } + maddr, err := ma.NewMultiaddr(cfg.Identity.Address) if err != nil { return nil, err @@ -113,26 +137,15 @@ func loadBitswap(cfg *config.Config, d ds.Datastore) (*bitswap.BitSwap, error) { return nil, err } - local := &peer.Peer{ + return &peer.Peer{ ID: peer.ID(b58.Decode(cfg.Identity.PeerID)), Addresses: []*ma.Multiaddr{maddr}, PrivKey: sk, PubKey: sk.GetPublic(), - } - - if len(local.ID) == 0 { - return nil, errors.New("No peer ID in config! (was ipfs init run?)") - } - - net := swarm.NewSwarm(local) - err = net.Listen() - if err != nil { - return nil, err - } - - route := dht.NewDHT(local, net, d) - route.Start() + }, nil +} +func initConnections(cfg *config.Config, route *dht.IpfsDHT) { for _, p := range cfg.Peers { maddr, err := ma.NewMultiaddr(p.Address) if err != nil { @@ -145,8 +158,6 @@ func loadBitswap(cfg *config.Config, d ds.Datastore) (*bitswap.BitSwap, error) { u.PErr("Bootstrapping error: %v\n", err) } } - - return bitswap.NewBitSwap(local, net, d, route), nil } func (n *IpfsNode) PinDagNode(nd *merkledag.Node) error { From b63e10f3b5d72d415329e49757cdbd8ce54669c8 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Thu, 11 Sep 2014 17:48:05 -0700 Subject: [PATCH 12/14] core: Don't require address for node initialization --- core/core.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/core/core.go b/core/core.go index 4e06621f551..beb6ddd5a87 100644 --- a/core/core.go +++ b/core/core.go @@ -122,9 +122,15 @@ func initIdentity(cfg *config.Config) (*peer.Peer, error) { return nil, errors.New("No peer ID in config! (was ipfs init run?)") } - maddr, err := ma.NewMultiaddr(cfg.Identity.Address) - if err != nil { - return nil, err + // address is optional + var addresses []*ma.Multiaddr + if len(cfg.Identity.Address) > 0 { + maddr, err := ma.NewMultiaddr(cfg.Identity.Address) + if err != nil { + return nil, err + } + + addresses = []*ma.Multiaddr{ maddr } } skb, err := base64.StdEncoding.DecodeString(cfg.Identity.PrivKey) @@ -139,7 +145,7 @@ func initIdentity(cfg *config.Config) (*peer.Peer, error) { return &peer.Peer{ ID: peer.ID(b58.Decode(cfg.Identity.PeerID)), - Addresses: []*ma.Multiaddr{maddr}, + Addresses: addresses, PrivKey: sk, PubKey: sk.GetPublic(), }, nil From 3ae37b29bde242c5bf87deb33b3a6dedd45b8b41 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Thu, 11 Sep 2014 17:50:05 -0700 Subject: [PATCH 13/14] core: Show error when config identity is not set --- core/core.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/core.go b/core/core.go index beb6ddd5a87..0a9db055a9e 100644 --- a/core/core.go +++ b/core/core.go @@ -118,6 +118,10 @@ func NewIpfsNode(cfg *config.Config, online bool) (*IpfsNode, error) { } func initIdentity(cfg *config.Config) (*peer.Peer, error) { + if cfg.Identity == nil { + return nil, errors.New("Identity was not set in config (was ipfs init run?)") + } + if len(cfg.Identity.PeerID) == 0 { return nil, errors.New("No peer ID in config! (was ipfs init run?)") } From 50d318c0bed3ee2a1b54f5a9b81b7ddd00d6f6da Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Thu, 11 Sep 2014 17:52:21 -0700 Subject: [PATCH 14/14] core: Updated basic initialization tests --- core/core_test.go | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/core/core_test.go b/core/core_test.go index f2de5f01600..c3c7474c280 100644 --- a/core/core_test.go +++ b/core/core_test.go @@ -6,17 +6,35 @@ import ( config "github.com/jbenet/go-ipfs/config" ) -func TestDatastores(t *testing.T) { +func TestInitialization(t *testing.T) { + id := &config.Identity { + PeerID: "QmNgdzLieYi8tgfo2WfTUzNVH5hQK9oAYGVf6dxN12NrHt", + Address: "/ip4/127.0.0.1/tcp/8000", + PrivKey: "CAASrRIwggkpAgEAAoICAQCwt67GTUQ8nlJhks6CgbLKOx7F5tl1r9zF4m3TUrG3Pe8h64vi+ILDRFd7QJxaJ/n8ux9RUDoxLjzftL4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wgf1JVHYfVWFUtAzUA+GdqWdOixo5cCsYJbqpNHfWVZN/bUQnBFIYwUwysnC29D+LUdQEQQ4qOm+gFAOtrWU62zMkXJ4iLt8Ify6kbrvsRXgbhQIzzGS7WH9XDarj0eZciuslr15TLMC1Azadf+cXHLR9gMHA13mT9vYIQKCAQA/DjGv8cKCkAvf7s2hqROGYAs6Jp8yhrsN1tYOwAPLRhtnCs+rLrg17M2vDptLlcRuI/vIElamdTmylRpjUQpX7yObzLO73nfVhpwRJVMdGU394iBIDncQ+JoHfUwgqJskbUM40dvZdyjbrqc/Q/4z+hbZb+oN/GXb8sVKBATPzSDMKQ/xqgisYIw+wmDPStnPsHAaIWOtni47zIgilJzD0WEk78/YjmPbUrboYvWziK5JiRRJFA1rkQqV1c0M+OXixIm+/yS8AksgCeaHr0WUieGcJtjT9uE8vyFop5ykhRiNxy9wGaq6i7IEecsrkd6DqxDHWkwhFuO1bSE83q/VAoIBAEA+RX1i/SUi08p71ggUi9WFMqXmzELp1L3hiEjOc2AklHk2rPxsaTh9+G95BvjhP7fRa/Yga+yDtYuyjO99nedStdNNSg03aPXILl9gs3r2dPiQKUEXZJ3FrH6tkils/8BlpOIRfbkszrdZIKTO9GCdLWQ30dQITDACs8zV/1GFGrHFrqnnMe/NpIFHWNZJ0/WZMi8wgWO6Ik8jHEpQtVXRiXLqy7U6hk170pa4GHOzvftfPElOZZjy9qn7KjdAQqy6spIrAE94OEL+fBgbHQZGLpuTlj6w6YGbMtPU8uo7sXKoc6WOCb68JWft3tejGLDa1946HAWqVM9B/UcneNc=", + } good := []*config.Config{ - &config.Config{Datastore: &config.Datastore{Type: "memory"}}, - &config.Config{Datastore: &config.Datastore{Type: "leveldb", Path: ".testdb"}}, + &config.Config { + Identity: id, + Datastore: &config.Datastore{ + Type: "memory", + }, + }, + + &config.Config { + Identity: id, + Datastore: &config.Datastore { + Type: "leveldb", + Path: ".testdb", + }, + }, } bad := []*config.Config{ - &config.Config{Datastore: &config.Datastore{}}, - &config.Config{Datastore: &config.Datastore{Type: "badtype"}}, + &config.Config{Identity: id, Datastore: &config.Datastore{}}, + &config.Config{Identity: id, Datastore: &config.Datastore{Type: "badtype"}}, &config.Config{}, + &config.Config{Datastore: &config.Datastore{Type: "memory"}}, nil, }