package tx import ( "bytes" "crypto/sha256" "encoding/binary" "encoding/hex" "errors" ) const MaxMoney int64 = 21000000 * 100000000 type OutPoint struct { Hash [32]byte Index uint32 } type Input struct { Previous OutPoint Script []byte Sequence uint32 Witness [][]byte } type Output struct { Value int64 Script []byte } type Transaction struct { Version int32 Inputs []Input Outputs []Output LockTime uint32 } func compact(b *bytes.Buffer, n uint64) { switch { case n < 253: b.WriteByte(byte(n)) case n <= 65535: b.WriteByte(253) binary.Write(b, binary.LittleEndian, uint16(n)) case n <= 0xffffffff: b.WriteByte(254) binary.Write(b, binary.LittleEndian, uint32(n)) default: b.WriteByte(255) binary.Write(b, binary.LittleEndian, n) } } func blob(b *bytes.Buffer, data []byte) { compact(b, uint64(len(data))); b.Write(data) } func (t Transaction) Serialize(witness bool) []byte { var b bytes.Buffer put := func(v any) { binary.Write(&b, binary.LittleEndian, v) } put(t.Version) has := false for _, in := range t.Inputs { if len(in.Witness) > 0 { has = true } } has = has && witness if has { b.Write([]byte{0, 1}) } compact(&b, uint64(len(t.Inputs))) for _, in := range t.Inputs { b.Write(in.Previous.Hash[:]) put(in.Previous.Index) blob(&b, in.Script) put(in.Sequence) } compact(&b, uint64(len(t.Outputs))) for _, out := range t.Outputs { put(out.Value) blob(&b, out.Script) } if has { for _, in := range t.Inputs { compact(&b, uint64(len(in.Witness))) for _, item := range in.Witness { blob(&b, item) } } } put(t.LockTime) return b.Bytes() } func displayHash(data []byte) string { h := sha256.Sum256(data) h = sha256.Sum256(h[:]) for i := 0; i < 16; i++ { h[i], h[31-i] = h[31-i], h[i] } return hex.EncodeToString(h[:]) } func (t Transaction) TXID() string { return displayHash(t.Serialize(false)) } func (t Transaction) WTXID() string { return displayHash(t.Serialize(true)) } func (t Transaction) Weight() int { return 3*len(t.Serialize(false)) + len(t.Serialize(true)) } func (t Transaction) VSize() int { return (t.Weight() + 3) / 4 } // Fee checks a supplied UTXO snapshot, not chain state or scripts. func (t Transaction) Fee(coins map[OutPoint]Output) (int64, error) { if len(t.Inputs) == 0 || len(t.Outputs) == 0 { return 0, errors.New("empty transaction") } var totalIn, totalOut int64 seen := make(map[OutPoint]bool) for _, in := range t.Inputs { if seen[in.Previous] { return 0, errors.New("duplicate input") } seen[in.Previous] = true coin, ok := coins[in.Previous] if !ok { return 0, errors.New("missing prevout") } if coin.Value < 0 || coin.Value > MaxMoney-totalIn { return 0, errors.New("input amount out of range") } totalIn += coin.Value } for _, out := range t.Outputs { if out.Value < 0 || out.Value > MaxMoney-totalOut { return 0, errors.New("output amount out of range") } totalOut += out.Value } if totalOut > totalIn { return 0, errors.New("insufficient input value") } return totalIn - totalOut, nil }