forked from blocto/solana-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
/
public_key.go
104 lines (86 loc) · 2.47 KB
/
public_key.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package common
import (
"crypto/sha256"
"encoding/json"
"errors"
"filippo.io/edwards25519"
"github.com/mr-tron/base58"
)
const (
PublicKeyLength = 32
MaxSeedLength = 32
MaxSeed = 16
)
type PublicKey [PublicKeyLength]byte
func (p PublicKey) String() string {
return p.ToBase58()
}
func PublicKeyFromString(s string) PublicKey {
d, _ := base58.Decode(s)
return PublicKeyFromBytes(d)
}
func PublicKeyFromBytes(b []byte) PublicKey {
var pubkey PublicKey
if len(b) > PublicKeyLength {
b = b[:PublicKeyLength]
}
copy(pubkey[PublicKeyLength-len(b):], b)
return pubkey
}
func CreateProgramAddress(seeds [][]byte, programId PublicKey) (PublicKey, error) {
if len(seeds) > MaxSeed {
return PublicKey{}, errors.New("length of the seed is too long for address generation")
}
buf := []byte{}
for _, seed := range seeds {
if len(seed) > MaxSeedLength {
return PublicKey{}, errors.New("length of the seed is too long for address generation")
}
buf = append(buf, seed...)
}
buf = append(buf, programId[:]...)
buf = append(buf, []byte("ProgramDerivedAddress")...)
h := sha256.Sum256(buf)
_, err := new(edwards25519.Point).SetBytes(h[:])
if err == nil {
return PublicKey{}, errors.New("invalid seeds, address must fall off the curve")
}
return PublicKeyFromBytes(h[:]), nil
}
func (p PublicKey) ToBase58() string {
return base58.Encode(p[:])
}
func (p PublicKey) Bytes() []byte {
return p[:]
}
func (p *PublicKey) MarshalJSON() ([]byte, error) {
return json.Marshal(p.ToBase58())
}
func CreateWithSeed(from PublicKey, seed string, programID PublicKey) PublicKey {
b := make([]byte, 0, 64+len(seed))
b = append(b, from[:]...)
b = append(b, seed[:]...)
b = append(b, programID[:]...)
hash := sha256.Sum256(b)
return PublicKeyFromBytes(hash[:])
}
func FindAssociatedTokenAddress(walletAddress, tokenMintAddress PublicKey) (PublicKey, int, error) {
seeds := [][]byte{}
seeds = append(seeds, walletAddress.Bytes())
seeds = append(seeds, TokenProgramID.Bytes())
seeds = append(seeds, tokenMintAddress.Bytes())
return FindProgramAddress(seeds, SPLAssociatedTokenAccountProgramID)
}
func FindProgramAddress(seed [][]byte, programID PublicKey) (PublicKey, int, error) {
var pubKey PublicKey
var err error
nonce := 0xff
for nonce != 0x0 {
pubKey, err = CreateProgramAddress(append(seed, []byte{byte(nonce)}), programID)
if err == nil {
return pubKey, nonce, nil
}
nonce--
}
return PublicKey{}, nonce, errors.New("unable to find a viable program address")
}