common_test.go raw
1 package wire
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "reflect"
8 "strings"
9 "testing"
10
11 "github.com/davecgh/go-spew/spew"
12
13 "github.com/p9c/p9/pkg/chainhash"
14 )
15
16 // mainNetGenesisHash is the hash of the first block in the block chain for the main network (genesis block).
17 var mainNetGenesisHash = chainhash.Hash([chainhash.HashSize]byte{
18 0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
19 0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
20 0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
21 0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
22 },
23 )
24
25 // mainNetGenesisMerkleRoot is the hash of the first transaction in the genesis block for the main network.
26 var mainNetGenesisMerkleRoot = chainhash.Hash([chainhash.HashSize]byte{
27 0x3b, 0xa3, 0xed, 0xfd, 0x7a, 0x7b, 0x12, 0xb2,
28 0x7a, 0xc7, 0x2c, 0x3e, 0x67, 0x76, 0x8f, 0x61,
29 0x7f, 0xc8, 0x1b, 0xc3, 0x88, 0x8a, 0x51, 0x32,
30 0x3a, 0x9f, 0xb8, 0xaa, 0x4b, 0x1e, 0x5e, 0x4a,
31 },
32 )
33
34 // fakeRandReader implements the io.Reader interface and is used to force errors in the RandomUint64 function.
35 type fakeRandReader struct {
36 n int
37 e error
38 }
39
40 // Read returns the fake reader error and the lesser of the fake reader value and the length of p.
41 func (r *fakeRandReader) Read(p []byte) (int, error) {
42 n := r.n
43 if n > len(p) {
44 n = len(p)
45 }
46 return n, r.e
47 }
48
49 // // TestElementWire tests wire encode and decode for various element types. This is mainly to test the "fast" paths in
50 // readElement and writeElement which use type assertions to avoid reflection when possible.
51 //
52 // func TestElementWire(t *testing.T) {
53 // type writeElementReflect int32
54 // tests := []struct {
55 // in interface{} // value to encode
56 // buf []byte // Wire encoding
57 // }{
58 // {int32(1), []byte{0x01, 0x00, 0x00, 0x00}},
59 // {uint32(256), []byte{0x00, 0x01, 0x00, 0x00}},
60 // {
61 // int64(65536),
62 // []byte{0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00},
63 // },
64 // {
65 // uint64(4294967296),
66 // []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00},
67 // },
68 // {
69 // true,
70 // []byte{0x01},
71 // },
72 // {
73 // false,
74 // []byte{0x00},
75 // },
76 // {
77 // [4]byte{0x01, 0x02, 0x03, 0x04},
78 // []byte{0x01, 0x02, 0x03, 0x04},
79 // },
80 // {
81 // [CommandSize]byte{
82 // 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
83 // 0x09, 0x0a, 0x0b, 0x0c,
84 // },
85 // []byte{
86 // 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
87 // 0x09, 0x0a, 0x0b, 0x0c,
88 // },
89 // },
90 // {
91 // [16]byte{
92 // 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
93 // 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
94 // },
95 // []byte{
96 // 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
97 // 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
98 // },
99 // },
100 // {
101 // (*chainhash.Hash)(&[chainhash.HashSize]byte{
102 // 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
103 // 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
104 // 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
105 // 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
106 // }),
107 // []byte{
108 // 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
109 // 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
110 // 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
111 // 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
112 // },
113 // },
114 // {
115 // ServiceFlag(SFNodeNetwork),
116 // []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
117 // },
118 // {
119 // InvType(InvTypeTx),
120 // []byte{0x01, 0x00, 0x00, 0x00},
121 // },
122 // {
123 // BitcoinNet(MainNet),
124 // []byte{0xf9, 0xbe, 0xb4, 0xd9},
125 // },
126 // // Type not supported by the "fast" path and requires reflection.
127 // {
128 // writeElementReflect(1),
129 // []byte{0x01, 0x00, 0x00, 0x00},
130 // },
131 // }
132 // t.Logf("Running %d tests", len(tests))
133 // for i, test := range tests {
134 // // Write to wire format.
135 // var buf bytes.Buffer
136 // e := writeElement(&buf, test.in)
137 // if e != nil {
138 // t.Errorf("writeElement #%d error %v", i, e)
139 // continue
140 // }
141 // if !bytes.Equal(buf.Hash(), test.buf) {
142 // t.Errorf("writeElement #%d\n got: %s want: %s", i,
143 // spew.Sdump(buf.Hash()), spew.Sdump(test.buf))
144 // continue
145 // }
146 // // Read from wire format.
147 // rbuf := bytes.NewReader(test.buf)
148 // val := test.in
149 // if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
150 // val = reflect.New(reflect.TypeOf(test.in)).Interface()
151 // }
152 // e = readElement(rbuf, val)
153 // if e != nil {
154 // t.Errorf("readElement #%d error %v", i, e)
155 // continue
156 // }
157 // ival := val
158 // if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
159 // ival = reflect.Indirect(reflect.ValueOf(val)).Interface()
160 // }
161 // if !reflect.DeepEqual(ival, test.in) {
162 // t.Errorf("readElement #%d\n got: %s want: %s", i,
163 // spew.Sdump(ival), spew.Sdump(test.in))
164 // continue
165 // }
166 // }
167 // }
168
169 // TestElementWireErrors performs negative tests against wire encode and decode of various element types to confirm error paths work correctly.
170 func TestElementWireErrors(t *testing.T) {
171 tests := []struct {
172 in interface{} // value to encode
173 max int // Max size of fixed buffer to induce errors
174 writeErr error // Expected write error
175 readErr error // Expected read error
176 }{
177 {int32(1), 0, io.ErrShortWrite, io.EOF},
178 {uint32(256), 0, io.ErrShortWrite, io.EOF},
179 {int64(65536), 0, io.ErrShortWrite, io.EOF},
180 {true, 0, io.ErrShortWrite, io.EOF},
181 {[4]byte{0x01, 0x02, 0x03, 0x04}, 0, io.ErrShortWrite, io.EOF},
182 {
183 [CommandSize]byte{
184 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
185 0x09, 0x0a, 0x0b, 0x0c,
186 },
187 0, io.ErrShortWrite, io.EOF,
188 },
189 {
190 [16]byte{
191 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
192 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
193 },
194 0, io.ErrShortWrite, io.EOF,
195 },
196 {
197 (*chainhash.Hash)(&[chainhash.HashSize]byte{
198 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
199 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
200 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
201 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
202 },
203 ),
204 0, io.ErrShortWrite, io.EOF,
205 },
206 {SFNodeNetwork, 0, io.ErrShortWrite, io.EOF},
207 {InvTypeTx, 0, io.ErrShortWrite, io.EOF},
208 {MainNet, 0, io.ErrShortWrite, io.EOF},
209 }
210 t.Logf("Running %d tests", len(tests))
211 for i, test := range tests {
212 // Encode to wire format.
213 w := newFixedWriter(test.max)
214 e := writeElement(w, test.in)
215 if e != test.writeErr {
216 t.Errorf("writeElement #%d wrong error got: %v, want: %v",
217 i, e, test.writeErr,
218 )
219 continue
220 }
221 // Decode from wire format.
222 r := newFixedReader(test.max, nil)
223 val := test.in
224 if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
225 val = reflect.New(reflect.TypeOf(test.in)).Interface()
226 }
227 e = readElement(r, val)
228 if e != test.readErr {
229 t.Errorf("readElement #%d wrong error got: %v, want: %v",
230 i, e, test.readErr,
231 )
232 continue
233 }
234 }
235 }
236
237 // TestVarIntWire tests wire encode and decode for variable length integers.
238 func TestVarIntWire(t *testing.T) {
239 pver := ProtocolVersion
240 tests := []struct {
241 in uint64 // value to encode
242 out uint64 // Expected decoded value
243 buf []byte // Wire encoding
244 pver uint32 // Protocol version for wire encoding
245 }{
246 // Latest protocol version.
247 // Single byte
248 {0, 0, []byte{0x00}, pver},
249 // Max single byte
250 {0xfc, 0xfc, []byte{0xfc}, pver},
251 // Min 2-byte
252 {0xfd, 0xfd, []byte{0xfd, 0x0fd, 0x00}, pver},
253 // Max 2-byte
254 {0xffff, 0xffff, []byte{0xfd, 0xff, 0xff}, pver},
255 // Min 4-byte
256 {0x10000, 0x10000, []byte{0xfe, 0x00, 0x00, 0x01, 0x00}, pver},
257 // Max 4-byte
258 {0xffffffff, 0xffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff}, pver},
259 // Min 8-byte
260 {
261 0x100000000, 0x100000000,
262 []byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00},
263 pver,
264 },
265 // Max 8-byte
266 {
267 0xffffffffffffffff, 0xffffffffffffffff,
268 []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
269 pver,
270 },
271 }
272 t.Logf("Running %d tests", len(tests))
273 for i, test := range tests {
274 // Encode to wire format.
275 var buf bytes.Buffer
276 e := WriteVarInt(&buf, test.pver, test.in)
277 if e != nil {
278 t.Errorf("WriteVarInt #%d error %v", i, e)
279 continue
280 }
281 if !bytes.Equal(buf.Bytes(), test.buf) {
282 t.Errorf("WriteVarInt #%d\n got: %s want: %s", i,
283 spew.Sdump(buf.Bytes()), spew.Sdump(test.buf),
284 )
285 continue
286 }
287 // Decode from wire format.
288 rbuf := bytes.NewReader(test.buf)
289 val, e := ReadVarInt(rbuf, test.pver)
290 if e != nil {
291 t.Errorf("ReadVarInt #%d error %v", i, e)
292 continue
293 }
294 if val != test.out {
295 t.Errorf("ReadVarInt #%d\n got: %d want: %d", i,
296 val, test.out,
297 )
298 continue
299 }
300 }
301 }
302
303 // TestVarIntWireErrors performs negative tests against wire encode and decode of variable length integers to confirm
304 // error paths work correctly.
305 func TestVarIntWireErrors(t *testing.T) {
306 pver := ProtocolVersion
307 tests := []struct {
308 in uint64 // value to encode
309 buf []byte // Wire encoding
310 pver uint32 // Protocol version for wire encoding
311 max int // Max size of fixed buffer to induce errors
312 writeErr error // Expected write error
313 readErr error // Expected read error
314 }{
315 // Force errors on discriminant.
316 {0, []byte{0x00}, pver, 0, io.ErrShortWrite, io.EOF},
317 // Force errors on 2-byte read/write.
318 {0xfd, []byte{0xfd}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
319 // Force errors on 4-byte read/write.
320 {0x10000, []byte{0xfe}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
321 // Force errors on 8-byte read/write.
322 {0x100000000, []byte{0xff}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
323 }
324 t.Logf("Running %d tests", len(tests))
325 for i, test := range tests {
326 // Encode to wire format.
327 w := newFixedWriter(test.max)
328 e := WriteVarInt(w, test.pver, test.in)
329 if e != test.writeErr {
330 t.Errorf("WriteVarInt #%d wrong error got: %v, want: %v",
331 i, e, test.writeErr,
332 )
333 continue
334 }
335 // Decode from wire format.
336 r := newFixedReader(test.max, test.buf)
337 _, e = ReadVarInt(r, test.pver)
338 if e != test.readErr {
339 t.Errorf("ReadVarInt #%d wrong error got: %v, want: %v",
340 i, e, test.readErr,
341 )
342 continue
343 }
344 }
345 }
346
347 // TestVarIntNonCanonical ensures variable length integers that are not encoded canonically return the expected error.
348 func TestVarIntNonCanonical(t *testing.T) {
349 pver := ProtocolVersion
350 tests := []struct {
351 name string // Test name for easier identification
352 in []byte // value to decode
353 pver uint32 // Protocol version for wire encoding
354 }{
355 {
356 "0 encoded with 3 bytes", []byte{0xfd, 0x00, 0x00},
357 pver,
358 },
359 {
360 "max single-byte value encoded with 3 bytes",
361 []byte{0xfd, 0xfc, 0x00}, pver,
362 },
363 {
364 "0 encoded with 5 bytes",
365 []byte{0xfe, 0x00, 0x00, 0x00, 0x00}, pver,
366 },
367 {
368 "max three-byte value encoded with 5 bytes",
369 []byte{0xfe, 0xff, 0xff, 0x00, 0x00}, pver,
370 },
371 {
372 "0 encoded with 9 bytes",
373 []byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
374 pver,
375 },
376 {
377 "max five-byte value encoded with 9 bytes",
378 []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00},
379 pver,
380 },
381 }
382 t.Logf("Running %d tests", len(tests))
383 for i, test := range tests {
384 // Decode from wire format.
385 rbuf := bytes.NewReader(test.in)
386 val, e := ReadVarInt(rbuf, test.pver)
387 if _, ok := e.(*MessageError); !ok {
388 t.Errorf("ReadVarInt #%d (%s) unexpected error %v", i,
389 test.name, e,
390 )
391 continue
392 }
393 if val != 0 {
394 t.Errorf("ReadVarInt #%d (%s)\n got: %d want: 0", i,
395 test.name, val,
396 )
397 continue
398 }
399 }
400 }
401
402 // TestVarIntWire tests the serialize size for variable length integers.
403 func TestVarIntSerializeSize(t *testing.T) {
404 tests := []struct {
405 val uint64 // value to get the serialized size for
406 size int // Expected serialized size
407 }{
408 // Single byte
409 {0, 1},
410 // Max single byte
411 {0xfc, 1},
412 // Min 2-byte
413 {0xfd, 3},
414 // Max 2-byte
415 {0xffff, 3},
416 // Min 4-byte
417 {0x10000, 5},
418 // Max 4-byte
419 {0xffffffff, 5},
420 // Min 8-byte
421 {0x100000000, 9},
422 // Max 8-byte
423 {0xffffffffffffffff, 9},
424 }
425 t.Logf("Running %d tests", len(tests))
426 for i, test := range tests {
427 serializedSize := VarIntSerializeSize(test.val)
428 if serializedSize != test.size {
429 t.Errorf("VarIntSerializeSize #%d got: %d, want: %d", i,
430 serializedSize, test.size,
431 )
432 continue
433 }
434 }
435 }
436
437 // TestVarStringWire tests wire encode and decode for variable length strings.
438 func TestVarStringWire(t *testing.T) {
439 pver := ProtocolVersion
440 // str256 is a string that takes a 2-byte varint to encode.
441 str256 := strings.Repeat("test", 64)
442 tests := []struct {
443 in string // String to encode
444 out string // String to decoded value
445 buf []byte // Wire encoding
446 pver uint32 // Protocol version for wire encoding
447 }{
448 // Latest protocol version.
449 // Empty string
450 {"", "", []byte{0x00}, pver},
451 // Single byte varint + string
452 {"Test", "Test", append([]byte{0x04}, []byte("Test")...), pver},
453 // 2-byte varint + string
454 {str256, str256, append([]byte{0xfd, 0x00, 0x01}, []byte(str256)...), pver},
455 }
456 t.Logf("Running %d tests", len(tests))
457 for i, test := range tests {
458 // Encode to wire format.
459 var buf bytes.Buffer
460 e := WriteVarString(&buf, test.pver, test.in)
461 if e != nil {
462 t.Errorf("WriteVarString #%d error %v", i, e)
463 continue
464 }
465 if !bytes.Equal(buf.Bytes(), test.buf) {
466 t.Errorf("WriteVarString #%d\n got: %s want: %s", i,
467 spew.Sdump(buf.Bytes()), spew.Sdump(test.buf),
468 )
469 continue
470 }
471 // Decode from wire format.
472 rbuf := bytes.NewReader(test.buf)
473 val, e := ReadVarString(rbuf, test.pver)
474 if e != nil {
475 t.Errorf("ReadVarString #%d error %v", i, e)
476 continue
477 }
478 if val != test.out {
479 t.Errorf("ReadVarString #%d\n got: %s want: %s", i,
480 val, test.out,
481 )
482 continue
483 }
484 }
485 }
486
487 // TestVarStringWireErrors performs negative tests against wire encode and decode of variable length strings to confirm
488 // error paths work correctly.
489 func TestVarStringWireErrors(t *testing.T) {
490 pver := ProtocolVersion
491 // str256 is a string that takes a 2-byte varint to encode.
492 str256 := strings.Repeat("test", 64)
493 tests := []struct {
494 in string // value to encode
495 buf []byte // Wire encoding
496 pver uint32 // Protocol version for wire encoding
497 max int // Max size of fixed buffer to induce errors
498 writeErr error // Expected write error
499 readErr error // Expected read error
500 }{
501 // Latest protocol version with intentional read/write errors. Force errors on empty string.
502 {"", []byte{0x00}, pver, 0, io.ErrShortWrite, io.EOF},
503 // Force error on single byte varint + string.
504 {"Test", []byte{0x04}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
505 // Force errors on 2-byte varint + string.
506 {str256, []byte{0xfd}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
507 }
508 t.Logf("Running %d tests", len(tests))
509 for i, test := range tests {
510 // Encode to wire format.
511 w := newFixedWriter(test.max)
512 e := WriteVarString(w, test.pver, test.in)
513 if e != test.writeErr {
514 t.Errorf("WriteVarString #%d wrong error got: %v, want: %v",
515 i, e, test.writeErr,
516 )
517 continue
518 }
519 // Decode from wire format.
520 r := newFixedReader(test.max, test.buf)
521 _, e = ReadVarString(r, test.pver)
522 if e != test.readErr {
523 t.Errorf("ReadVarString #%d wrong error got: %v, want: %v",
524 i, e, test.readErr,
525 )
526 continue
527 }
528 }
529 }
530
531 // TestVarStringOverflowErrors performs tests to ensure deserializing variable length strings intentionally crafted to
532 // use large values for the string length are handled properly. This could otherwise potentially be used as an attack
533 // vector.
534 func TestVarStringOverflowErrors(t *testing.T) {
535 pver := ProtocolVersion
536 tests := []struct {
537 buf []byte // Wire encoding
538 pver uint32 // Protocol version for wire encoding
539 e error // Expected error
540 }{
541 {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
542 pver, &MessageError{},
543 },
544 {[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
545 pver, &MessageError{},
546 },
547 }
548 t.Logf("Running %d tests", len(tests))
549 for i, test := range tests {
550 // Decode from wire format.
551 rbuf := bytes.NewReader(test.buf)
552 _, e := ReadVarString(rbuf, test.pver)
553 if reflect.TypeOf(e) != reflect.TypeOf(test.e) {
554 t.Errorf("ReadVarString #%d wrong error got: %v, "+
555 "want: %v", i, e, reflect.TypeOf(test.e),
556 )
557 continue
558 }
559 }
560 }
561
562 // TestVarBytesWire tests wire encode and decode for variable length byte array.
563 func TestVarBytesWire(t *testing.T) {
564 pver := ProtocolVersion
565 // bytes256 is a byte array that takes a 2-byte varint to encode.
566 bytes256 := bytes.Repeat([]byte{0x01}, 256)
567 tests := []struct {
568 in []byte // Byte Array to write
569 buf []byte // Wire encoding
570 pver uint32 // Protocol version for wire encoding
571 }{
572 // Latest protocol version.
573 // Empty byte array
574 {[]byte{}, []byte{0x00}, pver},
575 // Single byte varint + byte array
576 {[]byte{0x01}, []byte{0x01, 0x01}, pver},
577 // 2-byte varint + byte array
578 {bytes256, append([]byte{0xfd, 0x00, 0x01}, bytes256...), pver},
579 }
580 t.Logf("Running %d tests", len(tests))
581 for i, test := range tests {
582 // Encode to wire format.
583 var buf bytes.Buffer
584 e := WriteVarBytes(&buf, test.pver, test.in)
585 if e != nil {
586 t.Errorf("WriteVarBytes #%d error %v", i, e)
587 continue
588 }
589 if !bytes.Equal(buf.Bytes(), test.buf) {
590 t.Errorf("WriteVarBytes #%d\n got: %s want: %s", i,
591 spew.Sdump(buf.Bytes()), spew.Sdump(test.buf),
592 )
593 continue
594 }
595 // Decode from wire format.
596 rbuf := bytes.NewReader(test.buf)
597 val, e := ReadVarBytes(rbuf, test.pver, MaxMessagePayload,
598 "test payload",
599 )
600 if e != nil {
601 t.Errorf("ReadVarBytes #%d error %v", i, e)
602 continue
603 }
604 if !bytes.Equal(buf.Bytes(), test.buf) {
605 t.Errorf("ReadVarBytes #%d\n got: %s want: %s", i,
606 val, test.buf,
607 )
608 continue
609 }
610 }
611 }
612
613 // TestVarBytesWireErrors performs negative tests against wire encode and decode of variable length byte arrays to
614 // confirm error paths work correctly.
615 func TestVarBytesWireErrors(t *testing.T) {
616 pver := ProtocolVersion
617 // bytes256 is a byte array that takes a 2-byte varint to encode.
618 bytes256 := bytes.Repeat([]byte{0x01}, 256)
619 tests := []struct {
620 in []byte // Byte Array to write
621 buf []byte // Wire encoding
622 pver uint32 // Protocol version for wire encoding
623 max int // Max size of fixed buffer to induce errors
624 writeErr error // Expected write error
625 readErr error // Expected read error
626 }{
627 // Latest protocol version with intentional read/write errors.
628 // Force errors on empty byte array.
629 {[]byte{}, []byte{0x00}, pver, 0, io.ErrShortWrite, io.EOF},
630 // Force error on single byte varint + byte array.
631 {[]byte{0x01, 0x02, 0x03}, []byte{0x04}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
632 // Force errors on 2-byte varint + byte array.
633 {bytes256, []byte{0xfd}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
634 }
635 t.Logf("Running %d tests", len(tests))
636 for i, test := range tests {
637 // Encode to wire format.
638 w := newFixedWriter(test.max)
639 e := WriteVarBytes(w, test.pver, test.in)
640 if e != test.writeErr {
641 t.Errorf("WriteVarBytes #%d wrong error got: %v, want: %v",
642 i, e, test.writeErr,
643 )
644 continue
645 }
646 // Decode from wire format.
647 r := newFixedReader(test.max, test.buf)
648 _, e = ReadVarBytes(r, test.pver, MaxMessagePayload,
649 "test payload",
650 )
651 if e != test.readErr {
652 t.Errorf("ReadVarBytes #%d wrong error got: %v, want: %v",
653 i, e, test.readErr,
654 )
655 continue
656 }
657 }
658 }
659
660 // TestVarBytesOverflowErrors performs tests to ensure deserializing variable length byte arrays intentionally crafted
661 // to use large values for the array length are handled properly. This could otherwise potentially be used as an attack
662 // vector.
663 func TestVarBytesOverflowErrors(t *testing.T) {
664 pver := ProtocolVersion
665 tests := []struct {
666 buf []byte // Wire encoding
667 pver uint32 // Protocol version for wire encoding
668 e error // Expected error
669 }{
670 {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
671 pver, &MessageError{},
672 },
673 {[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
674 pver, &MessageError{},
675 },
676 }
677 t.Logf("Running %d tests", len(tests))
678 for i, test := range tests {
679 // Decode from wire format.
680 rbuf := bytes.NewReader(test.buf)
681 _, e := ReadVarBytes(rbuf, test.pver, MaxMessagePayload,
682 "test payload",
683 )
684 if reflect.TypeOf(e) != reflect.TypeOf(test.e) {
685 t.Errorf("ReadVarBytes #%d wrong error got: %v, "+
686 "want: %v", i, e, reflect.TypeOf(test.e),
687 )
688 continue
689 }
690 }
691 }
692
693 // TestRandomUint64 exercises the randomness of the random number generator on the system by ensuring the probability of
694 // the generated numbers. If the RNG is evenly distributed as a proper cryptographic RNG should be, there really should
695 // only be 1 number < 2^56 in 2^8 tries for a 64-bit number. However, use a higher number of 5 to really ensure the test
696 // doesn't fail unless the RNG is just horrendous.
697 func TestRandomUint64(t *testing.T) {
698 tries := 1 << 8 // 2^8
699 watermark := uint64(1 << 56) // 2^56
700 maxHits := 5
701 badRNG := "The random number generator on this system is clearly " +
702 "terrible since we got %d values less than %d in %d runs " +
703 "when only %d was expected"
704 numHits := 0
705 for i := 0; i < tries; i++ {
706 nonce, e := RandomUint64()
707 if e != nil {
708 t.Errorf("RandomUint64 iteration %d failed - e %v",
709 i, e,
710 )
711 return
712 }
713 if nonce < watermark {
714 numHits++
715 }
716 if numHits > maxHits {
717 str := fmt.Sprintf(badRNG, numHits, watermark, tries, maxHits)
718 t.Errorf("Random Uint64 iteration %d failed - %v %v", i,
719 str, numHits,
720 )
721 return
722 }
723 }
724 }
725
726 // TestRandomUint64Errors uses a fake reader to force error paths to be executed and checks the results accordingly.
727 func TestRandomUint64Errors(t *testing.T) {
728 // Test short reads.
729 fr := &fakeRandReader{n: 2, e: io.EOF}
730 nonce, e := randomUint64(fr)
731 if e != io.ErrUnexpectedEOF {
732 t.Errorf("Error not expected value of %v [%v]",
733 io.ErrUnexpectedEOF, e,
734 )
735 }
736 if nonce != 0 {
737 t.Errorf("Nonce is not 0 [%v]", nonce)
738 }
739 }
740