-
Notifications
You must be signed in to change notification settings - Fork 0
/
gid.go
82 lines (76 loc) · 1.64 KB
/
gid.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
package types
import (
"encoding/hex"
"fmt"
"github.com/koinotice/vite/crypto"
"math/big"
)
const (
GidSize = 10
hexGidIdLength = 2 * GidSize
)
var (
PRIVATE_GID = Gid{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
SNAPSHOT_GID = Gid{0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
DELEGATE_GID = Gid{0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
)
type Gid [GidSize]byte
func DataToGid(data ...[]byte) Gid {
gid, _ := BytesToGid(crypto.Hash(GidSize, data...))
return gid
}
func HexToGid(hexStr string) (Gid, error) {
if len(hexStr) != hexGidIdLength {
return Gid{}, fmt.Errorf("Not valid hex gid")
}
gid, err := hex.DecodeString(hexStr)
if err != nil {
return Gid{}, fmt.Errorf("Not valid hex gid")
}
return BytesToGid(gid)
}
func BigToGid(data *big.Int) (Gid, error) {
slice := data.Bytes()
if len(slice) < GidSize {
padded := make([]byte, GidSize)
copy(padded[GidSize-len(slice):], slice)
return BytesToGid(padded)
} else {
return BytesToGid(slice)
}
}
func BytesToGid(b []byte) (Gid, error) {
var gid Gid
err := gid.SetBytes(b)
return gid, err
}
func (gid *Gid) SetBytes(b []byte) error {
if len(b) != GidSize {
return fmt.Errorf("error gid size %v", len(b))
}
copy(gid[:], b)
return nil
}
func (gid *Gid) Bytes() []byte {
return gid[:]
}
func (gid Gid) Hex() string {
return hex.EncodeToString(gid[:])
}
func (gid Gid) String() string {
return gid.Hex()
}
func (gid *Gid) UnmarshalJSON(input []byte) error {
if !isString(input) {
return ErrJsonNotString
}
g, e := HexToGid(string(trimLeftRightQuotation(input)))
if e != nil {
return e
}
gid.SetBytes(g.Bytes())
return nil
}
func (gid Gid) MarshalText() ([]byte, error) {
return []byte(gid.String()), nil
}