From 4353646945045d89f77d0b362cb5e5533cbd117e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Thu, 23 May 2019 18:11:06 +0100 Subject: [PATCH] Consolidate abstractions and core types into go-libp2p-core (#69) --- go.mod | 7 +- go.sum | 24 +++-- interface.go | 156 ++++++------------------------- metrics.go | 14 +-- peerinfo.go | 119 +++--------------------- peerinfo_test.go | 232 ----------------------------------------------- 6 files changed, 65 insertions(+), 487 deletions(-) delete mode 100644 peerinfo_test.go diff --git a/go.mod b/go.mod index 72b6049..86338f3 100644 --- a/go.mod +++ b/go.mod @@ -8,10 +8,11 @@ require ( github.com/ipfs/go-ds-leveldb v0.0.1 github.com/ipfs/go-log v0.0.1 github.com/libp2p/go-buffer-pool v0.0.1 - github.com/libp2p/go-libp2p-crypto v0.0.1 - github.com/libp2p/go-libp2p-peer v0.0.1 + github.com/libp2p/go-libp2p-core v0.0.1 + github.com/libp2p/go-libp2p-crypto v0.1.0 + github.com/libp2p/go-libp2p-peer v0.2.0 github.com/multiformats/go-base32 v0.0.3 - github.com/multiformats/go-multiaddr v0.0.1 + github.com/multiformats/go-multiaddr v0.0.2 github.com/multiformats/go-multiaddr-net v0.0.1 github.com/multiformats/go-multihash v0.0.1 github.com/pkg/errors v0.8.1 diff --git a/go.sum b/go.sum index 67176d5..6df7a49 100644 --- a/go.sum +++ b/go.sum @@ -12,6 +12,7 @@ github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVa github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -42,6 +43,7 @@ github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+ github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ipfs/go-cid v0.0.1/go.mod h1:GHWU/WuQdMPmIosc4Yn1bcCT7dSeX4lBafM7iqUPQvM= github.com/ipfs/go-datastore v0.0.1 h1:AW/KZCScnBWlSb5JbnEnLKFWXL224LBEh/9KXXOrUms= github.com/ipfs/go-datastore v0.0.1/go.mod h1:d4KVXhMt913cLBEI/PXAy6ko+W7e9AhyAKBGh803qeE= github.com/ipfs/go-ds-badger v0.0.2 h1:7ToQt7QByBhOTuZF2USMv+PGlMcBC7FW7FdgQ4FCsoo= @@ -65,10 +67,13 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/libp2p/go-buffer-pool v0.0.1 h1:9Rrn/H46cXjaA2HQ5Y8lyhOS1NhTkZ4yuEs2r3Eechg= github.com/libp2p/go-buffer-pool v0.0.1/go.mod h1:xtyIz9PMobb13WaxR6Zo1Pd1zXJKYg0a8KiIvDp3TzQ= -github.com/libp2p/go-libp2p-crypto v0.0.1 h1:JNQd8CmoGTohO/akqrH16ewsqZpci2CbgYH/LmYl8gw= -github.com/libp2p/go-libp2p-crypto v0.0.1/go.mod h1:yJkNyDmO341d5wwXxDUGO0LykUVT72ImHNUqh5D/dBE= -github.com/libp2p/go-libp2p-peer v0.0.1 h1:0qwAOljzYewINrU+Kndoc+1jAL7vzY/oY2Go4DCGfyY= -github.com/libp2p/go-libp2p-peer v0.0.1/go.mod h1:nXQvOBbwVqoP+T5Y5nCjeH4sP9IX/J0AMzcDUVruVoo= +github.com/libp2p/go-flow-metrics v0.0.1/go.mod h1:Iv1GH0sG8DtYN3SVJ2eG221wMiNpZxBdp967ls1g+k8= +github.com/libp2p/go-libp2p-core v0.0.1 h1:HSTZtFIq/W5Ue43Zw+uWZyy2Vl5WtF0zDjKN8/DT/1I= +github.com/libp2p/go-libp2p-core v0.0.1/go.mod h1:g/VxnTZ/1ygHxH3dKok7Vno1VfpvGcGip57wjTU4fco= +github.com/libp2p/go-libp2p-crypto v0.1.0 h1:k9MFy+o2zGDNGsaoZl0MA3iZ75qXxr9OOoAZF+sD5OQ= +github.com/libp2p/go-libp2p-crypto v0.1.0/go.mod h1:sPUokVISZiy+nNuTTH/TY+leRSxnFj/2GLjtOTW90hI= +github.com/libp2p/go-libp2p-peer v0.2.0 h1:EQ8kMjaCUwt/Y5uLgjT8iY2qg0mGUT0N1zUjer50DsY= +github.com/libp2p/go-libp2p-peer v0.2.0/go.mod h1:RCffaCvUyW2CJmG2gAWVqwePwW7JMgxjsHm7+J5kjWY= github.com/mattn/go-colorable v0.1.1 h1:G1f5SKeVxmagw/IyvzvtZE4Gybcc4Tr1tf7I8z0XgOg= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw= @@ -77,16 +82,19 @@ github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 h1:lYpkrQH5ajf0 github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ= github.com/minio/sha256-simd v0.0.0-20190131020904-2d45a736cd16 h1:5W7KhL8HVF3XCFOweFD3BNESdnO8ewyYTFT2R+/b8FQ= github.com/minio/sha256-simd v0.0.0-20190131020904-2d45a736cd16/go.mod h1:2FMWW+8GMoPweT6+pI63m9YE3Lmw4J71hV56Chs1E/U= -github.com/mr-tron/base58 v1.1.0 h1:Y51FGVJ91WBqCEabAi5OPUz38eAx8DakuAm5svLcsfQ= github.com/mr-tron/base58 v1.1.0/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8= +github.com/mr-tron/base58 v1.1.1 h1:OJIdWOWYe2l5PQNgimGtuwHY8nDskvJ5vvs//YnzRLs= +github.com/mr-tron/base58 v1.1.1/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8= github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI= github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA= -github.com/multiformats/go-multiaddr v0.0.1 h1:/QUV3VBMDI6pi6xfiw7lr6xhDWWvQKn9udPn68kLSdY= github.com/multiformats/go-multiaddr v0.0.1/go.mod h1:xKVEak1K9cS1VdmPZW3LSIb6lgmoS58qz/pzqmAxV44= +github.com/multiformats/go-multiaddr v0.0.2 h1:RBysRCv5rv3FWlhKWKoXv8tnsCUpEpIZpCmqAGZos2s= +github.com/multiformats/go-multiaddr v0.0.2/go.mod h1:xKVEak1K9cS1VdmPZW3LSIb6lgmoS58qz/pzqmAxV44= github.com/multiformats/go-multiaddr-dns v0.0.1 h1:jQt9c6tDSdQLIlBo4tXYx7QUHCPjxsB1zXcag/2S7zc= github.com/multiformats/go-multiaddr-dns v0.0.1/go.mod h1:9kWcqw/Pj6FwxAwW38n/9403szc57zJPs45fmnznu3Q= github.com/multiformats/go-multiaddr-net v0.0.1 h1:76O59E3FavvHqNg7jvzWzsPSW5JSi/ek0E4eiDVbg9g= github.com/multiformats/go-multiaddr-net v0.0.1/go.mod h1:nw6HSxNmCIQH27XPGBuX+d1tnvM7ihcFwHMSstNAVUU= +github.com/multiformats/go-multibase v0.0.1/go.mod h1:bja2MqRZ3ggyXtZSEDKpl0uO/gviWFaSteVbWT51qgs= github.com/multiformats/go-multihash v0.0.1 h1:HHwN1K12I+XllBCrqKnhX949Orn4oawPkegHMu2vDqQ= github.com/multiformats/go-multihash v0.0.1/go.mod h1:w/5tugSrLEbWqlcgJabL3oHFKTwfvkofsjW2Qa1ct4U= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -100,6 +108,10 @@ github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/spacemonkeygo/openssl v0.0.0-20181017203307-c2dcc5cca94a h1:/eS3yfGjQKG+9kayBkj0ip1BGhq6zJ3eaVksphxAaek= +github.com/spacemonkeygo/openssl v0.0.0-20181017203307-c2dcc5cca94a/go.mod h1:7AyxJNCJ7SBZ1MfVQCWD6Uqo2oubI2Eq2y2eqf+A5r0= +github.com/spacemonkeygo/spacelog v0.0.0-20180420211403-2296661a0572 h1:RC6RW7j+1+HkWaX/Yh71Ee5ZHaHYt7ZP4sQgUrm6cDU= +github.com/spacemonkeygo/spacelog v0.0.0-20180420211403-2296661a0572/go.mod h1:w0SWMsp6j9O/dk4/ZpIhL+3CkG8ofA2vuv7k+ltqUMc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= diff --git a/interface.go b/interface.go index e3d988c..105dedc 100644 --- a/interface.go +++ b/interface.go @@ -1,148 +1,46 @@ package peerstore -import ( - "context" - "errors" - "io" - "math" - "time" +import core "github.com/libp2p/go-libp2p-core/peerstore" - ic "github.com/libp2p/go-libp2p-crypto" - peer "github.com/libp2p/go-libp2p-peer" - ma "github.com/multiformats/go-multiaddr" -) - -var ErrNotFound = errors.New("item not found") +// Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.ErrNotFound instead. +var ErrNotFound = core.ErrNotFound var ( - // AddressTTL is the expiration time of addresses. - AddressTTL = time.Hour + // Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.AddressTTL instead. + AddressTTL = core.AddressTTL - // TempAddrTTL is the ttl used for a short lived address - TempAddrTTL = time.Minute * 2 + // Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.TempAddrTTL instead. + TempAddrTTL = core.TempAddrTTL - // ProviderAddrTTL is the TTL of an address we've received from a provider. - // This is also a temporary address, but lasts longer. After this expires, - // the records we return will require an extra lookup. - ProviderAddrTTL = time.Minute * 10 + // Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.ProviderAddrTTL instead. + ProviderAddrTTL = core.ProviderAddrTTL - // RecentlyConnectedAddrTTL is used when we recently connected to a peer. - // It means that we are reasonably certain of the peer's address. - RecentlyConnectedAddrTTL = time.Minute * 10 + // Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.RecentlyConnectedAddrTTL instead. + RecentlyConnectedAddrTTL = core.RecentlyConnectedAddrTTL - // OwnObservedAddrTTL is used for our own external addresses observed by peers. - OwnObservedAddrTTL = time.Minute * 10 + // Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.OwnObservedAddrTTL instead. + OwnObservedAddrTTL = core.OwnObservedAddrTTL ) -// Permanent TTLs (distinct so we can distinguish between them, constant as they -// are, in fact, permanent) const ( + // Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.PermanentAddrTTL instead. + PermanentAddrTTL = core.PermanentAddrTTL - // PermanentAddrTTL is the ttl for a "permanent address" (e.g. bootstrap nodes). - PermanentAddrTTL = math.MaxInt64 - iota - - // ConnectedAddrTTL is the ttl used for the addresses of a peer to whom - // we're connected directly. This is basically permanent, as we will - // clear them + re-add under a TempAddrTTL after disconnecting. - ConnectedAddrTTL + // Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.ConnectedAddrTTL instead. + ConnectedAddrTTL = core.ConnectedAddrTTL ) -// Peerstore provides a threadsafe store of Peer related -// information. -type Peerstore interface { - io.Closer +// Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.Peerstore instead. +type Peerstore = core.Peerstore - AddrBook - KeyBook - PeerMetadata - Metrics - ProtoBook +// Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.PeerMetadata instead. +type PeerMetadata = core.PeerMetadata - // PeerInfo returns a peer.PeerInfo struct for given peer.ID. - // This is a small slice of the information Peerstore has on - // that peer, useful to other services. - PeerInfo(peer.ID) PeerInfo +// Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.AddrBook instead. +type AddrBook = core.AddrBook - // Peers returns all of the peer IDs stored across all inner stores. - Peers() peer.IDSlice -} +// Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.KeyBook instead. +type KeyBook = core.KeyBook -// PeerMetadata can handle values of any type. Serializing values is -// up to the implementation. Dynamic type introspection may not be -// supported, in which case explicitly enlisting types in the -// serializer may be required. -// -// Refer to the docs of the underlying implementation for more -// information. -type PeerMetadata interface { - // Get/Put is a simple registry for other peer-related key/value pairs. - // if we find something we use often, it should become its own set of - // methods. this is a last resort. - Get(p peer.ID, key string) (interface{}, error) - Put(p peer.ID, key string, val interface{}) error -} - -// AddrBook holds the multiaddrs of peers. -type AddrBook interface { - - // AddAddr calls AddAddrs(p, []ma.Multiaddr{addr}, ttl) - AddAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) - - // AddAddrs gives this AddrBook addresses to use, with a given ttl - // (time-to-live), after which the address is no longer valid. - // If the manager has a longer TTL, the operation is a no-op for that address - AddAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) - - // SetAddr calls mgr.SetAddrs(p, addr, ttl) - SetAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) - - // SetAddrs sets the ttl on addresses. This clears any TTL there previously. - // This is used when we receive the best estimate of the validity of an address. - SetAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) - - // UpdateAddrs updates the addresses associated with the given peer that have - // the given oldTTL to have the given newTTL. - UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) - - // Addresses returns all known (and valid) addresses for a given peer - Addrs(p peer.ID) []ma.Multiaddr - - // AddrStream returns a channel that gets all addresses for a given - // peer sent on it. If new addresses are added after the call is made - // they will be sent along through the channel as well. - AddrStream(context.Context, peer.ID) <-chan ma.Multiaddr - - // ClearAddresses removes all previously stored addresses - ClearAddrs(p peer.ID) - - // PeersWithAddrs returns all of the peer IDs stored in the AddrBook - PeersWithAddrs() peer.IDSlice -} - -// KeyBook tracks the keys of Peers. -type KeyBook interface { - // PubKey stores the public key of a peer. - PubKey(peer.ID) ic.PubKey - - // AddPubKey stores the public key of a peer. - AddPubKey(peer.ID, ic.PubKey) error - - // PrivKey returns the private key of a peer, if known. Generally this might only be our own - // private key, see - // https://discuss.libp2p.io/t/what-is-the-purpose-of-having-map-peer-id-privatekey-in-peerstore/74. - PrivKey(peer.ID) ic.PrivKey - - // AddPrivKey stores the private key of a peer. - AddPrivKey(peer.ID, ic.PrivKey) error - - // PeersWithKeys returns all the peer IDs stored in the KeyBook - PeersWithKeys() peer.IDSlice -} - -// ProtoBook tracks the protocols supported by peers -type ProtoBook interface { - GetProtocols(peer.ID) ([]string, error) - AddProtocols(peer.ID, ...string) error - SetProtocols(peer.ID, ...string) error - SupportsProtocols(peer.ID, ...string) ([]string, error) -} +// Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.ProtoBook instead. +type ProtoBook = core.ProtoBook diff --git a/metrics.go b/metrics.go index 05b8676..f6d0ccb 100644 --- a/metrics.go +++ b/metrics.go @@ -4,6 +4,7 @@ import ( "sync" "time" + moved "github.com/libp2p/go-libp2p-core/peerstore" "github.com/libp2p/go-libp2p-peer" ) @@ -12,17 +13,8 @@ import ( // 1 is 100% change, 0 is no change. var LatencyEWMASmoothing = 0.1 -// Metrics is just an object that tracks metrics -// across a set of peers. -type Metrics interface { - - // RecordLatency records a new latency measurement - RecordLatency(peer.ID, time.Duration) - - // LatencyEWMA returns an exponentially-weighted moving avg. - // of all measurements of a peer's latency. - LatencyEWMA(peer.ID) time.Duration -} +// Deprecated: use github.com/libp2p/go-libp2p-core/peerstore.Metrics instead. +type Metrics = moved.Metrics type metrics struct { latmap map[peer.ID]time.Duration diff --git a/peerinfo.go b/peerinfo.go index 6adaa20..24c8c31 100644 --- a/peerinfo.go +++ b/peerinfo.go @@ -1,115 +1,22 @@ package peerstore import ( - "encoding/json" - "fmt" - "strings" - - peer "github.com/libp2p/go-libp2p-peer" + core "github.com/libp2p/go-libp2p-core/peer" ma "github.com/multiformats/go-multiaddr" ) -// PeerInfo is a small struct used to pass around a peer with -// a set of addresses (and later, keys?). This is not meant to be -// a complete view of the system, but rather to model updates to -// the peerstore. It is used by things like the routing system. -type PeerInfo struct { - ID peer.ID - Addrs []ma.Multiaddr +// Deprecated: use github.com/libp2p/go-libp2p-core/peer.Info instead. +type PeerInfo = core.AddrInfo + +// Deprecated: use github.com/libp2p/go-libp2p-core/peer.ErrInvalidAddr instead. +var ErrInvalidAddr = core.ErrInvalidAddr + +// Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoFromP2pAddr instead. +func InfoFromP2pAddr(m ma.Multiaddr) (*core.AddrInfo, error) { + return core.AddrInfoFromP2pAddr(m) } -var _ fmt.Stringer = PeerInfo{} - -func (pi PeerInfo) String() string { - return fmt.Sprintf("{%v: %v}", pi.ID, pi.Addrs) -} - -var ErrInvalidAddr = fmt.Errorf("invalid p2p multiaddr") - -func InfoFromP2pAddr(m ma.Multiaddr) (*PeerInfo, error) { - if m == nil { - return nil, ErrInvalidAddr - } - - // make sure it's an IPFS addr - parts := ma.Split(m) - if len(parts) < 1 { - return nil, ErrInvalidAddr - } - - // TODO(lgierth): we shouldn't assume /ipfs is the last part - ipfspart := parts[len(parts)-1] - if ipfspart.Protocols()[0].Code != ma.P_IPFS { - return nil, ErrInvalidAddr - } - - // make sure the /ipfs value parses as a peer.ID - peerIdParts := strings.Split(ipfspart.String(), "/") - peerIdStr := peerIdParts[len(peerIdParts)-1] - id, err := peer.IDB58Decode(peerIdStr) - if err != nil { - return nil, err - } - - // we might have received just an /ipfs part, which means there's no addr. - var addrs []ma.Multiaddr - if len(parts) > 1 { - addrs = append(addrs, ma.Join(parts[:len(parts)-1]...)) - } - - return &PeerInfo{ - ID: id, - Addrs: addrs, - }, nil -} - -func InfoToP2pAddrs(pi *PeerInfo) ([]ma.Multiaddr, error) { - var addrs []ma.Multiaddr - tpl := "/" + ma.ProtocolWithCode(ma.P_IPFS).Name + "/" - for _, addr := range pi.Addrs { - p2paddr, err := ma.NewMultiaddr(tpl + peer.IDB58Encode(pi.ID)) - if err != nil { - return nil, err - } - addrs = append(addrs, addr.Encapsulate(p2paddr)) - } - return addrs, nil -} - -func (pi *PeerInfo) Loggable() map[string]interface{} { - return map[string]interface{}{ - "peerID": pi.ID.Pretty(), - "addrs": pi.Addrs, - } -} - -func (pi PeerInfo) MarshalJSON() ([]byte, error) { - out := make(map[string]interface{}) - out["ID"] = pi.ID.Pretty() - var addrs []string - for _, a := range pi.Addrs { - addrs = append(addrs, a.String()) - } - out["Addrs"] = addrs - return json.Marshal(out) -} - -func (pi *PeerInfo) UnmarshalJSON(b []byte) error { - var data map[string]interface{} - err := json.Unmarshal(b, &data) - if err != nil { - return err - } - pid, err := peer.IDB58Decode(data["ID"].(string)) - if err != nil { - return err - } - pi.ID = pid - addrs, ok := data["Addrs"].([]interface{}) - if ok { - for _, a := range addrs { - pi.Addrs = append(pi.Addrs, ma.StringCast(a.(string))) - } - } - return nil +// Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoToP2pAddrs instead. +func InfoToP2pAddrs(pi *core.AddrInfo) ([]ma.Multiaddr, error) { + return core.AddrInfoToP2pAddrs(pi) } diff --git a/peerinfo_test.go b/peerinfo_test.go deleted file mode 100644 index 336c719..0000000 --- a/peerinfo_test.go +++ /dev/null @@ -1,232 +0,0 @@ -package peerstore - -import ( - "encoding/json" - "testing" - - "github.com/libp2p/go-libp2p-peer" - ma "github.com/multiformats/go-multiaddr" -) - -func mustAddr(t *testing.T, s string) ma.Multiaddr { - addr, err := ma.NewMultiaddr(s) - if err != nil { - t.Fatal(err) - } - - return addr -} - -func TestPeerInfoMarshal(t *testing.T) { - a := mustAddr(t, "/ip4/1.2.3.4/tcp/4536") - b := mustAddr(t, "/ip4/1.2.3.8/udp/7777") - id, err := peer.IDB58Decode("QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ") - if err != nil { - t.Fatal(err) - } - - pi := &PeerInfo{ - ID: id, - Addrs: []ma.Multiaddr{a, b}, - } - - data, err := pi.MarshalJSON() - if err != nil { - t.Fatal(err) - } - - pi2 := new(PeerInfo) - if err := pi2.UnmarshalJSON(data); err != nil { - t.Fatal(err) - } - - if pi2.ID != pi.ID { - t.Fatal("ids didnt match after marshal") - } - - if !pi.Addrs[0].Equal(pi2.Addrs[0]) { - t.Fatal("wrong addrs") - } - - if !pi.Addrs[1].Equal(pi2.Addrs[1]) { - t.Fatal("wrong addrs") - } - - lgbl := pi2.Loggable() - if lgbl["peerID"] != id.Pretty() { - t.Fatal("loggables gave wrong peerID output") - } -} - -func TestPeerInfoMarshalWithPointer(t *testing.T) { - a := mustAddr(t, "/ip4/1.2.3.4/tcp/4536") - b := mustAddr(t, "/ip4/1.2.3.8/udp/7777") - id, err := peer.IDB58Decode("QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ") - if err != nil { - t.Fatal(err) - } - - pi := PeerInfo{ - ID: id, - Addrs: []ma.Multiaddr{a, b}, - } - - data, err := json.Marshal(&pi) - if err != nil { - t.Fatal(err) - } - - pi2 := new(PeerInfo) - if err := json.Unmarshal(data, pi2); err != nil { - t.Fatal(err) - } - - if pi2.ID != pi.ID { - t.Fatal("ids didnt match after marshal") - } - - if !pi.Addrs[0].Equal(pi2.Addrs[0]) { - t.Fatal("wrong addrs") - } - - if !pi.Addrs[1].Equal(pi2.Addrs[1]) { - t.Fatal("wrong addrs") - } - - lgbl := pi2.Loggable() - if lgbl["peerID"] != id.Pretty() { - t.Fatal("loggables gave wrong peerID output") - } -} - -func TestPeerInfoMarshalWithValue(t *testing.T) { - a := mustAddr(t, "/ip4/1.2.3.4/tcp/4536") - b := mustAddr(t, "/ip4/1.2.3.8/udp/7777") - id, err := peer.IDB58Decode("QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ") - if err != nil { - t.Fatal(err) - } - - pi := PeerInfo{ - ID: id, - Addrs: []ma.Multiaddr{a, b}, - } - - data, err := json.Marshal(pi) - if err != nil { - t.Fatal(err) - } - - pi2 := new(PeerInfo) - if err := json.Unmarshal(data, pi2); err != nil { - t.Fatal(err) - } - - if pi2.ID != pi.ID { - t.Fatal("ids didnt match after marshal") - } - - if !pi.Addrs[0].Equal(pi2.Addrs[0]) { - t.Fatal("wrong addrs") - } - - if !pi.Addrs[1].Equal(pi2.Addrs[1]) { - t.Fatal("wrong addrs") - } - - lgbl := pi2.Loggable() - if lgbl["peerID"] != id.Pretty() { - t.Fatal("loggables gave wrong peerID output") - } -} - -func TestP2pAddrParsing(t *testing.T) { - id, err := peer.IDB58Decode("QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ") - if err != nil { - t.Error(err) - } - addr := ma.StringCast("/ip4/1.2.3.4/tcp/4536") - p2paddr := ma.Join(addr, ma.StringCast("/ipfs/"+peer.IDB58Encode(id))) - - pinfo, err := InfoFromP2pAddr(p2paddr) - if err != nil { - t.Error(err) - } - - if pinfo.ID != id { - t.Fatalf("expected PeerID [%s], got [%s]", id, pinfo.ID) - } - - if len(pinfo.Addrs) != 1 { - t.Fatalf("expected 1 addr, got %d", len(pinfo.Addrs)) - } - - if !addr.Equal(pinfo.Addrs[0]) { - t.Fatalf("expected addr [%s], got [%s]", addr, pinfo.Addrs[0]) - } - - addr = ma.StringCast("/ipfs/" + peer.IDB58Encode(id)) - pinfo, err = InfoFromP2pAddr(addr) - if err != nil { - t.Error(err) - } - - if pinfo.ID != id { - t.Fatalf("expected PeerID [%s], got [%s]", id, pinfo.ID) - } - - if len(pinfo.Addrs) > 0 { - t.Fatalf("expected 0 addrs, got %d", len(pinfo.Addrs)) - } - - addr = ma.StringCast("/ip4/1.2.3.4/tcp/4536") - pinfo, err = InfoFromP2pAddr(addr) - if err == nil { - t.Fatalf("expected error, got none") - } - - addr = ma.StringCast("/ip4/1.2.3.4/tcp/4536/http") - pinfo, err = InfoFromP2pAddr(addr) - if err == nil { - t.Fatalf("expected error, got none") - } -} - -func TestP2pAddrConstruction(t *testing.T) { - id, err := peer.IDB58Decode("QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ") - if err != nil { - t.Error(err) - } - addr := ma.StringCast("/ip4/1.2.3.4/tcp/4536") - p2paddr := ma.Join(addr, ma.StringCast("/ipfs/"+peer.IDB58Encode(id))) - - pi := &PeerInfo{ID: id, Addrs: []ma.Multiaddr{addr}} - p2paddrs, err := InfoToP2pAddrs(pi) - if err != nil { - t.Error(err) - } - - if len(p2paddrs) != 1 { - t.Fatalf("expected 1 addr, got %d", len(p2paddrs)) - } - - if !p2paddr.Equal(p2paddrs[0]) { - t.Fatalf("expected [%s], got [%s]", p2paddr, p2paddrs[0]) - } - - pi = &PeerInfo{ID: id} - p2paddrs, err = InfoToP2pAddrs(pi) - if err != nil { - t.Error(err) - } - - if len(p2paddrs) > 0 { - t.Fatalf("expected 0 addrs, got %d", len(p2paddrs)) - } - - pi = &PeerInfo{Addrs: []ma.Multiaddr{ma.StringCast("/ip4/1.2.3.4/tcp/4536")}} - _, err = InfoToP2pAddrs(pi) - if err == nil { - t.Fatalf("expected error, got none") - } -}