github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/encoding/base58/base58.go (about)

     1  package base58
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  
     7  	"github.com/mr-tron/base58"
     8  	"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
     9  )
    10  
    11  // CheckDecode implements base58-encoded string decoding with a hash-based
    12  // checksum check.
    13  func CheckDecode(s string) (b []byte, err error) {
    14  	b, err = base58.Decode(s)
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  
    19  	if len(b) < 5 {
    20  		return nil, errors.New("invalid base-58 check string: missing checksum")
    21  	}
    22  
    23  	if !bytes.Equal(hash.Checksum(b[:len(b)-4]), b[len(b)-4:]) {
    24  		return nil, errors.New("invalid base-58 check string: invalid checksum")
    25  	}
    26  
    27  	// Strip the 4 byte long hash.
    28  	b = b[:len(b)-4]
    29  
    30  	return b, nil
    31  }
    32  
    33  // CheckEncode encodes the given byte slice into a base58 string with a hash-based
    34  // checksum appended to it.
    35  func CheckEncode(b []byte) string {
    36  	b = append(b, hash.Checksum(b)...)
    37  
    38  	return base58.Encode(b)
    39  }