multiaddr.go 5.22 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4
package multiaddr

import (
	"bytes"
5
	"encoding/json"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"fmt"
Jeromy's avatar
Jeromy committed
7
	"log"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	"strings"
Marten Seemann's avatar
Marten Seemann committed
9 10

	"golang.org/x/exp/slices"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12 13 14 15 16 17 18
)

// multiaddr is the data structure representing a Multiaddr
type multiaddr struct {
	bytes []byte
}

// NewMultiaddr parses and validates an input string, returning a *Multiaddr
Jeromy's avatar
Jeromy committed
19 20 21 22 23 24 25
func NewMultiaddr(s string) (a Multiaddr, err error) {
	defer func() {
		if e := recover(); e != nil {
			log.Printf("Panic in NewMultiaddr on input %q: %s", s, e)
			err = fmt.Errorf("%v", e)
		}
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26 27 28 29
	b, err := stringToBytes(s)
	if err != nil {
		return nil, err
	}
30
	return &multiaddr{bytes: b}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31 32 33 34
}

// NewMultiaddrBytes initializes a Multiaddr from a byte representation.
// It validates it as an input string.
Jeromy's avatar
Jeromy committed
35 36 37 38 39 40 41 42
func NewMultiaddrBytes(b []byte) (a Multiaddr, err error) {
	defer func() {
		if e := recover(); e != nil {
			log.Printf("Panic in NewMultiaddrBytes on input %q: %s", b, e)
			err = fmt.Errorf("%v", e)
		}
	}()

43
	if err := validateBytes(b); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44 45
		return nil, err
	}
46

47
	return &multiaddr{bytes: b}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48 49 50
}

// Equal tests whether two multiaddrs are equal
51
func (m *multiaddr) Equal(m2 Multiaddr) bool {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52 53 54 55
	return bytes.Equal(m.bytes, m2.Bytes())
}

// Bytes returns the []byte representation of this Multiaddr
56 57
//
// Do not modify the returned buffer, it may be shared.
58
func (m *multiaddr) Bytes() []byte {
59
	return m.bytes
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60 61 62
}

// String returns the string representation of a Multiaddr
63
func (m *multiaddr) String() string {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65
	s, err := bytesToString(m.bytes)
	if err != nil {
66
		panic(fmt.Errorf("multiaddr failed to convert back to string. corrupted? %s", err))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68 69 70
	}
	return s
}

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
func (m *multiaddr) MarshalBinary() ([]byte, error) {
	return m.Bytes(), nil
}

func (m *multiaddr) UnmarshalBinary(data []byte) error {
	new, err := NewMultiaddrBytes(data)
	if err != nil {
		return err
	}
	*m = *(new.(*multiaddr))
	return nil
}

func (m *multiaddr) MarshalText() ([]byte, error) {
	return []byte(m.String()), nil
}

func (m *multiaddr) UnmarshalText(data []byte) error {
	new, err := NewMultiaddr(string(data))
	if err != nil {
		return err
	}
	*m = *(new.(*multiaddr))
	return nil
}

func (m *multiaddr) MarshalJSON() ([]byte, error) {
	return json.Marshal(m.String())
}

func (m *multiaddr) UnmarshalJSON(data []byte) error {
	var v string
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}
	new, err := NewMultiaddr(v)
	*m = *(new.(*multiaddr))
	return err
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111 112
// Protocols returns the list of protocols this Multiaddr has.
// will panic in case we access bytes incorrectly.
113
func (m *multiaddr) Protocols() []Protocol {
Steven Allen's avatar
Steven Allen committed
114
	ps := make([]Protocol, 0, 8)
115
	b := m.bytes
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116
	for len(b) > 0 {
117 118 119 120 121
		code, n, err := ReadVarintCode(b)
		if err != nil {
			panic(err)
		}

122
		p := ProtocolWithCode(code)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123
		if p.Code == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124 125 126 127 128
			// this is a panic (and not returning err) because this should've been
			// caught on constructing the Multiaddr
			panic(fmt.Errorf("no protocol with code %d", b[0]))
		}
		ps = append(ps, p)
129 130
		b = b[n:]

131
		n, size, err := sizeForAddr(p, b)
Jeromy's avatar
Jeromy committed
132 133 134 135
		if err != nil {
			panic(err)
		}

136
		b = b[n+size:]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139 140 141
	}
	return ps
}

// Encapsulate wraps a given Multiaddr, returning the resulting joined Multiaddr
142
func (m *multiaddr) Encapsulate(o Multiaddr) Multiaddr {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143 144 145
	mb := m.bytes
	ob := o.Bytes()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147 148
	b := make([]byte, len(mb)+len(ob))
	copy(b, mb)
	copy(b[len(mb):], ob)
149
	return &multiaddr{bytes: b}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150 151 152
}

// Decapsulate unwraps Multiaddr up until the given Multiaddr is found.
153
func (m *multiaddr) Decapsulate(o Multiaddr) Multiaddr {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155 156 157 158 159 160
	s1 := m.String()
	s2 := o.String()
	i := strings.LastIndex(s1, s2)
	if i < 0 {
		// if multiaddr not contained, returns a copy.
		cpy := make([]byte, len(m.bytes))
		copy(cpy, m.bytes)
161
		return &multiaddr{bytes: cpy}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163
	}

Steven Allen's avatar
Steven Allen committed
164 165 166 167
	if i == 0 {
		return nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168 169 170 171 172 173
	ma, err := NewMultiaddr(s1[:i])
	if err != nil {
		panic("Multiaddr.Decapsulate incorrect byte boundaries.")
	}
	return ma
}
174 175 176

var ErrProtocolNotFound = fmt.Errorf("protocol not found in multiaddr")

177
func (m *multiaddr) ValueForProtocol(code int) (value string, err error) {
Steven Allen's avatar
Steven Allen committed
178 179 180 181 182 183
	err = ErrProtocolNotFound
	ForEach(m, func(c Component) bool {
		if c.Protocol().Code == code {
			value = c.Value()
			err = nil
			return false
184
		}
Steven Allen's avatar
Steven Allen committed
185 186 187
		return true
	})
	return
188
}
189 190 191 192 193

// FilterAddrs is a filter that removes certain addresses, according to the given filters.
// If all filters return true, the address is kept.
func FilterAddrs(a []Multiaddr, filters ...func(Multiaddr) bool) []Multiaddr {
	b := make([]Multiaddr, 0, len(a))
194
addrloop:
195 196
	for _, addr := range a {
		for _, filter := range filters {
197 198 199
			if !filter(addr) {
				continue addrloop
			}
200
		}
201
		b = append(b, addr)
202 203 204
	}
	return b
}
205 206 207 208 209 210 211 212 213 214

// Contains reports whether addr is contained in addrs.
func Contains(addrs []Multiaddr, addr Multiaddr) bool {
	for _, a := range addrs {
		if addr.Equal(a) {
			return true
		}
	}
	return false
}
Marten Seemann's avatar
Marten Seemann committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

// Unique deduplicates addresses in place, leave only unique addresses.
// It doesn't allocate.
func Unique(addrs []Multiaddr) []Multiaddr {
	if len(addrs) == 0 {
		return addrs
	}
	// Use the new slices package here, as the sort function doesn't allocate (sort.Slice does).
	slices.SortFunc(addrs, func(a, b Multiaddr) bool { return bytes.Compare(a.Bytes(), b.Bytes()) < 0 })
	idx := 1
	for i := 1; i < len(addrs); i++ {
		if !addrs[i-1].Equal(addrs[i]) {
			addrs[idx] = addrs[i]
			idx++
		}
	}
	for i := idx; i < len(addrs); i++ {
		addrs[i] = nil
	}
	return addrs[:idx]
}