package segwit import ( "bytes" "crypto/sha256" "encoding/binary" "errors" ) func Hash256(b []byte) [32]byte { h := sha256.Sum256(b); return sha256.Sum256(h[:]) } func P2WPKH(hash []byte) ([]byte, error) { if len(hash) != 20 { return nil, errors.New("expected 20-byte hash") } return append([]byte{0, 20}, hash...), nil } func P2WSH(script []byte) []byte { h := sha256.Sum256(script); return append([]byte{0, 32}, h[:]...) } func MatchesWitnessScript(program, script []byte) bool { return bytes.Equal(program, P2WSH(script)) } func P2WPKHScriptCode(hash []byte) ([]byte, error) { if len(hash) != 20 { return nil, errors.New("expected 20-byte hash") } b := append([]byte{0x76, 0xa9, 20}, hash...) return append(b, 0x88, 0xac), nil } 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 SerializeWitness(items [][]byte) []byte { var b bytes.Buffer compact(&b, uint64(len(items))) for _, v := range items { compact(&b, uint64(len(v))) b.Write(v) } return b.Bytes() } type Outpoint struct { Hash [32]byte Index uint32 } type Input struct { Previous Outpoint Sequence uint32 } type Output struct { Value int64 Script []byte } type Tx struct { Version int32 Inputs []Input Outputs []Output Locktime uint32 } func put(b *bytes.Buffer, v any) { binary.Write(b, binary.LittleEndian, v) } func outpoint(b *bytes.Buffer, o Outpoint) { b.Write(o.Hash[:]); put(b, o.Index) } // SighashAll implements BIP143 SIGHASH_ALL only, with caller-supplied scriptCode. // Outpoint hashes must be in wire byte order. This is not a transaction validator. func SighashAll(t Tx, index int, scriptCode []byte, amount int64) ([32]byte, error) { if index < 0 || index >= len(t.Inputs) || amount < 0 || amount > 2100000000000000 { return [32]byte{}, errors.New("invalid input or amount") } var p, s, o, b bytes.Buffer for _, in := range t.Inputs { outpoint(&p, in.Previous) put(&s, in.Sequence) } for _, v := range t.Outputs { if v.Value < 0 || v.Value > 2100000000000000 { return [32]byte{}, errors.New("invalid output") } put(&o, v.Value) compact(&o, uint64(len(v.Script))) o.Write(v.Script) } hp, hs, ho := Hash256(p.Bytes()), Hash256(s.Bytes()), Hash256(o.Bytes()) put(&b, t.Version) b.Write(hp[:]) b.Write(hs[:]) outpoint(&b, t.Inputs[index].Previous) compact(&b, uint64(len(scriptCode))) b.Write(scriptCode) put(&b, amount) put(&b, t.Inputs[index].Sequence) b.Write(ho[:]) put(&b, t.Locktime) put(&b, uint32(1)) return Hash256(b.Bytes()), nil }