-
Notifications
You must be signed in to change notification settings - Fork 562
/
tlv.go
271 lines (229 loc) · 6.23 KB
/
tlv.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package waddrmgr
import (
"bytes"
"fmt"
"io"
"github.com/btcsuite/btcd/txscript"
"github.com/lightningnetwork/lnd/tlv"
)
const (
typeTapscriptType tlv.Type = 1
typeTapscriptControlBlock tlv.Type = 2
typeTapscriptLeaves tlv.Type = 3
typeTapscriptRevealedScript tlv.Type = 4
typeTapLeafVersion tlv.Type = 1
typeTapLeafScript tlv.Type = 2
)
// tlvEncodeTaprootScript encodes the given internal key and full set of taproot
// script leaves into a byte slice encoded as a TLV stream.
func tlvEncodeTaprootScript(s *Tapscript) ([]byte, error) {
if s == nil {
return nil, fmt.Errorf("cannot encode nil script")
}
typ := uint8(s.Type)
tlvRecords := []tlv.Record{
tlv.MakePrimitiveRecord(typeTapscriptType, &typ),
}
if s.ControlBlock != nil {
if s.ControlBlock.InternalKey == nil {
return nil, fmt.Errorf("control block is missing " +
"internal key")
}
blockBytes, err := s.ControlBlock.ToBytes()
if err != nil {
return nil, fmt.Errorf("error encoding control block: "+
"%v", err)
}
tlvRecords = append(tlvRecords, tlv.MakePrimitiveRecord(
typeTapscriptControlBlock, &blockBytes,
))
}
if len(s.Leaves) > 0 {
tlvRecords = append(tlvRecords, tlv.MakeDynamicRecord(
typeTapscriptLeaves, &s.Leaves, func() uint64 {
return recordSize(leavesEncoder, &s.Leaves)
}, leavesEncoder, leavesDecoder,
))
}
if len(s.RevealedScript) > 0 {
tlvRecords = append(tlvRecords, tlv.MakePrimitiveRecord(
typeTapscriptRevealedScript, &s.RevealedScript,
))
}
tlvStream, err := tlv.NewStream(tlvRecords...)
if err != nil {
return nil, err
}
var buf bytes.Buffer
err = tlvStream.Encode(&buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// tlvDecodeTaprootTaprootScript decodes the given byte slice as a TLV stream
// and attempts to parse the taproot internal key and full set of leaves from
// it.
func tlvDecodeTaprootTaprootScript(tlvData []byte) (*Tapscript, error) {
var (
typ uint8
controlBlockBytes []byte
s = &Tapscript{}
)
tlvStream, err := tlv.NewStream(
tlv.MakePrimitiveRecord(typeTapscriptType, &typ),
tlv.MakePrimitiveRecord(
typeTapscriptControlBlock, &controlBlockBytes,
),
tlv.MakeDynamicRecord(
typeTapscriptLeaves, &s.Leaves, func() uint64 {
return recordSize(leavesEncoder, &s.Leaves)
}, leavesEncoder, leavesDecoder,
),
tlv.MakePrimitiveRecord(
typeTapscriptRevealedScript, &s.RevealedScript,
),
)
if err != nil {
return nil, err
}
parsedTypes, err := tlvStream.DecodeWithParsedTypes(bytes.NewReader(
tlvData,
))
if err != nil {
return nil, err
}
s.Type = TapscriptType(typ)
if t, ok := parsedTypes[typeTapscriptControlBlock]; ok && t == nil {
s.ControlBlock, err = txscript.ParseControlBlock(
controlBlockBytes,
)
if err != nil {
return nil, fmt.Errorf("error decoding control block: "+
"%v", err)
}
}
return s, nil
}
// leavesEncoder is a custom TLV decoder for a slice of tap leaf records.
func leavesEncoder(w io.Writer, val interface{}, buf *[8]byte) error {
if v, ok := val.(*[]txscript.TapLeaf); ok {
for _, c := range *v {
leafVersion := uint8(c.LeafVersion)
tlvRecords := []tlv.Record{
tlv.MakePrimitiveRecord(
typeTapLeafVersion, &leafVersion,
),
}
if len(c.Script) > 0 {
tlvRecords = append(
tlvRecords, tlv.MakePrimitiveRecord(
typeTapLeafScript, &c.Script,
),
)
}
tlvStream, err := tlv.NewStream(tlvRecords...)
if err != nil {
return err
}
var leafTLVBytes bytes.Buffer
err = tlvStream.Encode(&leafTLVBytes)
if err != nil {
return err
}
// We encode the record with a varint length followed by
// the _raw_ TLV bytes.
tlvLen := uint64(len(leafTLVBytes.Bytes()))
if err := tlv.WriteVarInt(w, tlvLen, buf); err != nil {
return err
}
_, err = w.Write(leafTLVBytes.Bytes())
if err != nil {
return err
}
}
return nil
}
return tlv.NewTypeForEncodingErr(val, "[]txscript.TapLeaf")
}
// leavesDecoder is a custom TLV decoder for a slice of tap leaf records.
func leavesDecoder(r io.Reader, val interface{}, buf *[8]byte, l uint64) error {
if v, ok := val.(*[]txscript.TapLeaf); ok {
var leaves []txscript.TapLeaf
// Using the length information given, we'll create a new
// limited reader that'll return an EOF once the end has been
// reached so the stream stops consuming bytes.
innerTlvReader := io.LimitedReader{
R: r,
N: int64(l),
}
for {
// Read out the varint that encodes the size of this
// inner TLV record.
blobSize, err := tlv.ReadVarInt(r, buf)
if err == io.EOF {
break
} else if err != nil {
return err
}
innerInnerTlvReader := io.LimitedReader{
R: &innerTlvReader,
N: int64(blobSize),
}
var (
leafVersion uint8
script []byte
)
tlvStream, err := tlv.NewStream(
tlv.MakePrimitiveRecord(
typeTapLeafVersion, &leafVersion,
),
tlv.MakePrimitiveRecord(
typeTapLeafScript, &script,
),
)
if err != nil {
return err
}
parsedTypes, err := tlvStream.DecodeWithParsedTypes(
&innerInnerTlvReader,
)
if err != nil {
return err
}
leaf := txscript.TapLeaf{
LeafVersion: txscript.TapscriptLeafVersion(
leafVersion,
),
}
// Only set script when actually parsed to make
// difference between nil and empty slice work
// correctly. The parsedTypes entry must be nil if it
// was parsed fully.
if t, ok := parsedTypes[typeTapLeafScript]; ok && t == nil {
leaf.Script = script
}
leaves = append(leaves, leaf)
}
*v = leaves
return nil
}
return tlv.NewTypeForDecodingErr(val, "[]txscript.TapLeaf", l, l)
}
// recordSize returns the amount of bytes this TLV record will occupy when
// encoded.
func recordSize(encoder tlv.Encoder, v interface{}) uint64 {
var (
b bytes.Buffer
buf [8]byte
)
// We know that encoding works since the tests pass in the build this
// file is checked into, so we'll simplify things and simply encode it
// ourselves then report the total amount of bytes used.
if err := encoder(&b, v, &buf); err != nil {
// This should never error out, but we log it just in case it
// does.
log.Errorf("encoding the record failed: %v", err)
}
return uint64(len(b.Bytes()))
}