/
util.go
140 lines (123 loc) · 2.28 KB
/
util.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
package box
import (
"bytes"
"encoding/binary"
"math/big"
)
const u32Len uint32 = 4
func marshalSignature(r, s *big.Int) []byte {
sig := newbw(nil)
sig.Write(r.Bytes())
sig.Write(s.Bytes())
return sig.Bytes()
}
type bw struct {
buf *bytes.Buffer
err error
}
func newbw(init []byte) *bw {
b := new(bw)
b.buf = new(bytes.Buffer)
if init != nil {
b.buf.Write(init)
}
return b
}
func (b *bw) Write(data []byte) {
if b.err != nil {
return
}
b.err = binary.Write(b.buf, binary.BigEndian, uint32(len(data)))
b.buf.Write(data)
}
func (b *bw) WriteUint32(n uint32) {
if b.err != nil {
return
}
b.err = binary.Write(b.buf, binary.BigEndian, u32Len)
if b.err == nil {
b.err = binary.Write(b.buf, binary.BigEndian, n)
}
}
func (b *bw) Bytes() []byte {
if b.err != nil {
return nil
}
return b.buf.Bytes()
}
func unmarshalSignature(sig []byte) (r, s *big.Int) {
b := newbr(sig)
rb := b.Next()
sb := b.Next()
if rb != nil && sb != nil {
r = new(big.Int).SetBytes(rb)
s = new(big.Int).SetBytes(sb)
}
return
}
type br struct {
buf *bytes.Buffer
err error
}
func newbr(data []byte) *br {
b := new(br)
b.buf = bytes.NewBuffer(data)
return b
}
func (b *br) Next() []byte {
if b.err != nil {
return nil
}
var dlen uint32
b.err = binary.Read(b.buf, binary.BigEndian, &dlen)
if b.err == nil {
if int(dlen) > b.buf.Len() {
return nil
} else if int(dlen) <= 0 {
return nil
}
data := make([]byte, int(dlen))
b.buf.Read(data)
return data
}
return nil
}
func (b *br) NextU32() (uint32, bool) {
if b.err != nil {
return 0, false
}
var n uint32
b.err = binary.Read(b.buf, binary.BigEndian, &n)
if b.err != nil {
return 0, false
}
if int(n) > b.buf.Len() {
return 0, false
}
b.err = binary.Read(b.buf, binary.BigEndian, &n)
return n, b.err == nil
}
// Zero out a byte slice.
func zero(in []byte) {
if in == nil {
return
}
inlen := len(in)
for i := 0; i < inlen; i++ {
in[i] ^= in[i]
}
}
// zeroPad returns a new slice of length size. The contents of input are right
// aligned in the new slice.
func zeroPad(in []byte, outlen int) (out []byte) {
var inLen int
if inLen = len(in); inLen > outlen {
inLen = outlen
} else if inLen == outlen {
return in
}
start := outlen - inLen
out = make([]byte, outlen)
copy(out[start:], in)
return
}