github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/consensus/segwit/segwit.go (about) 1 package segwit 2 3 import ( 4 "errors" 5 6 "github.com/bytom/bytom/consensus" 7 "github.com/bytom/bytom/protocol/vm" 8 "github.com/bytom/bytom/protocol/vm/vmutil" 9 ) 10 11 func IsP2WScript(prog []byte) bool { 12 return IsP2WPKHScript(prog) || IsP2WSHScript(prog) || IsStraightforward(prog) 13 } 14 15 func IsStraightforward(prog []byte) bool { 16 insts, err := vm.ParseProgram(prog) 17 if err != nil { 18 return false 19 } 20 if len(insts) != 1 { 21 return false 22 } 23 return insts[0].Op == vm.OP_TRUE || insts[0].Op == vm.OP_FAIL 24 } 25 26 func IsP2WPKHScript(prog []byte) bool { 27 insts, err := vm.ParseProgram(prog) 28 if err != nil { 29 return false 30 } 31 if len(insts) != 2 { 32 return false 33 } 34 if insts[0].Op != vm.OP_0 { 35 return false 36 } 37 return insts[1].Op == vm.OP_DATA_20 && len(insts[1].Data) == consensus.PayToWitnessPubKeyHashDataSize 38 } 39 40 func IsP2WSHScript(prog []byte) bool { 41 insts, err := vm.ParseProgram(prog) 42 if err != nil { 43 return false 44 } 45 if len(insts) != 2 { 46 return false 47 } 48 if insts[0].Op != vm.OP_0 { 49 return false 50 } 51 return insts[1].Op == vm.OP_DATA_32 && len(insts[1].Data) == consensus.PayToWitnessScriptHashDataSize 52 } 53 54 func ConvertP2PKHSigProgram(prog []byte) ([]byte, error) { 55 insts, err := vm.ParseProgram(prog) 56 if err != nil { 57 return nil, err 58 } 59 if insts[0].Op == vm.OP_0 { 60 return vmutil.P2PKHSigProgram(insts[1].Data) 61 } 62 return nil, errors.New("unknow P2PKH version number") 63 } 64 65 func ConvertP2SHProgram(prog []byte) ([]byte, error) { 66 insts, err := vm.ParseProgram(prog) 67 if err != nil { 68 return nil, err 69 } 70 if insts[0].Op == vm.OP_0 { 71 return vmutil.P2SHProgram(insts[1].Data) 72 } 73 return nil, errors.New("unknow P2SHP version number") 74 } 75 76 func GetHashFromStandardProg(prog []byte) ([]byte, error) { 77 insts, err := vm.ParseProgram(prog) 78 if err != nil { 79 return nil, err 80 } 81 82 return insts[1].Data, nil 83 }