-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.go
44 lines (38 loc) · 863 Bytes
/
util.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
package common
import (
"encoding/hex"
"github.com/libp2p/go-libp2p-crypto"
"encoding/binary"
)
func Hex(b []byte) []byte {
enc := make([]byte, len(b)*2+2)
copy(enc, "0x")
hex.Encode(enc[2:], b)
return enc
}
// Generate address by public key
func GenAddrByPubkey(key crypto.PubKey) (Address, error) {
var addr Address
pubkey, err := key.Bytes()
if err != nil {
return addr, err
}
pubkey = pubkey[1:]
h := Sha256(pubkey)
hash := h[len(h)-AddressLength:]
addr = HashToAddr(Sha256(hash))
return addr, nil
}
// Generate address by private key
func GenAddrByPrivkey(key crypto.PrivKey) (Address, error) {
pubkey := key.GetPublic()
return GenAddrByPubkey(pubkey)
}
func Uint2Bytes(v uint64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, v)
return b[:]
}
func Bytes2Uint(d []byte) uint64 {
return binary.BigEndian.Uint64(d)
}