github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/crypto/ed25519/chainkd/serialize.go (about)

     1  package chainkd
     2  
     3  import (
     4  	"encoding/hex"
     5  	"errors"
     6  )
     7  
     8  const (
     9  	extendedPublicKeySize  = 64
    10  	extendedPrivateKeySize = 64
    11  )
    12  
    13  var (
    14  	ErrBadKeyLen = errors.New("bad key length")
    15  	ErrBadKeyStr = errors.New("bad key string")
    16  )
    17  
    18  func (xpub XPub) MarshalText() ([]byte, error) {
    19  	hexBytes := make([]byte, hex.EncodedLen(len(xpub.Bytes())))
    20  	hex.Encode(hexBytes, xpub.Bytes())
    21  	return hexBytes, nil
    22  }
    23  
    24  func (xpub XPub) Bytes() []byte {
    25  	return xpub[:]
    26  }
    27  
    28  func (xprv XPrv) MarshalText() ([]byte, error) {
    29  	hexBytes := make([]byte, hex.EncodedLen(len(xprv.Bytes())))
    30  	hex.Encode(hexBytes, xprv.Bytes())
    31  	return hexBytes, nil
    32  }
    33  
    34  func (xprv XPrv) Bytes() []byte {
    35  	return xprv[:]
    36  }
    37  
    38  func (xpub *XPub) UnmarshalText(inp []byte) error {
    39  	if len(inp) != 2*extendedPublicKeySize {
    40  		return ErrBadKeyStr
    41  	}
    42  	_, err := hex.Decode(xpub[:], inp)
    43  	return err
    44  }
    45  
    46  func (xpub XPub) String() string {
    47  	return hex.EncodeToString(xpub.Bytes())
    48  }
    49  
    50  func (xprv *XPrv) UnmarshalText(inp []byte) error {
    51  	if len(inp) != 2*extendedPrivateKeySize {
    52  		return ErrBadKeyStr
    53  	}
    54  	_, err := hex.Decode(xprv[:], inp)
    55  	return err
    56  }
    57  
    58  func (xprv XPrv) String() string {
    59  	return hex.EncodeToString(xprv.Bytes())
    60  }