github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/toolbar/common/address.go (about)

     1  package common
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/bytom/bytom/common"
     7  	"github.com/bytom/bytom/consensus"
     8  	"github.com/bytom/bytom/consensus/segwit"
     9  	"github.com/bytom/bytom/protocol/vm/vmutil"
    10  )
    11  
    12  func GetAddressFromControlProgram(prog []byte) string {
    13  	if segwit.IsP2WPKHScript(prog) {
    14  		if pubHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
    15  			return buildP2PKHAddress(pubHash)
    16  		}
    17  	} else if segwit.IsP2WSHScript(prog) {
    18  		if scriptHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
    19  			return buildP2SHAddress(scriptHash)
    20  		}
    21  	}
    22  
    23  	return ""
    24  }
    25  
    26  func buildP2PKHAddress(pubHash []byte) string {
    27  	address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
    28  	if err != nil {
    29  		return ""
    30  	}
    31  
    32  	return address.EncodeAddress()
    33  }
    34  
    35  func buildP2SHAddress(scriptHash []byte) string {
    36  	address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
    37  	if err != nil {
    38  		return ""
    39  	}
    40  
    41  	return address.EncodeAddress()
    42  }
    43  
    44  func GetControlProgramFromAddress(address string) ([]byte, error) {
    45  	decodeaddress, err := common.DecodeAddress(address, &consensus.ActiveNetParams)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	redeemContract := decodeaddress.ScriptAddress()
    51  	program := []byte{}
    52  	switch decodeaddress.(type) {
    53  	case *common.AddressWitnessPubKeyHash:
    54  		program, err = vmutil.P2WPKHProgram(redeemContract)
    55  	case *common.AddressWitnessScriptHash:
    56  		program, err = vmutil.P2WSHProgram(redeemContract)
    57  	default:
    58  		return nil, errors.New("Invalid address")
    59  	}
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	return program, nil
    64  }