1// Copyright (c) 2013-2016 The btcsuite developers
2// Use of this source code is governed by an ISC
3// license that can be found in the LICENSE file.
4
5package btcutil_test
6
7import (
8	"bytes"
9	"io"
10	"reflect"
11	"testing"
12
13	"github.com/btcsuite/btcd/chaincfg/chainhash"
14	"github.com/btcsuite/btcutil"
15	"github.com/davecgh/go-spew/spew"
16)
17
18// TestTx tests the API for Tx.
19func TestTx(t *testing.T) {
20	testTx := Block100000.Transactions[0]
21	tx := btcutil.NewTx(testTx)
22
23	// Ensure we get the same data back out.
24	if msgTx := tx.MsgTx(); !reflect.DeepEqual(msgTx, testTx) {
25		t.Errorf("MsgTx: mismatched MsgTx - got %v, want %v",
26			spew.Sdump(msgTx), spew.Sdump(testTx))
27	}
28
29	// Ensure transaction index set and get work properly.
30	wantIndex := 0
31	tx.SetIndex(0)
32	if gotIndex := tx.Index(); gotIndex != wantIndex {
33		t.Errorf("Index: mismatched index - got %v, want %v",
34			gotIndex, wantIndex)
35	}
36
37	// Hash for block 100,000 transaction 0.
38	wantHashStr := "8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87"
39	wantHash, err := chainhash.NewHashFromStr(wantHashStr)
40	if err != nil {
41		t.Errorf("NewHashFromStr: %v", err)
42	}
43
44	// Request the hash multiple times to test generation and caching.
45	for i := 0; i < 2; i++ {
46		hash := tx.Hash()
47		if !hash.IsEqual(wantHash) {
48			t.Errorf("Hash #%d mismatched hash - got %v, want %v", i,
49				hash, wantHash)
50		}
51	}
52}
53
54// TestNewTxFromBytes tests creation of a Tx from serialized bytes.
55func TestNewTxFromBytes(t *testing.T) {
56	// Serialize the test transaction.
57	testTx := Block100000.Transactions[0]
58	var testTxBuf bytes.Buffer
59	err := testTx.Serialize(&testTxBuf)
60	if err != nil {
61		t.Errorf("Serialize: %v", err)
62	}
63	testTxBytes := testTxBuf.Bytes()
64
65	// Create a new transaction from the serialized bytes.
66	tx, err := btcutil.NewTxFromBytes(testTxBytes)
67	if err != nil {
68		t.Errorf("NewTxFromBytes: %v", err)
69		return
70	}
71
72	// Ensure the generated MsgTx is correct.
73	if msgTx := tx.MsgTx(); !reflect.DeepEqual(msgTx, testTx) {
74		t.Errorf("MsgTx: mismatched MsgTx - got %v, want %v",
75			spew.Sdump(msgTx), spew.Sdump(testTx))
76	}
77}
78
79// TestTxErrors tests the error paths for the Tx API.
80func TestTxErrors(t *testing.T) {
81	// Serialize the test transaction.
82	testTx := Block100000.Transactions[0]
83	var testTxBuf bytes.Buffer
84	err := testTx.Serialize(&testTxBuf)
85	if err != nil {
86		t.Errorf("Serialize: %v", err)
87	}
88	testTxBytes := testTxBuf.Bytes()
89
90	// Truncate the transaction byte buffer to force errors.
91	shortBytes := testTxBytes[:4]
92	_, err = btcutil.NewTxFromBytes(shortBytes)
93	if err != io.EOF {
94		t.Errorf("NewTxFromBytes: did not get expected error - "+
95			"got %v, want %v", err, io.EOF)
96	}
97}
98