github.com/deso-protocol/core@v1.2.9/lib/base58.go (about)

     1  package lib
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"fmt"
     6  	"github.com/btcsuite/btcutil/base58"
     7  	"github.com/golang/glog"
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  func Base58CheckEncode(input []byte, isPrivate bool, params *DeSoParams) string {
    12  	prefix := params.Base58PrefixPublicKey
    13  	if isPrivate {
    14  		prefix = params.Base58PrefixPrivateKey
    15  	}
    16  	return Base58CheckEncodeWithPrefix(input, prefix)
    17  }
    18  
    19  func Base58CheckEncodeWithPrefix(input []byte, prefix [3]byte) string {
    20  	b := []byte{}
    21  	b = append(b, prefix[:]...)
    22  	b = append(b, input[:]...)
    23  	cksum := _checksum(b)
    24  	b = append(b, cksum[:]...)
    25  	return base58.Encode(b)
    26  }
    27  
    28  func MustBase58CheckDecode(input string) []byte {
    29  	if input == "" {
    30  		return nil
    31  	}
    32  	ret, _, err := Base58CheckDecode(input)
    33  	if err != nil {
    34  		glog.Fatal(err)
    35  	}
    36  	return ret
    37  }
    38  
    39  func Base58CheckDecode(input string) (_result []byte, _prefix []byte, _err error) {
    40  	return Base58CheckDecodePrefix(input, 3 /*prefixLen*/)
    41  }
    42  
    43  func Base58CheckDecodePrefix(input string, prefixLen int) (_result []byte, _prefix []byte, _err error) {
    44  	decoded := base58.Decode(input)
    45  	if len(decoded) < 5 {
    46  		return nil, nil, errors.Wrap(fmt.Errorf("CheckDecode: Invalid input format"), "")
    47  	}
    48  	var cksum [4]byte
    49  	copy(cksum[:], decoded[len(decoded)-4:])
    50  	if _checksum(decoded[:len(decoded)-4]) != cksum {
    51  		return nil, nil, errors.Wrap(fmt.Errorf("CheckDecode: Checksum does not match"), "")
    52  	}
    53  	prefix := decoded[:prefixLen]
    54  	payload := decoded[prefixLen : len(decoded)-4]
    55  	return payload, prefix, nil
    56  }
    57  
    58  func _checksum(input []byte) (cksum [4]byte) {
    59  	h := sha256.Sum256(input)
    60  	h2 := sha256.Sum256(h[:])
    61  	copy(cksum[:], h2[:4])
    62  	return
    63  }