forked from libp2p/go-libp2p
/
voucher.go
69 lines (54 loc) · 1.56 KB
/
voucher.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
package proto
import (
"time"
"github.com/JonyBepary/go-libp2p-pq/core/peer"
"github.com/JonyBepary/go-libp2p-pq/core/record"
pbv2 "github.com/JonyBepary/go-libp2p-pq/p2p/protocol/circuitv2/pb"
"google.golang.org/protobuf/proto"
)
const RecordDomain = "libp2p-relay-rsvp"
// TODO: register in multicodec table in https://github.com/multiformats/multicodec
var RecordCodec = []byte{0x03, 0x02}
func init() {
record.RegisterType(&ReservationVoucher{})
}
type ReservationVoucher struct {
// Relay is the ID of the peer providing relay service
Relay peer.ID
// Peer is the ID of the peer receiving relay service through Relay
Peer peer.ID
// Expiration is the expiration time of the reservation
Expiration time.Time
}
var _ record.Record = (*ReservationVoucher)(nil)
func (rv *ReservationVoucher) Domain() string {
return RecordDomain
}
func (rv *ReservationVoucher) Codec() []byte {
return RecordCodec
}
func (rv *ReservationVoucher) MarshalRecord() ([]byte, error) {
expiration := uint64(rv.Expiration.Unix())
return proto.Marshal(&pbv2.ReservationVoucher{
Relay: []byte(rv.Relay),
Peer: []byte(rv.Peer),
Expiration: &expiration,
})
}
func (rv *ReservationVoucher) UnmarshalRecord(blob []byte) error {
pbrv := pbv2.ReservationVoucher{}
err := proto.Unmarshal(blob, &pbrv)
if err != nil {
return err
}
rv.Relay, err = peer.IDFromBytes(pbrv.GetRelay())
if err != nil {
return err
}
rv.Peer, err = peer.IDFromBytes(pbrv.GetPeer())
if err != nil {
return err
}
rv.Expiration = time.Unix(int64(pbrv.GetExpiration()), 0)
return nil
}