aboutsummaryrefslogtreecommitdiffstats
path: root/p2p/enr/enr.go
blob: 48683471d21f4284412a2b4cbd21d2aadd35d345 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

// Package enr implements Ethereum Node Records as defined in EIP-778. A node record holds
// arbitrary information about a node on the peer-to-peer network.
//
// Records contain named keys. To store and retrieve key/values in a record, use the Entry
// interface.
//
// Records must be signed before transmitting them to another node. Decoding a record verifies
// its signature. When creating a record, set the entries you want, then call Sign to add the
// signature. Modifying a record invalidates the signature.
//
// Package enr supports the "secp256k1-keccak" identity scheme.
package enr

import (
    "bytes"
    "errors"
    "fmt"
    "io"
    "sort"

    "github.com/ethereum/go-ethereum/rlp"
)

const SizeLimit = 300 // maximum encoded size of a node record in bytes

var (
    errNoID           = errors.New("unknown or unspecified identity scheme")
    errInvalidSig     = errors.New("invalid signature")
    errNotSorted      = errors.New("record key/value pairs are not sorted by key")
    errDuplicateKey   = errors.New("record contains duplicate key")
    errIncompletePair = errors.New("record contains incomplete k/v pair")
    errTooBig         = fmt.Errorf("record bigger than %d bytes", SizeLimit)
    errEncodeUnsigned = errors.New("can't encode unsigned record")
    errNotFound       = errors.New("no such key in record")
)

// Record represents a node record. The zero value is an empty record.
type Record struct {
    seq       uint64 // sequence number
    signature []byte // the signature
    raw       []byte // RLP encoded record
    pairs     []pair // sorted list of all key/value pairs
}

// pair is a key/value pair in a record.
type pair struct {
    k string
    v rlp.RawValue
}

// Signed reports whether the record has a valid signature.
func (r *Record) Signed() bool {
    return r.signature != nil
}

// Seq returns the sequence number.
func (r *Record) Seq() uint64 {
    return r.seq
}

// SetSeq updates the record sequence number. This invalidates any signature on the record.
// Calling SetSeq is usually not required because setting any key in a signed record
// increments the sequence number.
func (r *Record) SetSeq(s uint64) {
    r.signature = nil
    r.raw = nil
    r.seq = s
}

// Load retrieves the value of a key/value pair. The given Entry must be a pointer and will
// be set to the value of the entry in the record.
//
// Errors returned by Load are wrapped in KeyError. You can distinguish decoding errors
// from missing keys using the IsNotFound function.
func (r *Record) Load(e Entry) error {
    i := sort.Search(len(r.pairs), func(i int) bool { return r.pairs[i].k >= e.ENRKey() })
    if i < len(r.pairs) && r.pairs[i].k == e.ENRKey() {
        if err := rlp.DecodeBytes(r.pairs[i].v, e); err != nil {
            return &KeyError{Key: e.ENRKey(), Err: err}
        }
        return nil
    }
    return &KeyError{Key: e.ENRKey(), Err: errNotFound}
}

// Set adds or updates the given entry in the record. It panics if the value can't be
// encoded. If the record is signed, Set increments the sequence number and invalidates
// the sequence number.
func (r *Record) Set(e Entry) {
    blob, err := rlp.EncodeToBytes(e)
    if err != nil {
        panic(fmt.Errorf("enr: can't encode %s: %v", e.ENRKey(), err))
    }
    r.invalidate()

    pairs := make([]pair, len(r.pairs))
    copy(pairs, r.pairs)
    i := sort.Search(len(pairs), func(i int) bool { return pairs[i].k >= e.ENRKey() })
    switch {
    case i < len(pairs) && pairs[i].k == e.ENRKey():
        // element is present at r.pairs[i]
        pairs[i].v = blob
    case i < len(r.pairs):
        // insert pair before i-th elem
        el := pair{e.ENRKey(), blob}
        pairs = append(pairs, pair{})
        copy(pairs[i+1:], pairs[i:])
        pairs[i] = el
    default:
        // element should be placed at the end of r.pairs
        pairs = append(pairs, pair{e.ENRKey(), blob})
    }
    r.pairs = pairs
}

func (r *Record) invalidate() {
    if r.signature == nil {
        r.seq++
    }
    r.signature = nil
    r.raw = nil
}

// EncodeRLP implements rlp.Encoder. Encoding fails if
// the record is unsigned.
func (r Record) EncodeRLP(w io.Writer) error {
    if !r.Signed() {
        return errEncodeUnsigned
    }
    _, err := w.Write(r.raw)
    return err
}

// DecodeRLP implements rlp.Decoder. Decoding verifies the signature.
func (r *Record) DecodeRLP(s *rlp.Stream) error {
    raw, err := s.Raw()
    if err != nil {
        return err
    }
    if len(raw) > SizeLimit {
        return errTooBig
    }

    // Decode the RLP container.
    dec := Record{raw: raw}
    s = rlp.NewStream(bytes.NewReader(raw), 0)
    if _, err := s.List(); err != nil {
        return err
    }
    if err = s.Decode(&dec.signature); err != nil {
        return err
    }
    if err = s.Decode(&dec.seq); err != nil {
        return err
    }
    // The rest of the record contains sorted k/v pairs.
    var prevkey string
    for i := 0; ; i++ {
        var kv pair
        if err := s.Decode(&kv.k); err != nil {
            if err == rlp.EOL {
                break
            }
            return err
        }
        if err := s.Decode(&kv.v); err != nil {
            if err == rlp.EOL {
                return errIncompletePair
            }
            return err
        }
        if i > 0 {
            if kv.k == prevkey {
                return errDuplicateKey
            }
            if kv.k < prevkey {
                return errNotSorted
            }
        }
        dec.pairs = append(dec.pairs, kv)
        prevkey = kv.k
    }
    if err := s.ListEnd(); err != nil {
        return err
    }

    _, scheme := dec.idScheme()
    if scheme == nil {
        return errNoID
    }
    if err := scheme.Verify(&dec, dec.signature); err != nil {
        return err
    }
    *r = dec
    return nil
}

// NodeAddr returns the node address. The return value will be nil if the record is
// unsigned or uses an unknown identity scheme.
func (r *Record) NodeAddr() []byte {
    _, scheme := r.idScheme()
    if scheme == nil {
        return nil
    }
    return scheme.NodeAddr(r)
}

// SetSig sets the record signature. It returns an error if the encoded record is larger
// than the size limit or if the signature is invalid according to the passed scheme.
func (r *Record) SetSig(idscheme string, sig []byte) error {
    // Check that "id" is set and matches the given scheme. This panics because
    // inconsitencies here are always implementation bugs in the signing function calling
    // this method.
    id, s := r.idScheme()
    if s == nil {
        panic(errNoID)
    }
    if id != idscheme {
        panic(fmt.Errorf("identity scheme mismatch in Sign: record has %s, want %s", id, idscheme))
    }

    // Verify against the scheme.
    if err := s.Verify(r, sig); err != nil {
        return err
    }
    raw, err := r.encode(sig)
    if err != nil {
        return err
    }
    r.signature, r.raw = sig, raw
    return nil
}

// AppendElements appends the sequence number and entries to the given slice.
func (r *Record) AppendElements(list []interface{}) []interface{} {
    list = append(list, r.seq)
    for _, p := range r.pairs {
        list = append(list, p.k, p.v)
    }
    return list
}

func (r *Record) encode(sig []byte) (raw []byte, err error) {
    list := make([]interface{}, 1, 2*len(r.pairs)+1)
    list[0] = sig
    list = r.AppendElements(list)
    if raw, err = rlp.EncodeToBytes(list); err != nil {
        return nil, err
    }
    if len(raw) > SizeLimit {
        return nil, errTooBig
    }
    return raw, nil
}

func (r *Record) idScheme() (string, IdentityScheme) {
    var id ID
    if err := r.Load(&id); err != nil {
        return "", nil
    }
    return string(id), FindIdentityScheme(string(id))
}