-
Notifications
You must be signed in to change notification settings - Fork 0
/
sr25519.go
64 lines (51 loc) · 1.6 KB
/
sr25519.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
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: LGPL-3.0-only
package sr25519
import (
"crypto/rand"
"github.com/NirajBhattarai/klay-utils/crypto"
"github.com/centrifuge/go-substrate-rpc-client/signature"
"github.com/centrifuge/go-substrate-rpc-client/types"
"github.com/klaytn/klaytn/common/hexutil"
)
var _ crypto.Keypair = &Keypair{}
type Keypair struct {
keyringPair *signature.KeyringPair
}
func GenerateKeypair(network string) (*Keypair, error) {
data := make([]byte, 32)
_, err := rand.Read(data)
if err != nil {
return nil, err
}
return NewKeypairFromSeed("//"+hexutil.Encode(data), network)
}
func NewKeypairFromSeed(seed, network string) (*Keypair, error) {
kp, err := signature.KeyringPairFromSecret(seed, network)
return &Keypair{&kp}, err
}
func NewKeypairFromKRP(pair signature.KeyringPair) *Keypair {
return &Keypair{&pair}
}
// AsKeyringPair returns the underlying KeyringPair
func (kp *Keypair) AsKeyringPair() *signature.KeyringPair {
return kp.keyringPair
}
// Encode uses scale to encode underlying KeyringPair
func (kp *Keypair) Encode() []byte {
out, _ := types.EncodeToBytes(kp.keyringPair)
return out
}
// Decode initializes keypair by decoding input as a KeyringPair
func (kp *Keypair) Decode(in []byte) error {
kp.keyringPair = &signature.KeyringPair{}
return types.DecodeFromBytes(in, kp.keyringPair)
}
// Address returns the ss58 formated address
func (kp *Keypair) Address() string {
return kp.keyringPair.Address
}
// PublicKey returns the publickey encoded as a string
func (kp *Keypair) PublicKey() string {
return hexutil.Encode(kp.keyringPair.PublicKey)
}