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

     1  package utxo
     2  
     3  import (
     4  	"encoding/binary"
     5  	"fmt"
     6  
     7  	"github.com/piotrnar/gocoin/lib/btc"
     8  )
     9  
    10  const (
    11  	UtxoIdxLen = 8 // Increase this value (maximum 32) for better security at a cost of memory usage
    12  )
    13  
    14  type UtxoKeyType [UtxoIdxLen]byte
    15  
    16  type AllUnspentTx []*OneUnspentTx
    17  
    18  // OneUnspentTx is returned by GetUnspentFromPkScr.
    19  type OneUnspentTx struct {
    20  	btc.TxPrevOut
    21  	Value   uint64
    22  	MinedAt uint32
    23  	*btc.BtcAddr
    24  	destString string
    25  	Coinbase   bool
    26  	Message    []byte
    27  }
    28  
    29  func (x AllUnspentTx) Len() int {
    30  	return len(x)
    31  }
    32  
    33  func (x AllUnspentTx) Less(i, j int) bool {
    34  	if x[i].MinedAt == x[j].MinedAt {
    35  		if x[i].TxPrevOut.Hash == x[j].TxPrevOut.Hash {
    36  			return x[i].TxPrevOut.Vout < x[j].TxPrevOut.Vout
    37  		}
    38  		return binary.LittleEndian.Uint64(x[i].TxPrevOut.Hash[24:32]) <
    39  			binary.LittleEndian.Uint64(x[j].TxPrevOut.Hash[24:32])
    40  	}
    41  	return x[i].MinedAt < x[j].MinedAt
    42  }
    43  
    44  func (x AllUnspentTx) Swap(i, j int) {
    45  	x[i], x[j] = x[j], x[i]
    46  }
    47  
    48  func (ou *OneUnspentTx) String() (s string) {
    49  	s = fmt.Sprintf("%15s BTC %s", btc.UintToBtc(ou.Value), ou.TxPrevOut.String())
    50  	if ou.BtcAddr != nil {
    51  		s += " " + ou.DestAddr() + ou.BtcAddr.Label()
    52  	}
    53  	if ou.MinedAt != 0 {
    54  		s += fmt.Sprint(" ", ou.MinedAt)
    55  	}
    56  	if ou.Coinbase {
    57  		s += fmt.Sprint(" Coinbase")
    58  	}
    59  	if ou.Message != nil {
    60  		s += "  "
    61  		for _, c := range ou.Message {
    62  			if c < ' ' || c > 127 {
    63  				s += fmt.Sprintf("\\x%02x", c)
    64  			} else {
    65  				s += string(c)
    66  			}
    67  		}
    68  	}
    69  	return
    70  }
    71  
    72  func (ou *OneUnspentTx) FixDestString() {
    73  	ou.destString = ou.BtcAddr.String()
    74  }
    75  
    76  func (ou *OneUnspentTx) UnspentTextLine() (s string) {
    77  	s = fmt.Sprintf("%s # %.8f BTC @ %s%s, block %d", ou.TxPrevOut.String(),
    78  		float64(ou.Value)/1e8, ou.DestAddr(), ou.BtcAddr.Label(), ou.MinedAt)
    79  	return
    80  }
    81  
    82  func (ou *OneUnspentTx) DestAddr() string {
    83  	if ou.destString == "" {
    84  		return ou.BtcAddr.String()
    85  	}
    86  	return ou.destString
    87  }