package psbt import ( "bytes" "fmt" ) // FinalWitness returns the final scriptWitness of the first input that carries one. // // A local wallet finalises its own contract inputs, so the witness is the answer a caller // needs: it is applied to the unsigned transaction before the transaction is broadcast. func FinalWitness(raw []byte) ([][]byte, error) { if !bytes.HasPrefix(raw, magic) { return nil, ErrNotPSBT } reader := &cursor{raw: raw, at: len(magic)} // The global map is skipped: only input maps can carry a final witness. for { key, _, err := reader.record() if err != nil { return nil, err } if key == nil { break } } for { key, value, err := reader.record() if err != nil { return nil, err } if key == nil { // An input map ended without a final witness; try the next one. if !reader.more() { break } continue } if len(key) == 1 && key[0] == inputFinalWitness { return decodeWitness(value) } } return nil, fmt.Errorf("psbt: no final script witness") } // decodeWitness reads a BIP174 witness stack. func decodeWitness(value []byte) ([][]byte, error) { c := &witnessCursor{raw: value} count, err := c.compactSize() if err != nil { return nil, err } if count == 0 || count > 16 { return nil, fmt.Errorf("psbt: a %d-item witness", count) } items := make([][]byte, 0, count) for i := 0; i < count; i++ { item, err := c.bytes() if err != nil { return nil, err } items = append(items, item) } if c.at != len(value) { return nil, fmt.Errorf("psbt: %d trailing bytes after a witness", len(value)-c.at) } return items, nil } // witnessCursor reads a witness stack, separate from the PSBT map cursor. type witnessCursor struct { raw []byte at int } func (c *witnessCursor) u8() (byte, error) { if c.at >= len(c.raw) { return 0, fmt.Errorf("psbt: a witness ends inside a value") } b := c.raw[c.at] c.at++ return b, nil } func (c *witnessCursor) compactSize() (int, error) { first, err := c.u8() if err != nil { return 0, err } switch { case first < 0xfd: return int(first), nil case first == 0xfd: if c.at+2 > len(c.raw) { return 0, fmt.Errorf("psbt: a short witness length") } value := int(c.raw[c.at]) | int(c.raw[c.at+1])<<8 c.at += 2 return value, nil default: return 0, fmt.Errorf("psbt: a witness length past 0xfd is not a witness") } } func (c *witnessCursor) bytes() ([]byte, error) { length, err := c.compactSize() if err != nil { return nil, err } if c.at+length > len(c.raw) { return nil, fmt.Errorf("psbt: a witness item runs past the stack") } out := append([]byte(nil), c.raw[c.at:c.at+length]...) c.at += length return out, nil }