-
Notifications
You must be signed in to change notification settings - Fork 1
/
tron.go
82 lines (69 loc) · 2.03 KB
/
tron.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
78
79
80
81
82
package blockchainkeys
import (
"crypto/ecdsa"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/mr-tron/base58"
)
func (t *TronNetwork) GenerateKeyPair() (privateKey string, publicKey string, address string, err error) {
// Generation privateKey
private, err := crypto.GenerateKey()
if err != nil {
fmt.Printf("Error generation privateKey: %v", err)
return "", "", "", err
}
// Get publicKey from privateKey
public := private.Public()
// PublicKey to ECDSA format
publicKeyECDSA, ok := public.(*ecdsa.PublicKey)
if !ok {
fmt.Println("Error format publicKey to ECDSA")
return "", "", "", err
}
// Get Address from PublicKey
addrs := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
addrs = "41" + addrs[2:]
addb, _ := hex.DecodeString(addrs)
hash1 := s256(s256(addb))
secret := hash1[:4]
for _, v := range secret {
addb = append(addb, v)
}
privateKey = hexutil.Encode(crypto.FromECDSA(private))
publicKey = hexutil.Encode(crypto.FromECDSAPub(publicKeyECDSA))
address = base58.Encode(addb)
return privateKey, publicKey, address, nil
}
func (t *TronNetwork) GetPublicKeyAndAddressByPrivateKey(privateKey string) (publicKey string, address string, err error) {
pk, err := crypto.HexToECDSA(privateKey)
if err != nil {
return "", "", err
}
pb := pk.Public()
publicKeyECDSA, ok := pb.(*ecdsa.PublicKey)
if !ok {
return "", "", fmt.Errorf("error casting public key to ECDSA")
}
publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
publicKeyHex := hexutil.Encode(publicKeyBytes)[4:]
addrs := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
addrs = "41" + addrs[2:]
addb, _ := hex.DecodeString(addrs)
hash1 := s256(s256(addb))
secret := hash1[:4]
for _, v := range secret {
addb = append(addb, v)
}
publicKey = hexutil.Encode(crypto.FromECDSAPub(publicKeyECDSA))
address = base58.Encode(addb)
return publicKeyHex, address, nil
}
func s256(s []byte) []byte {
h := sha256.New()
h.Write(s)
bs := h.Sum(nil)
return bs
}