-
Notifications
You must be signed in to change notification settings - Fork 4
/
entry.go
52 lines (40 loc) · 1.06 KB
/
entry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package utxo
import (
"encoding/binary"
"fmt"
"github.com/btcsuite/btcd/chaincfg/chainhash"
)
var ErrKeySize = fmt.Errorf("wrong key length")
type Entry struct {
Address []byte
TxHash *chainhash.Hash
Value int64
}
func toPair(entry *Entry) (key, value []byte) {
addressLen := len(entry.Address)
key = make([]byte, addressLen+chainhash.HashSize)
copy(key[:addressLen], entry.Address[:])
copy(key[addressLen:], entry.TxHash.CloneBytes())
value = make([]byte, binary.MaxVarintLen64)
binary.LittleEndian.PutUint64(value[:], uint64(entry.Value))
return
}
func toEntry(key, value []byte) (*Entry, error) {
if len(key) < chainhash.HashSize {
return nil, ErrKeySize
}
addressLen := len(key) - chainhash.HashSize
address := make([]byte, addressLen)
copy(address, key[:addressLen])
hashBytes := make([]byte, chainhash.HashSize)
copy(hashBytes, key[addressLen:])
hash, err := chainhash.NewHash(hashBytes)
if err != nil {
return nil, err
}
return &Entry{
Address: address,
TxHash: hash,
Value: int64(binary.LittleEndian.Uint64(value[:])),
}, nil
}