github.com/piotrnar/gocoin@v0.0.0-20240512203912-faa0448c5e96/lib/btc/uint256.go (about)

     1  package btc
     2  
     3  import (
     4  	"fmt"
     5  	"bytes"
     6  	"math/big"
     7  	"encoding/hex"
     8  )
     9  
    10  const Uint256IdxLen = 8  // The bigger it is, the more memory is needed, but lower chance of a collision
    11  
    12  type Uint256 struct {
    13  	Hash [32]byte
    14  }
    15  
    16  func NewUint256(h []byte) (res *Uint256) {
    17  	res = new(Uint256)
    18  	copy(res.Hash[:], h)
    19  	return
    20  }
    21  
    22  // Get from MSB hexstring
    23  func NewUint256FromString(s string) (res *Uint256) {
    24  	d, e := hex.DecodeString(s)
    25  	if e != nil {
    26  		//println("NewUint256FromString", s, e.Error())
    27  		return
    28  	}
    29  	if len(d)!=32 {
    30  		//println("NewUint256FromString", s, "not 32 bytes long")
    31  		return
    32  	}
    33  	res = new(Uint256)
    34  	for i := 0; i<32; i++ {
    35  		res.Hash[31-i] = d[i]
    36  	}
    37  	return
    38  }
    39  
    40  
    41  func NewSha2Hash(data []byte) (res *Uint256) {
    42  	res = new(Uint256)
    43  	ShaHash(data, res.Hash[:])
    44  	return
    45  }
    46  
    47  
    48  func (u *Uint256) Bytes() []byte {
    49  	return u.Hash[:]
    50  }
    51  
    52  
    53  func (u *Uint256) String() (s string) {
    54  	for i := 0; i<32; i++ {
    55  		s+= fmt.Sprintf("%02x", u.Hash[31-i])
    56  	}
    57  	return
    58  }
    59  
    60  func (u *Uint256) Equal(o *Uint256) bool {
    61  	return bytes.Equal(u.Hash[:], o.Hash[:])
    62  }
    63  
    64  func (u *Uint256) Calc(data []byte) {
    65  	ShaHash(data, u.Hash[:])
    66  }
    67  
    68  
    69  func BIdx(hash []byte) (o [Uint256IdxLen]byte) {
    70  	copy(o[:], hash[:Uint256IdxLen])
    71  	return
    72  }
    73  
    74  func (u *Uint256) BIdx() (o [Uint256IdxLen]byte) {
    75  	o = BIdx(u.Hash[:])
    76  	return
    77  }
    78  
    79  func (u *Uint256) BigInt() *big.Int {
    80  	var buf [32]byte
    81  	for i := range buf {
    82  		buf[i] = u.Hash[31-i]
    83  	}
    84  	return new(big.Int).SetBytes(buf[:])
    85  }