generated from ipfs/ipfs-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathrecord.go
471 lines (389 loc) · 11.1 KB
/
record.go
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//go:generate protoc -I=pb --go_out=pb pb/record.proto
package ipns
import (
"bytes"
"errors"
"fmt"
"sort"
"time"
ipns_pb "github.com/ipfs/boxo/ipns/pb"
"github.com/ipfs/boxo/path"
"github.com/ipfs/boxo/util"
logging "github.com/ipfs/go-log/v2"
"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/codec/dagcbor"
"github.com/ipld/go-ipld-prime/datamodel"
basicnode "github.com/ipld/go-ipld-prime/node/basic"
ic "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
"go.uber.org/multierr"
"google.golang.org/protobuf/proto"
)
var log = logging.Logger("ipns")
type ValidityType int64
// ValidityEOL means "this record is valid until {Validity}". This is currently
// the only supported Validity type.
const ValidityEOL ValidityType = 0
// Record represents an [IPNS Record].
//
// [IPNS Record]: https://specs.ipfs.tech/ipns/ipns-record/
type Record struct {
pb *ipns_pb.IpnsRecord
node datamodel.Node
}
// UnmarshalRecord parses the [Protobuf-serialized] IPNS Record into a usable
// [Record] struct. Please note that this function does not perform a full
// validation of the record. For that use [Validate].
//
// [Protobuf-serialized]: https://specs.ipfs.tech/ipns/ipns-record/#record-serialization-format
func UnmarshalRecord(data []byte) (*Record, error) {
if len(data) > MaxRecordSize {
return nil, ErrRecordSize
}
var pb ipns_pb.IpnsRecord
err := proto.Unmarshal(data, &pb)
if err != nil {
return nil, multierr.Combine(ErrInvalidRecord, err)
}
record := &Record{
pb: &pb,
}
// Ensure the record has DAG-CBOR data because we need it.
if len(pb.GetData()) == 0 {
return nil, multierr.Combine(ErrInvalidRecord, ErrDataMissing)
}
// Decode CBOR data.
builder := basicnode.Prototype__Map{}.NewBuilder()
if err := dagcbor.Decode(builder, bytes.NewReader(pb.GetData())); err != nil {
return nil, multierr.Combine(ErrInvalidRecord, err)
}
record.node = builder.Build()
return record, nil
}
// MarshalRecord encodes the given IPNS Record into its [Protobuf serialization format].
//
// [Protobuf serialization format]: https://specs.ipfs.tech/ipns/ipns-record/#record-serialization-format
func MarshalRecord(rec *Record) ([]byte, error) {
return proto.Marshal(rec.pb)
}
// Value returns the [path.Path] that is embedded in this IPNS Record. If the
// path is invalid, an [ErrInvalidPath] is returned.
func (rec *Record) Value() (path.Path, error) {
value, err := rec.getBytesValue(cborValueKey)
if err != nil {
return nil, err
}
p, err := path.NewPath(string(value))
if err != nil {
return nil, multierr.Combine(ErrInvalidPath, err)
}
return p, nil
}
func (rec *Record) ValidityType() (ValidityType, error) {
value, err := rec.getIntValue(cborValidityTypeKey)
if err != nil {
return -1, err
}
return ValidityType(value), nil
}
// Validity returns the validity of the IPNS Record. This function returns
// [ErrUnrecognizedValidity] if the validity type of the record isn't EOL.
// Otherwise, it returns an error if it can't parse the EOL.
func (rec *Record) Validity() (time.Time, error) {
validityType, err := rec.ValidityType()
if err != nil {
return time.Time{}, err
}
switch validityType {
case ValidityEOL:
value, err := rec.getBytesValue(cborValidityKey)
if err != nil {
return time.Time{}, err
}
v, err := util.ParseRFC3339(string(value))
if err != nil {
return time.Time{}, multierr.Combine(ErrInvalidValidity, err)
}
return v, nil
default:
return time.Time{}, ErrUnrecognizedValidity
}
}
func (rec *Record) Sequence() (uint64, error) {
value, err := rec.getIntValue(cborSequenceKey)
if err != nil {
return 0, err
}
return uint64(value), nil
}
func (rec *Record) TTL() (time.Duration, error) {
value, err := rec.getIntValue(cborTTLKey)
if err != nil {
return 0, err
}
return time.Duration(value), nil
}
func (rec *Record) PubKey() (ic.PubKey, error) {
if pk := rec.pb.GetPubKey(); len(pk) != 0 {
return ic.UnmarshalPublicKey(pk)
}
return nil, ErrPublicKeyNotFound
}
func (rec *Record) getBytesValue(key string) ([]byte, error) {
node, err := rec.node.LookupByString(key)
if err != nil {
return nil, multierr.Combine(ErrInvalidRecord, err)
}
value, err := node.AsBytes()
if err != nil {
return nil, multierr.Combine(ErrInvalidRecord, err)
}
return value, nil
}
func (rec *Record) getIntValue(key string) (int64, error) {
node, err := rec.node.LookupByString(key)
if err != nil {
return -1, multierr.Combine(ErrInvalidRecord, err)
}
value, err := node.AsInt()
if err != nil {
return -1, multierr.Combine(ErrInvalidRecord, err)
}
return value, nil
}
const (
cborValidityKey = "Validity"
cborValidityTypeKey = "ValidityType"
cborValueKey = "Value"
cborSequenceKey = "Sequence"
cborTTLKey = "TTL"
)
type options struct {
v1Compatibility bool
embedPublicKey *bool
}
type Option func(*options)
func WithV1Compatibility(compatible bool) Option {
return func(o *options) {
o.v1Compatibility = compatible
}
}
func WithPublicKey(embedded bool) Option {
return func(o *options) {
o.embedPublicKey = &embedded
}
}
func processOptions(opts ...Option) *options {
options := &options{
// TODO: produce V2-only records by default after IPIP-XXXX ships with Kubo
// and Helia for at least 6 months.
v1Compatibility: true,
}
for _, opt := range opts {
opt(options)
}
return options
}
// NewRecord creates a new IPNS [Record] and signs it with the given private key.
// By default, we embed the public key for key types whose peer IDs do not encode
// the public key, such as RSA and ECDSA key types. This can be changed with the
// option [WithPublicKey]. In addition, records are, by default created with V1
// compatibility.
func NewRecord(sk ic.PrivKey, value path.Path, seq uint64, eol time.Time, ttl time.Duration, opts ...Option) (*Record, error) {
options := processOptions(opts...)
node, err := createNode(value, seq, eol, ttl)
if err != nil {
return nil, err
}
cborData, err := nodeToCBOR(node)
if err != nil {
return nil, err
}
sig2Data, err := recordDataForSignatureV2(cborData)
if err != nil {
return nil, err
}
sig2, err := sk.Sign(sig2Data)
if err != nil {
return nil, err
}
pb := ipns_pb.IpnsRecord{
Data: cborData,
SignatureV2: sig2,
}
if options.v1Compatibility {
pb.Value = []byte(value.String())
typ := ipns_pb.IpnsRecord_EOL
pb.ValidityType = &typ
pb.Sequence = &seq
pb.Validity = []byte(util.FormatRFC3339(eol))
ttlNs := uint64(ttl.Nanoseconds())
pb.Ttl = proto.Uint64(ttlNs)
// For now we still create V1 signatures. These are deprecated, and not
// used during verification anymore (Validate func requires SignatureV2),
// but setting it here allows legacy nodes (e.g., go-ipfs < v0.9.0) to
// still resolve IPNS published by modern nodes.
sig1, err := sk.Sign(recordDataForSignatureV1(&pb))
if err != nil {
return nil, fmt.Errorf("%w: could not compute signature data", err)
}
pb.SignatureV1 = sig1
}
embedPublicKey := false
if options.embedPublicKey == nil {
embedPublicKey, err = needToEmbedPublicKey(sk.GetPublic())
if err != nil {
return nil, err
}
} else {
embedPublicKey = *options.embedPublicKey
}
if embedPublicKey {
pkBytes, err := ic.MarshalPublicKey(sk.GetPublic())
if err != nil {
return nil, err
}
pb.PubKey = pkBytes
}
return &Record{
pb: &pb,
node: node,
}, nil
}
func createNode(value path.Path, seq uint64, eol time.Time, ttl time.Duration) (datamodel.Node, error) {
m := make(map[string]ipld.Node)
var keys []string
m[cborValueKey] = basicnode.NewBytes([]byte(value.String()))
keys = append(keys, cborValueKey)
m[cborValidityKey] = basicnode.NewBytes([]byte(util.FormatRFC3339(eol)))
keys = append(keys, cborValidityKey)
m[cborValidityTypeKey] = basicnode.NewInt(int64(ValidityEOL))
keys = append(keys, cborValidityTypeKey)
m[cborSequenceKey] = basicnode.NewInt(int64(seq))
keys = append(keys, cborSequenceKey)
m[cborTTLKey] = basicnode.NewInt(int64(ttl))
keys = append(keys, cborTTLKey)
sort.Slice(keys, func(i, j int) bool {
li, lj := len(keys[i]), len(keys[j])
if li == lj {
return keys[i] < keys[j]
}
return li < lj
})
newNd := basicnode.Prototype__Map{}.NewBuilder()
ma, err := newNd.BeginMap(int64(len(keys)))
if err != nil {
return nil, err
}
for _, k := range keys {
if err := ma.AssembleKey().AssignString(k); err != nil {
return nil, err
}
if err := ma.AssembleValue().AssignNode(m[k]); err != nil {
return nil, err
}
}
if err := ma.Finish(); err != nil {
return nil, err
}
return newNd.Build(), nil
}
func nodeToCBOR(node datamodel.Node) ([]byte, error) {
buf := new(bytes.Buffer)
if err := dagcbor.Encode(node, buf); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func recordDataForSignatureV1(e *ipns_pb.IpnsRecord) []byte {
return bytes.Join([][]byte{
e.Value,
e.Validity,
[]byte(fmt.Sprint(e.GetValidityType())),
},
[]byte{})
}
func recordDataForSignatureV2(data []byte) ([]byte, error) {
dataForSig := []byte("ipns-signature:")
dataForSig = append(dataForSig, data...)
return dataForSig, nil
}
func needToEmbedPublicKey(pk ic.PubKey) (bool, error) {
// First try extracting the peer ID from the public key.
pid, err := peer.IDFromPublicKey(pk)
if err != nil {
return false, fmt.Errorf("cannot convert public key to peer ID: %w", err)
}
_, err = pid.ExtractPublicKey()
if err == nil {
// Can be extracted, therefore no need to embed the public key.
return false, nil
}
if errors.Is(err, peer.ErrNoPublicKey) {
return true, nil
}
return false, fmt.Errorf("cannot extract ID from public key: %w", err)
}
// compare compares two IPNS Records. It returns:
//
// - -1 if a is older than b
// - 0 if a and b cannot be ordered (this doesn't mean that they are equal)
// - +1 if a is newer than b
//
// This function does not validate the records. The caller is responsible for
// ensuring that the Records are valid by using [Validate].
func compare(a, b *Record) (int, error) {
aHasV2Sig := a.pb.GetSignatureV2() != nil
bHasV2Sig := b.pb.GetSignatureV2() != nil
// Having a newer signature version is better than an older signature version
if aHasV2Sig && !bHasV2Sig {
return 1, nil
} else if !aHasV2Sig && bHasV2Sig {
return -1, nil
}
as, err := a.Sequence()
if err != nil {
return 0, err
}
bs, err := b.Sequence()
if err != nil {
return 0, err
}
if as > bs {
return 1, nil
} else if as < bs {
return -1, nil
}
at, err := a.Validity()
if err != nil {
return 0, err
}
bt, err := b.Validity()
if err != nil {
return 0, err
}
if at.After(bt) {
return 1, nil
} else if bt.After(at) {
return -1, nil
}
return 0, nil
}
// ExtractPublicKey extracts a [crypto.PubKey] matching the given [Name] from
// the IPNS Record, if possible.
func ExtractPublicKey(rec *Record, name Name) (ic.PubKey, error) {
if pk, err := rec.PubKey(); err == nil {
expPid, err := peer.IDFromPublicKey(pk)
if err != nil {
return nil, multierr.Combine(ErrInvalidPublicKey, err)
}
if !name.Equal(NameFromPeer(expPid)) {
return nil, ErrPublicKeyMismatch
}
return pk, nil
} else if !errors.Is(err, ErrPublicKeyNotFound) {
return nil, multierr.Combine(ErrInvalidPublicKey, err)
} else {
return name.Peer().ExtractPublicKey()
}
}