github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/topicsdb/key.go (about)

     1  package topicsdb
     2  
     3  import (
     4  	"github.com/unicornultrafoundation/go-helios/common/bigendian"
     5  	"github.com/unicornultrafoundation/go-u2u/common"
     6  )
     7  
     8  const (
     9  	uint8Size  = 1
    10  	uint64Size = 8
    11  	hashSize   = common.HashLength
    12  
    13  	logrecKeySize = uint64Size + hashSize + uint64Size
    14  	topicKeySize  = hashSize + uint8Size + logrecKeySize
    15  	otherKeySize  = logrecKeySize + uint8Size
    16  )
    17  
    18  type (
    19  	// ID of log record
    20  	ID [logrecKeySize]byte
    21  )
    22  
    23  func NewID(block uint64, tx common.Hash, logIndex uint) (id ID) {
    24  	copy(id[:], uintToBytes(block))
    25  	copy(id[uint64Size:], tx.Bytes())
    26  	copy(id[uint64Size+hashSize:], uintToBytes(uint64(logIndex)))
    27  	return
    28  }
    29  
    30  func (id *ID) Bytes() []byte {
    31  	return (*id)[:]
    32  }
    33  
    34  func (id *ID) BlockNumber() uint64 {
    35  	return bytesToUint((*id)[:uint64Size])
    36  }
    37  
    38  func (id *ID) TxHash() (tx common.Hash) {
    39  	copy(tx[:], (*id)[uint64Size:uint64Size+hashSize])
    40  	return
    41  }
    42  
    43  func (id *ID) Index() uint {
    44  	return uint(bytesToUint(
    45  		(*id)[uint64Size+hashSize : uint64Size+hashSize+uint64Size]))
    46  }
    47  
    48  func topicKey(topic common.Hash, pos uint8, logrec ID) []byte {
    49  	key := make([]byte, 0, topicKeySize)
    50  
    51  	key = append(key, topic.Bytes()...)
    52  	key = append(key, posToBytes(pos)...)
    53  	key = append(key, logrec.Bytes()...)
    54  
    55  	return key
    56  }
    57  
    58  func posToBytes(pos uint8) []byte {
    59  	return []byte{pos}
    60  }
    61  
    62  func bytesToPos(b []byte) uint8 {
    63  	return uint8(b[0])
    64  }
    65  
    66  func uintToBytes(n uint64) []byte {
    67  	return bigendian.Uint64ToBytes(n)
    68  }
    69  
    70  func bytesToUint(b []byte) uint64 {
    71  	return bigendian.BytesToUint64(b)
    72  }
    73  
    74  func extractLogrecID(key []byte) (id ID) {
    75  	switch len(key) {
    76  	case topicKeySize:
    77  		copy(id[:], key[hashSize+uint8Size:])
    78  		return
    79  	default:
    80  		panic("wrong key type")
    81  	}
    82  }