This repository has been archived by the owner on Nov 7, 2019. It is now read-only.
/
helpers.go
77 lines (60 loc) · 1.61 KB
/
helpers.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
// Copyright 2019 Wireline, Inc.
//
package registry
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"github.com/tendermint/tendermint/crypto"
"golang.org/x/crypto/ripemd160"
)
// GenRecordHash generates a transaction hash.
func GenRecordHash(r Record) []byte {
first := sha256.New()
bytes, err := json.MarshalIndent(r, "", " ")
if err != nil {
panic("Record marshal error.")
}
first.Write(bytes)
firstHash := first.Sum(nil)
second := sha256.New()
second.Write(firstHash)
secondHash := second.Sum(nil)
return secondHash
}
// GetAddressFromPubKey gets an address from the public key.
func GetAddressFromPubKey(pubKey crypto.PubKey) string {
hasherSHA256 := sha256.New()
hasherSHA256.Write(pubKey.Bytes())
sha := hasherSHA256.Sum(nil)
hasherRIPEMD160 := ripemd160.New()
hasherRIPEMD160.Write(sha)
ripemd := hasherRIPEMD160.Sum(nil)
return BytesToHex(ripemd)
}
// BytesToBase64 encodes a byte array as a base64 string.
func BytesToBase64(bytes []byte) string {
return base64.StdEncoding.EncodeToString(bytes)
}
// BytesFromBase64 decodes a byte array from a base64 string.
func BytesFromBase64(str string) []byte {
bytes, err := base64.StdEncoding.DecodeString(str)
if err != nil {
panic("Error decoding string to bytes.")
}
return bytes
}
// BytesToHex encodes a byte array as a hex string.
func BytesToHex(bytes []byte) string {
return hex.EncodeToString(bytes)
}
// BytesFromHex decodes a byte array from a hex string.
func BytesFromHex(str string) []byte {
bytes, err := hex.DecodeString(str)
if err != nil {
panic("Error decoding hex to bytes.")
}
return bytes
}