github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/api/program.go (about)

     1  package api
     2  
     3  import (
     4  	"context"
     5  	"encoding/hex"
     6  	"fmt"
     7  
     8  	"github.com/bytom/bytom/consensus/segwit"
     9  	"github.com/bytom/bytom/protocol/vm"
    10  )
    11  
    12  // DecodeProgResp is response for decode program
    13  type DecodeProgResp struct {
    14  	Instructions string `json:"instructions"`
    15  }
    16  
    17  func (a *API) decodeProgram(ctx context.Context, ins struct {
    18  	Program string `json:"program"`
    19  }) Response {
    20  	prog, err := hex.DecodeString(ins.Program)
    21  	if err != nil {
    22  		return NewErrorResponse(err)
    23  	}
    24  
    25  	// if program is P2PKH or P2SH script, convert it into actual executed program
    26  	if segwit.IsP2WPKHScript(prog) {
    27  		if witnessProg, err := segwit.ConvertP2PKHSigProgram(prog); err == nil {
    28  			prog = witnessProg
    29  		}
    30  	} else if segwit.IsP2WSHScript(prog) {
    31  		if witnessProg, err := segwit.ConvertP2SHProgram(prog); err == nil {
    32  			prog = witnessProg
    33  		}
    34  	}
    35  
    36  	insts, err := vm.ParseProgram(prog)
    37  	if err != nil {
    38  		return NewErrorResponse(err)
    39  	}
    40  
    41  	var result string
    42  	for _, inst := range insts {
    43  		result += fmt.Sprintf("%s %s\n", inst.Op, hex.EncodeToString(inst.Data))
    44  	}
    45  	return NewSuccessResponse(DecodeProgResp{Instructions: result})
    46  }