/
peer_id.go
63 lines (50 loc) · 1.22 KB
/
peer_id.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
package p2pkey
import (
"database/sql/driver"
"encoding/json"
"fmt"
"strings"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/pkg/errors"
)
const peerIDPrefix = "p2p_"
type PeerID peer.ID
func (p PeerID) String() string {
return fmt.Sprintf("%s%s", peerIDPrefix, peer.ID(p).String())
}
func (p PeerID) Raw() string {
return peer.ID(p).String()
}
func (p *PeerID) UnmarshalText(bs []byte) error {
input := string(bs)
if strings.HasPrefix(input, peerIDPrefix) {
input = string(bs[len(peerIDPrefix):])
}
peerID, err := peer.Decode(input)
if err != nil {
return errors.Wrapf(err, `PeerID#UnmarshalText("%v")`, input)
}
*p = PeerID(peerID)
return nil
}
func (p *PeerID) Scan(value interface{}) error {
s, is := value.(string)
if !is {
return errors.Errorf("PeerID#Scan got %T, expected string", value)
}
*p = PeerID("")
return p.UnmarshalText([]byte(s))
}
func (p PeerID) Value() (driver.Value, error) {
return peer.Encode(peer.ID(p)), nil
}
func (p PeerID) MarshalJSON() ([]byte, error) {
return json.Marshal(p.String())
}
func (p *PeerID) UnmarshalJSON(input []byte) error {
var result string
if err := json.Unmarshal(input, &result); err != nil {
return err
}
return p.UnmarshalText([]byte(result))
}