forked from gagliardetto/solana-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeys.go
340 lines (284 loc) · 7.63 KB
/
keys.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package solana
import (
"crypto"
"crypto/ed25519"
crypto_rand "crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io/ioutil"
"math"
"filippo.io/edwards25519"
"github.com/mr-tron/base58"
)
type PrivateKey []byte
func MustPrivateKeyFromBase58(in string) PrivateKey {
out, err := PrivateKeyFromBase58(in)
if err != nil {
panic(err)
}
return out
}
func PrivateKeyFromBase58(privkey string) (PrivateKey, error) {
res, err := base58.Decode(privkey)
if err != nil {
return nil, err
}
return res, nil
}
func PrivateKeyFromSolanaKeygenFile(file string) (PrivateKey, error) {
content, err := ioutil.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("read keygen file: %w", err)
}
var values []byte
err = json.Unmarshal(content, &values)
if err != nil {
return nil, fmt.Errorf("decode keygen file: %w", err)
}
return PrivateKey([]byte(values)), nil
}
func (k PrivateKey) String() string {
return base58.Encode(k)
}
func NewRandomPrivateKey() (PrivateKey, error) {
pub, priv, err := ed25519.GenerateKey(crypto_rand.Reader)
if err != nil {
return nil, err
}
var publicKey PublicKey
copy(publicKey[:], pub)
return PrivateKey(priv), nil
}
func (k PrivateKey) Sign(payload []byte) (Signature, error) {
p := ed25519.PrivateKey(k)
signData, err := p.Sign(crypto_rand.Reader, payload, crypto.Hash(0))
if err != nil {
return Signature{}, err
}
var signature Signature
copy(signature[:], signData)
return signature, err
}
func (k PrivateKey) PublicKey() PublicKey {
p := ed25519.PrivateKey(k)
pub := p.Public().(ed25519.PublicKey)
var publicKey PublicKey
copy(publicKey[:], pub)
return publicKey
}
type PublicKey [PublicKeyLength]byte
func PublicKeyFromBytes(in []byte) (out PublicKey) {
byteCount := len(in)
if byteCount == 0 {
return
}
max := PublicKeyLength
if byteCount < max {
max = byteCount
}
copy(out[:], in[0:max])
return
}
func MustPublicKeyFromBase58(in string) PublicKey {
out, err := PublicKeyFromBase58(in)
if err != nil {
panic(err)
}
return out
}
func PublicKeyFromBase58(in string) (out PublicKey, err error) {
val, err := base58.Decode(in)
if err != nil {
return out, fmt.Errorf("decode: %w", err)
}
if len(val) != PublicKeyLength {
return out, fmt.Errorf("invalid length, expected %v, got %d", PublicKeyLength, len(val))
}
copy(out[:], val)
return
}
func (p PublicKey) MarshalText() ([]byte, error) {
return []byte(base58.Encode(p[:])), nil
}
func (p *PublicKey) UnmarshalText(data []byte) (err error) {
*p, err = PublicKeyFromBase58(string(data))
if err != nil {
return fmt.Errorf("invalid public key %q: %w", data, err)
}
return
}
func (p PublicKey) MarshalJSON() ([]byte, error) {
return json.Marshal(base58.Encode(p[:]))
}
func (p *PublicKey) UnmarshalJSON(data []byte) (err error) {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
*p, err = PublicKeyFromBase58(s)
if err != nil {
return fmt.Errorf("invalid public key %q: %w", s, err)
}
return
}
func (p PublicKey) Equals(pb PublicKey) bool {
return p == pb
}
// ToPointer returns a pointer to the pubkey.
func (p PublicKey) ToPointer() *PublicKey {
return &p
}
func (p PublicKey) Bytes() []byte {
return []byte(p[:])
}
var zeroPublicKey = PublicKey{}
// IsZero returns whether the public key is zero.
// NOTE: the System Program public key is also zero.
func (p PublicKey) IsZero() bool {
return p == zeroPublicKey
}
func (p PublicKey) String() string {
return base58.Encode(p[:])
}
type PublicKeySlice []PublicKey
// UniqueAppend appends the provided pubkey only if it is not
// already present in the slice.
// Returns true when the provided pubkey wasn't already present.
func (slice *PublicKeySlice) UniqueAppend(pubkey PublicKey) bool {
if !slice.Has(pubkey) {
slice.Append(pubkey)
return true
}
return false
}
func (slice *PublicKeySlice) Append(pubkey PublicKey) {
*slice = append(*slice, pubkey)
}
func (slice PublicKeySlice) Has(pubkey PublicKey) bool {
for _, key := range slice {
if key.Equals(pubkey) {
return true
}
}
return false
}
var nativeProgramIDs = PublicKeySlice{
BPFLoaderProgramID,
BPFLoaderDeprecatedProgramID,
FeatureProgramID,
ConfigProgramID,
StakeProgramID,
VoteProgramID,
Secp256k1ProgramID,
SystemProgramID,
SysVarClockPubkey,
SysVarEpochSchedulePubkey,
SysVarFeesPubkey,
SysVarInstructionsPubkey,
SysVarRecentBlockHashesPubkey,
SysVarRentPubkey,
SysVarRewardsPubkey,
SysVarSlotHashesPubkey,
SysVarSlotHistoryPubkey,
SysVarStakeHistoryPubkey,
}
// https://github.com/solana-labs/solana/blob/216983c50e0a618facc39aa07472ba6d23f1b33a/sdk/program/src/pubkey.rs#L372
func isNativeProgramID(key PublicKey) bool {
return nativeProgramIDs.Has(key)
}
const (
/// Number of bytes in a pubkey.
PublicKeyLength = 32
// Maximum length of derived pubkey seed.
MaxSeedLength = 32
// Maximum number of seeds.
MaxSeeds = 16
// // Maximum string length of a base58 encoded pubkey.
// MaxBase58Length = 44
)
// Ported from https://github.com/solana-labs/solana/blob/216983c50e0a618facc39aa07472ba6d23f1b33a/sdk/program/src/pubkey.rs#L159
func CreateWithSeed(base PublicKey, seed string, owner PublicKey) (PublicKey, error) {
if len(seed) > MaxSeedLength {
return PublicKey{}, errors.New("Max seed length exceeded")
}
// let owner = owner.as_ref();
// if owner.len() >= PDA_MARKER.len() {
// let slice = &owner[owner.len() - PDA_MARKER.len()..];
// if slice == PDA_MARKER {
// return Err(PubkeyError::IllegalOwner);
// }
// }
b := make([]byte, 0, 64+len(seed))
b = append(b, base[:]...)
b = append(b, seed[:]...)
b = append(b, owner[:]...)
hash := sha256.Sum256(b)
return PublicKeyFromBytes(hash[:]), nil
}
const PDA_MARKER = "ProgramDerivedAddress"
// Create a program address.
// Ported from https://github.com/solana-labs/solana/blob/216983c50e0a618facc39aa07472ba6d23f1b33a/sdk/program/src/pubkey.rs#L204
func CreateProgramAddress(seeds [][]byte, programID PublicKey) (PublicKey, error) {
if len(seeds) > MaxSeeds {
return PublicKey{}, errors.New("Max seed length exceeded")
}
for _, seed := range seeds {
if len(seed) > MaxSeedLength {
return PublicKey{}, errors.New("Max seed length exceeded")
}
}
if isNativeProgramID(programID) {
return PublicKey{}, fmt.Errorf("illegal owner: %s is a native program", programID)
}
buf := []byte{}
for _, seed := range seeds {
buf = append(buf, seed...)
}
buf = append(buf, programID[:]...)
buf = append(buf, []byte(PDA_MARKER)...)
hash := sha256.Sum256(buf)
_, err := new(edwards25519.Point).SetBytes(hash[:])
isOnCurve := err == nil
if isOnCurve {
return PublicKey{}, errors.New("invalid seeds; address must fall off the curve")
}
return PublicKeyFromBytes(hash[:]), nil
}
// Find a valid program address and its corresponding bump seed.
func FindProgramAddress(seed [][]byte, programID PublicKey) (PublicKey, uint8, error) {
var address PublicKey
var err error
bumpSeed := uint8(math.MaxUint8)
for bumpSeed != 0 {
address, err = CreateProgramAddress(append(seed, []byte{byte(bumpSeed)}), programID)
if err == nil {
return address, bumpSeed, nil
}
bumpSeed--
}
return PublicKey{}, bumpSeed, errors.New("unable to find a valid program address")
}
func FindAssociatedTokenAddress(
walletAddress PublicKey,
splTokenMintAddress PublicKey,
) (PublicKey, uint8, error) {
return findAssociatedTokenAddressAndBumpSeed(
walletAddress,
splTokenMintAddress,
SPLAssociatedTokenAccountProgramID,
)
}
func findAssociatedTokenAddressAndBumpSeed(
walletAddress PublicKey,
splTokenMintAddress PublicKey,
programID PublicKey,
) (PublicKey, uint8, error) {
return FindProgramAddress([][]byte{
walletAddress[:],
SPLTokenProgramID[:],
splTokenMintAddress[:],
},
programID,
)
}