github.com/decred/dcrlnd@v0.7.6/shachain/shahash.go (about)

     1  // Copyright (c) 2013-2016 The btcsuite developers
     2  // Copyright (c) 2015-2016 The Decred developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package shachain
     7  
     8  import (
     9  	"crypto/sha256"
    10  	"encoding/hex"
    11  	"fmt"
    12  )
    13  
    14  const (
    15  	// HashSize of array used to store hashes.  See ShaHash.
    16  	HashSize = sha256.Size
    17  
    18  	// MaxHashStringSize is the maximum length of a ShaHash hash string.
    19  	MaxHashStringSize = HashSize * 2
    20  )
    21  
    22  // ErrHashStrSize describes an error that indicates the caller specified a hash
    23  // string that has too many characters.
    24  var ErrHashStrSize = fmt.Errorf("max hash string length is %v bytes",
    25  	MaxHashStringSize)
    26  
    27  // ShaHash represents a sha256 hash that is used when working with shachains.
    28  type ShaHash [HashSize]byte
    29  
    30  // String returns the ShaHash as a hexadecimal string.
    31  func (hash ShaHash) String() string {
    32  	return hex.EncodeToString(hash[:])
    33  }
    34  
    35  // NewHash returns a new ShaHash from a byte slice.  An error is returned if
    36  // the number of bytes passed in is not HashSize.
    37  func NewHash(newHash []byte) (*ShaHash, error) {
    38  	nhlen := len(newHash)
    39  	if nhlen != HashSize {
    40  		return nil, fmt.Errorf("invalid hash length of %v, want %v", nhlen,
    41  			HashSize)
    42  	}
    43  
    44  	var hash ShaHash
    45  	copy(hash[:], newHash)
    46  	return &hash, nil
    47  }
    48  
    49  // NewHashFromStr creates a ShaHash from a hexadeimal hash string.  Unlike most
    50  // hashes used in cryptocurrencies, this function does not perform any byte
    51  // reversals.
    52  func NewHashFromStr(hash string) (*ShaHash, error) {
    53  	// Return an error if hash string is too long.
    54  	if len(hash) > MaxHashStringSize {
    55  		return nil, ErrHashStrSize
    56  	}
    57  
    58  	// Hex decoder expects the hash to be a multiple of two.
    59  	if len(hash)%2 != 0 {
    60  		hash = "0" + hash
    61  	}
    62  
    63  	// Convert string hash to bytes.
    64  	buf, err := hex.DecodeString(hash)
    65  	if err != nil {
    66  		return nil, err
    67  	}
    68  
    69  	return NewHash(buf)
    70  }