File: encoding_test.go

package info (click to toggle)
sia 1.3.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,340 kB
  • sloc: makefile: 80; sh: 52
file content (583 lines) | stat: -rw-r--r-- 17,223 bytes parent folder | download | duplicates (3)
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
package types

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math/big"
	"strings"
	"testing"

	"github.com/NebulousLabs/Sia/crypto"
	"github.com/NebulousLabs/Sia/encoding"
	"github.com/NebulousLabs/fastrand"
)

func hashStr(v interface{}) string {
	h := crypto.HashObject(v)
	return fmt.Sprintf("%x", h[:])
}

// TestBlockEncodes probes the MarshalSia and UnmarshalSia methods of the
// Block type.
func TestBlockEncoding(t *testing.T) {
	b := Block{
		MinerPayouts: []SiacoinOutput{
			{Value: CalculateCoinbase(0)},
			{Value: CalculateCoinbase(0)},
		},
	}
	var decB Block
	err := encoding.Unmarshal(encoding.Marshal(b), &decB)
	if err != nil {
		t.Fatal(err)
	}
	if len(decB.MinerPayouts) != len(b.MinerPayouts) ||
		decB.MinerPayouts[0].Value.Cmp(b.MinerPayouts[0].Value) != 0 ||
		decB.MinerPayouts[1].Value.Cmp(b.MinerPayouts[1].Value) != 0 {
		t.Fatal("block changed after encode/decode:", b, decB)
	}
}

// TestCurrencyMarshalJSON probes the MarshalJSON and UnmarshalJSON functions
// of the currency type.
func TestCurrencyMarshalJSON(t *testing.T) {
	b30 := big.NewInt(30)
	c30 := NewCurrency64(30)

	bMar30, err := b30.MarshalJSON()
	if err != nil {
		t.Fatal(err)
	}
	cMar30, err := c30.MarshalJSON()
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(bMar30, bytes.Trim(cMar30, `"`)) {
		t.Error("Currency does not match the marshalling of its math/big equivalent")
	}

	var cUmar30 Currency
	err = cUmar30.UnmarshalJSON(cMar30)
	if err != nil {
		t.Fatal(err)
	}
	if c30.Cmp(cUmar30) != 0 {
		t.Error("Incorrect unmarshalling of currency type.")
	}

	cMar30[0] = 0
	err = cUmar30.UnmarshalJSON(cMar30)
	if err == nil {
		t.Error("JSON decoded nonsense input")
	}
}

// TestCurrencyMarshalSia probes the MarshalSia and UnmarshalSia functions of
// the currency type.
func TestCurrencyMarshalSia(t *testing.T) {
	c := NewCurrency64(1656)
	buf := new(bytes.Buffer)
	err := c.MarshalSia(buf)
	if err != nil {
		t.Fatal(err)
	}
	var cUmar Currency
	cUmar.UnmarshalSia(buf)
	if c.Cmp(cUmar) != 0 {
		t.Error("marshal and unmarshal mismatch for currency type")
	}
}

// TestCurrencyString probes the String function of the currency type.
func TestCurrencyString(t *testing.T) {
	b := big.NewInt(7135)
	c := NewCurrency64(7135)
	if b.String() != c.String() {
		t.Error("string function not behaving as expected")
	}
}

// TestCurrencyScan probes the Scan function of the currency type.
func TestCurrencyScan(t *testing.T) {
	var c0 Currency
	c1 := NewCurrency64(81293)
	_, err := fmt.Sscan("81293", &c0)
	if err != nil {
		t.Fatal(err)
	}
	if c0.Cmp(c1) != 0 {
		t.Error("scanned number does not equal expected value")
	}
	_, err = fmt.Sscan("z", &c0)
	if err == nil {
		t.Fatal("scan is accepting garbage input")
	}
}

// TestCurrencyEncoding checks that a currency can encode and decode without
// error.
func TestCurrencyEncoding(t *testing.T) {
	c := NewCurrency64(351)
	cMar := encoding.Marshal(c)
	var cUmar Currency
	err := encoding.Unmarshal(cMar, &cUmar)
	if err != nil {
		t.Error("Error unmarshalling a currency:", err)
	}
	if cUmar.Cmp(c) != 0 {
		t.Error("Marshalling and Unmarshalling a currency did not work correctly")
	}
}

// TestNegativeCurrencyUnmarshalJSON tries to unmarshal a negative number from
// JSON.
func TestNegativeCurrencyUnmarshalJSON(t *testing.T) {
	// Marshal a 2 digit number.
	c := NewCurrency64(35)
	cMar, err := c.MarshalJSON()
	if err != nil {
		t.Fatal(err)
	}

	// Change the first digit to a negative character.
	cMar[0] = 45

	// Try unmarshalling the negative currency.
	var cNeg Currency
	err = cNeg.UnmarshalJSON(cMar)
	if err != ErrNegativeCurrency {
		t.Error("expecting ErrNegativeCurrency:", err)
	}
	if cNeg.i.Sign() < 0 {
		t.Error("negative currency returned")
	}
}

// TestNegativeCurrencyScan tries to scan in a negative number and checks for
// an error.
func TestNegativeCurrencyScan(t *testing.T) {
	var c Currency
	_, err := fmt.Sscan("-23", &c)
	if err != ErrNegativeCurrency {
		t.Error("expecting ErrNegativeCurrency:", err)
	}
}

// TestCurrencyUnsafeDecode tests that decoding into an existing Currency
// value does not overwrite its contents.
func TestCurrencyUnsafeDecode(t *testing.T) {
	// Scan
	backup := SiacoinPrecision.Mul64(1)
	c := SiacoinPrecision
	_, err := fmt.Sscan("7", &c)
	if err != nil {
		t.Error(err)
	} else if !SiacoinPrecision.Equals(backup) {
		t.Errorf("Scan changed value of SiacoinPrecision: %v -> %v", backup, SiacoinPrecision)
	}

	// UnmarshalSia
	c = SiacoinPrecision
	err = encoding.Unmarshal(encoding.Marshal(NewCurrency64(7)), &c)
	if err != nil {
		t.Error(err)
	} else if !SiacoinPrecision.Equals(backup) {
		t.Errorf("UnmarshalSia changed value of SiacoinPrecision: %v -> %v", backup, SiacoinPrecision)
	}
}

// TestTransactionEncoding tests that optimizations applied to the encoding of
// the Transaction type do not change its encoding.
func TestTransactionEncoding(t *testing.T) {
	var txn Transaction
	if h := hashStr(txn); h != "143aa0da2b6a4ca39eee3ee50a6536d75eedff3b5ef0229a6d603afa7854d5b8" {
		t.Error("encoding mismatch:", h)
	}

	txn = Transaction{
		SiacoinInputs:         []SiacoinInput{{}},
		SiacoinOutputs:        []SiacoinOutput{{}},
		FileContracts:         []FileContract{{}},
		FileContractRevisions: []FileContractRevision{{}},
		StorageProofs:         []StorageProof{{}},
		SiafundInputs:         []SiafundInput{{}},
		SiafundOutputs:        []SiafundOutput{{}},
		MinerFees:             []Currency{{}},
		ArbitraryData:         [][]byte{{}},
		TransactionSignatures: []TransactionSignature{{}},
	}
	if h := hashStr(txn); h != "a6c0f41cb89aaede0682ab06c1e757e12d662a0156ec878f85b935bc219fb3ca" {
		t.Error("encoding mismatch:", h)
	}
}

// TestSiacoinInputEncoding tests that optimizations applied to the encoding
// of the SiacoinInput type do not change its encoding.
func TestSiacoinInputEncoding(t *testing.T) {
	var sci SiacoinInput
	if h := hashStr(sci); h != "2f806f905436dc7c5079ad8062467266e225d8110a3c58d17628d609cb1c99d0" {
		t.Error("encoding mismatch:", h)
	}

	sci = SiacoinInput{
		ParentID:         SiacoinOutputID{1, 2, 3},
		UnlockConditions: UnlockConditions{},
	}
	if h := hashStr(sci); h != "f172a8f5892bb2b63eff32de6fd83c132be5ad134d1227d8881632bd809ae075" {
		t.Error("encoding mismatch:", h)
	}
}

// TestSiacoinOutputEncoding tests that optimizations applied to the encoding
// of the SiacoinOutput type do not change its encoding.
func TestSiacoinOutputEncoding(t *testing.T) {
	var sco SiacoinOutput
	if h := hashStr(sco); h != "4a1931803561f431decab002e7425f0a8531d5e456a1a47fd9998a2530c0f800" {
		t.Error("encoding mismatch:", h)
	}

	sco = SiacoinOutput{
		Value:      NewCurrency64(0),
		UnlockHash: UnlockHash{1, 2, 3},
	}
	if h := hashStr(sco); h != "32fb94ae64201f3e0a373947382367666bcf205d47a58ece9260c459986ae6fd" {
		t.Error("encoding mismatch:", h)
	}
}

// TestSiafundInputEncoding tests that optimizations applied to the encoding
// of the SiafundInput type do not change its encoding.
func TestSiafundInputEncoding(t *testing.T) {
	var sci SiafundInput
	if h := hashStr(sci); h != "978a948b1a92bcddcea382bafc7718a25f8cc49b8fb11db5d9159afa960cf70a" {
		t.Error("encoding mismatch:", h)
	}

	sci = SiafundInput{
		ParentID:         SiafundOutputID{1, 2, 3},
		UnlockConditions: UnlockConditions{1, nil, 3},
		ClaimUnlockHash:  UnlockHash{1, 2, 3},
	}
	if h := hashStr(sci); h != "1a6781ca002262e1def98e294f86dd81f866e2db9029954c64a36d20d0c6b46f" {
		t.Error("encoding mismatch:", h)
	}
}

// TestSiafundOutputEncoding tests that optimizations applied to the encoding
// of the SiafundOutput type do not change its encoding.
func TestSiafundOutputEncoding(t *testing.T) {
	var sco SiafundOutput
	if h := hashStr(sco); h != "df69a516de12056d0895fdea7a0274c5aba67091543238670513104c1af69c1f" {
		t.Error("encoding mismatch:", h)
	}

	sco = SiafundOutput{
		Value:      NewCurrency64(0),
		UnlockHash: UnlockHash{1, 2, 3},
		ClaimStart: NewCurrency64(4),
	}
	if h := hashStr(sco); h != "9524d2250b21adc76967e9f86d26a68982727329e5c42a6bf5e62504891a5176" {
		t.Error("encoding mismatch:", h)
	}
}

// TestCoveredFieldsEncoding tests that optimizations applied to the encoding
// of the CoveredFields type do not change its encoding.
func TestCoveredFieldsEncoding(t *testing.T) {
	var cf CoveredFields
	if h := hashStr(cf); h != "aecfdceb8b630b5b00668d229221f876b3be1630703c4615a642db2c666b4fd7" {
		t.Error("encoding mismatch:", h)
	}

	cf = CoveredFields{
		WholeTransaction:      true,
		SiacoinInputs:         []uint64{0},
		SiacoinOutputs:        []uint64{1},
		FileContracts:         []uint64{2},
		FileContractRevisions: []uint64{3},
		StorageProofs:         []uint64{4},
		SiafundInputs:         []uint64{5},
		SiafundOutputs:        []uint64{6},
		MinerFees:             []uint64{7},
		ArbitraryData:         []uint64{8},
		TransactionSignatures: []uint64{9, 10},
	}
	if h := hashStr(cf); h != "5b10cd6b50b09447aae02829643e62b513ce99b969a80aeb620f74e77ca9bbba" {
		t.Error("encoding mismatch:", h)
	}
}

// TestSiaPublicKeyEncoding tests that optimizations applied to the encoding
// of the SiaPublicKey type do not change its encoding.
func TestSiaPublicKeyEncoding(t *testing.T) {
	var spk SiaPublicKey
	if h := hashStr(spk); h != "19ea4a516c66775ea1f648d71f6b8fa227e8b0c1a0c9203f82c33b89c4e759b5" {
		t.Error("encoding mismatch:", h)
	}

	spk = SiaPublicKey{
		Algorithm: Specifier{1, 2, 3},
		Key:       []byte{4, 5, 6},
	}
	if h := hashStr(spk); h != "9c781bbeebc23a1885d00e778c358f0a4bc81a82b48191449129752a380adc03" {
		t.Error("encoding mismatch:", h)
	}
}

// TestSiaPublicKeyLoadString checks that the LoadString method is the proper
// inverse of the String() method, also checks that there are no stupid panics
// or severe errors.
func TestSiaPublicKeyLoadString(t *testing.T) {
	spk := SiaPublicKey{
		Algorithm: SignatureEd25519,
		Key:       fastrand.Bytes(32),
	}

	spkString := spk.String()
	var loadedSPK SiaPublicKey
	loadedSPK.LoadString(spkString)
	if !bytes.Equal(loadedSPK.Algorithm[:], spk.Algorithm[:]) {
		t.Error("SiaPublicKey is not loading correctly")
	}
	if !bytes.Equal(loadedSPK.Key, spk.Key) {
		t.Log(loadedSPK.Key, spk.Key)
		t.Error("SiaPublicKey is not loading correctly")
	}

	// Try loading crappy strings.
	parts := strings.Split(spkString, ":")
	spk.LoadString(parts[0])
	spk.LoadString(parts[0][1:])
	spk.LoadString(parts[0][:1])
	spk.LoadString(parts[1])
	spk.LoadString(parts[1][1:])
	spk.LoadString(parts[1][:1])
	spk.LoadString(parts[0] + parts[1])

}

// TestSiaPublicKeyString does a quick check to verify that the String method
// on the SiaPublicKey is producing the expected output.
func TestSiaPublicKeyString(t *testing.T) {
	spk := SiaPublicKey{
		Algorithm: SignatureEd25519,
		Key:       make([]byte, 32),
	}

	if spk.String() != "ed25519:0000000000000000000000000000000000000000000000000000000000000000" {
		t.Error("got wrong value for spk.String():", spk.String())
	}
}

// TestSpecifierMarshaling tests the marshaling methods of the specifier
// type.
func TestSpecifierMarshaling(t *testing.T) {
	s1 := SpecifierClaimOutput
	b, err := json.Marshal(s1)
	if err != nil {
		t.Fatal(err)
	}
	var s2 Specifier
	err = json.Unmarshal(b, &s2)
	if err != nil {
		t.Fatal(err)
	} else if s2 != s1 {
		t.Fatal("mismatch:", s1, s2)
	}

	// invalid json
	x := 3
	b, _ = json.Marshal(x)
	err = json.Unmarshal(b, &s2)
	if err == nil {
		t.Fatal("Unmarshal should have failed")
	}
}

// TestTransactionSignatureEncoding tests that optimizations applied to the
// encoding of the TransactionSignature type do not change its encoding.
func TestTransactionSignatureEncoding(t *testing.T) {
	var ts TransactionSignature
	if h := hashStr(ts); h != "5801097b0ae98fe7cedd4569afc11c0a433f284681ad4d66dd7181293f6d2bba" {
		t.Error("encoding mismatch:", h)
	}

	ts = TransactionSignature{
		ParentID:       crypto.Hash{1, 2, 3},
		PublicKeyIndex: 4,
		Timelock:       5,
		CoveredFields:  CoveredFields{},
		Signature:      []byte{6, 7, 8},
	}
	if h := hashStr(ts); h != "a3ce36fd8e1d6b7e5b030cdc2630d24a44472072bbd06e94d32d11132d817db0" {
		t.Error("encoding mismatch:", h)
	}
}

// TestUnlockConditionsEncoding tests that optimizations applied to the
// encoding of the UnlockConditions type do not change its encoding.
func TestUnlockConditionsEncoding(t *testing.T) {
	var uc UnlockConditions
	if h := hashStr(uc); h != "19ea4a516c66775ea1f648d71f6b8fa227e8b0c1a0c9203f82c33b89c4e759b5" {
		t.Error("encoding mismatch:", h)
	}

	uc = UnlockConditions{
		Timelock:           1,
		PublicKeys:         []SiaPublicKey{{}},
		SignaturesRequired: 3,
	}
	if h := hashStr(uc); h != "164d3741bd274d5333ab1fe8ab641b9d25cb0e0bed8e1d7bc466b5fffc956d96" {
		t.Error("encoding mismatch:", h)
	}
}

// TestUnlockHashJSONMarshalling checks that when an unlock hash is marshalled
// and unmarshalled using JSON, the result is what is expected.
func TestUnlockHashJSONMarshalling(t *testing.T) {
	// Create an unlock hash.
	uc := UnlockConditions{
		Timelock:           5,
		SignaturesRequired: 3,
	}
	uh := uc.UnlockHash()

	// Marshal the unlock hash.
	marUH, err := json.Marshal(uh)
	if err != nil {
		t.Fatal(err)
	}

	// Unmarshal the unlock hash and compare to the original.
	var umarUH UnlockHash
	err = json.Unmarshal(marUH, &umarUH)
	if err != nil {
		t.Fatal(err)
	}
	if umarUH != uh {
		t.Error("Marshalled and unmarshalled unlock hash are not equivalent")
	}

	// Corrupt the checksum.
	marUH[36]++
	err = umarUH.UnmarshalJSON(marUH)
	if err != ErrInvalidUnlockHashChecksum {
		t.Error("expecting an invalid checksum:", err)
	}
	marUH[36]--

	// Try an input that's not correct hex.
	marUH[7] += 100
	err = umarUH.UnmarshalJSON(marUH)
	if err == nil {
		t.Error("Expecting error after corrupting input")
	}
	marUH[7] -= 100

	// Try an input of the wrong length.
	err = (&umarUH).UnmarshalJSON(marUH[2:])
	if err != ErrUnlockHashWrongLen {
		t.Error("Got wrong error:", err)
	}
}

// TestUnlockHashStringMarshalling checks that when an unlock hash is
// marshalled and unmarshalled using String and LoadString, the result is what
// is expected.
func TestUnlockHashStringMarshalling(t *testing.T) {
	// Create an unlock hash.
	uc := UnlockConditions{
		Timelock:           2,
		SignaturesRequired: 7,
	}
	uh := uc.UnlockHash()

	// Marshal the unlock hash.
	marUH := uh.String()

	// Unmarshal the unlock hash and compare to the original.
	var umarUH UnlockHash
	err := umarUH.LoadString(marUH)
	if err != nil {
		t.Fatal(err)
	}
	if umarUH != uh {
		t.Error("Marshalled and unmarshalled unlock hash are not equivalent")
	}

	// Corrupt the checksum.
	byteMarUH := []byte(marUH)
	byteMarUH[36]++
	err = umarUH.LoadString(string(byteMarUH))
	if err != ErrInvalidUnlockHashChecksum {
		t.Error("expecting an invalid checksum:", err)
	}
	byteMarUH[36]--

	// Try an input that's not correct hex.
	byteMarUH[7] += 100
	err = umarUH.LoadString(string(byteMarUH))
	if err == nil {
		t.Error("Expecting error after corrupting input")
	}
	byteMarUH[7] -= 100

	// Try an input of the wrong length.
	err = umarUH.LoadString(string(byteMarUH[2:]))
	if err != ErrUnlockHashWrongLen {
		t.Error("Got wrong error:", err)
	}
}

// TestCurrencyHumanString checks that the HumanString method of the currency
// type is correctly formatting values.
func TestCurrencyUnits(t *testing.T) {
	tests := []struct {
		in  Currency
		out string
	}{
		{NewCurrency64(1), "1 H"},
		{NewCurrency64(1000), "1000 H"},
		{NewCurrency64(100000000000), "100000000000 H"},
		{NewCurrency64(1000000000000), "1 pS"},
		{NewCurrency64(1234560000000), "1.235 pS"},
		{NewCurrency64(12345600000000), "12.35 pS"},
		{NewCurrency64(123456000000000), "123.5 pS"},
		{NewCurrency64(1000000000000000), "1 nS"},
		{NewCurrency64(1000000000000000000), "1 uS"},
		{NewCurrency64(1000000000).Mul64(1000000000000), "1 mS"},
		{NewCurrency64(1).Mul(SiacoinPrecision), "1 SC"},
		{NewCurrency64(1000).Mul(SiacoinPrecision), "1 KS"},
		{NewCurrency64(1000000).Mul(SiacoinPrecision), "1 MS"},
		{NewCurrency64(1000000000).Mul(SiacoinPrecision), "1 GS"},
		{NewCurrency64(1000000000000).Mul(SiacoinPrecision), "1 TS"},
		{NewCurrency64(1234560000000).Mul(SiacoinPrecision), "1.235 TS"},
		{NewCurrency64(1234560000000000).Mul(SiacoinPrecision), "1235 TS"},
	}
	for _, test := range tests {
		if test.in.HumanString() != test.out {
			t.Errorf("currencyUnits(%v): expected %v, got %v", test.in, test.out, test.in.HumanString())
		}
	}
}

// TestTransactionMarshalSiaSize tests that the txn.MarshalSiaSize method is
// always consistent with len(encoding.Marshal(txn)).
func TestTransactionMarshalSiaSize(t *testing.T) {
	txn := Transaction{
		SiacoinInputs:         []SiacoinInput{{}},
		SiacoinOutputs:        []SiacoinOutput{{}},
		FileContracts:         []FileContract{{}},
		FileContractRevisions: []FileContractRevision{{}},
		StorageProofs:         []StorageProof{{}},
		SiafundInputs:         []SiafundInput{{}},
		SiafundOutputs:        []SiafundOutput{{}},
		MinerFees:             []Currency{{}},
		ArbitraryData:         [][]byte{{}},
		TransactionSignatures: []TransactionSignature{{}},
	}
	if txn.MarshalSiaSize() != len(encoding.Marshal(txn)) {
		t.Errorf("sizes do not match: expected %v, got %v", len(encoding.Marshal(txn)), txn.MarshalSiaSize())
	}
}