-
Notifications
You must be signed in to change notification settings - Fork 17
/
types.go
129 lines (107 loc) · 2.34 KB
/
types.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
package rlp
import (
"errors"
"fmt"
"net"
"time"
"github.com/indexsupply/x/bint"
"github.com/indexsupply/x/isxsecp256k1"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
)
var errNoData = errors.New("requested item contains 0 bytes")
func Bytes(b []byte) Item {
if b == nil {
return Item{d: []byte{}}
}
return Item{d: b}
}
func (i Item) Bytes() []byte {
return i.d
}
func Uint16(n uint16) Item {
return Item{d: bint.Encode(nil, uint64(n))}
}
func (i Item) Uint16() uint16 {
return uint16(bint.Decode(i.d))
}
func Uint64(n uint64) Item {
return Item{d: bint.Encode(nil, n)}
}
func (i Item) Uint64() uint64 {
return bint.Decode(i.d)
}
func String(s string) Item {
return Item{d: []byte(s)}
}
func (i Item) String() string {
return string(i.d)
}
func Time(t time.Time) Item {
return Uint64(uint64(t.Unix()))
}
func (i Item) Time() time.Time {
return time.Unix(int64(i.Uint64()), 0)
}
// Uncompressed secpk256k1 public key
func Secp256k1PublicKey(pubk *secp256k1.PublicKey) Item {
b := isxsecp256k1.Encode(pubk)
return Bytes(b[:])
}
func (i Item) Secp256k1PublicKey() (*secp256k1.PublicKey, error) {
switch len(i.d) {
case 0:
return nil, errNoData
case 33:
var b [33]byte
copy(b[:], i.d)
return isxsecp256k1.DecodeCompressed(b)
case 64:
var b [64]byte
copy(b[:], i.d)
return isxsecp256k1.Decode(b)
default:
return nil, errors.New(fmt.Sprintf("secp256k1 pubkey must be 33 or 64 bytes. got: %d", len(i.d)))
}
}
func (i Item) Hash() ([32]byte, error) {
var h [32]byte
if len(i.d) == 0 {
return h, errNoData
}
if len(i.d) != 32 {
return h, errors.New("hash must be exactly 32 bytes")
}
copy(h[:], i.d)
return h, nil
}
func (i Item) IP() (net.IP, error) {
switch len(i.d) {
case 0:
return nil, errNoData
case 4, 16:
return net.IP(i.d), nil
default:
return nil, errors.New(fmt.Sprintf("ip must be 4 or 16 bytes. got: %d", len(i.d)))
}
}
func (i Item) Bytes32() ([32]byte, error) {
if len(i.d) != 32 {
return [32]byte{}, errors.New("must be exactly 32 bytes")
}
return *(*[32]byte)(i.d), nil
}
func (i Item) Bytes65() ([65]byte, error) {
if len(i.d) != 65 {
return [65]byte{}, errors.New("must be exactly 65 bytes")
}
return *(*[65]byte)(i.d), nil
}
func Byte(b byte) Item {
if b == 0 {
return Item{d: []byte{}}
}
return Item{d: []byte{b}}
}
func Int(n int) Item {
return Item{d: bint.Encode(nil, uint64(n))}
}