package tx import ( "bytes" "errors" "testing" ) // TestDecodeRoundTrip: what the wallet writes, it reads back byte for byte, with and without // witnesses. func TestDecodeRoundTrip(t *testing.T) { transaction := New() transaction.AddInput(Outpoint{Hash: [32]byte{1, 2, 3}, Index: 7}, 0xfffffffe) transaction.AddInput(Outpoint{Hash: [32]byte{4}, Index: 0}, 0xffffffff) transaction.AddOutput(50_000, []byte{0x00, 0x14, 1, 2, 3, 4}) transaction.AddOutput(1_000, []byte{0x6a}) transaction.LockTime = 42 raw, err := transaction.Serialize() if err != nil { t.Fatalf("Serialize: %v", err) } decoded, err := Decode(raw) if err != nil { t.Fatalf("Decode: %v", err) } if decoded.Version != transaction.Version || decoded.LockTime != 42 { t.Fatalf("version %d locktime %d", decoded.Version, decoded.LockTime) } if len(decoded.Inputs) != 2 || len(decoded.Outputs) != 2 { t.Fatalf("%d inputs, %d outputs", len(decoded.Inputs), len(decoded.Outputs)) } if decoded.Inputs[0].Index != 7 || decoded.Inputs[0].Hash != ([32]byte{1, 2, 3}) { t.Fatalf("first outpoint %v", decoded.Inputs[0].Outpoint) } if decoded.Outputs[0].Value != 50_000 || !bytes.Equal(decoded.Outputs[0].Script, []byte{0x00, 0x14, 1, 2, 3, 4}) { t.Fatalf("first output %+v", decoded.Outputs[0]) } again, err := decoded.Serialize() if err != nil || !bytes.Equal(again, raw) { t.Fatalf("re-serialised differs: %v", err) } // With a witness. transaction.Inputs[0].Witness = [][]byte{{1, 2}, {3}} wire, err := transaction.SerializeWitness() if err != nil { t.Fatalf("SerializeWitness: %v", err) } decoded, err = Decode(wire) if err != nil { t.Fatalf("Decode with witness: %v", err) } if len(decoded.Inputs[0].Witness) != 2 || decoded.Inputs[0].Witness[1][0] != 3 { t.Fatalf("witness %v", decoded.Inputs[0].Witness) } if decoded.TxIDOrPanic(t) != transaction.TxIDOrPanic(t) { t.Fatal("the decoded transaction has a different txid") } } // TxIDOrPanic is a test convenience: a txid error is a test failure, not a value to compare. func (t *Tx) TxIDOrPanic(tb testing.TB) [32]byte { tb.Helper() id, err := t.TxID() if err != nil { tb.Fatalf("TxID: %v", err) } return id } // TestDecodeRefusesBadInput: truncation and trailing bytes are errors, not shorter // transactions. func TestDecodeRefusesBadInput(t *testing.T) { transaction := New() transaction.AddInput(Outpoint{Index: 1}, 0) transaction.AddOutput(1, []byte{0x6a}) raw, err := transaction.Serialize() if err != nil { t.Fatal(err) } for cut := 0; cut < len(raw); cut++ { if _, err := Decode(raw[:cut]); err == nil { t.Fatalf("%d bytes decoded", cut) } } if _, err := Decode(append(append([]byte(nil), raw...), 0x00)); !errors.Is(err, ErrTrailing) { t.Fatalf("trailing byte: %v", err) } }