forked from gagliardetto/solana-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys.go
677 lines (575 loc) · 16.2 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
// Copyright 2021 github.com/gagliardetto
// This file has been modified by github.com/gagliardetto
//
// Copyright 2020 dfuse Platform Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package solana
import (
"bytes"
"crypto"
"crypto/ed25519"
crypto_rand "crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io/ioutil"
"math"
"sort"
"filippo.io/edwards25519"
"github.com/mr-tron/base58"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
)
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
}
// PK is a convenience alias for PublicKey
type PK = PublicKey
func (p PublicKey) Verify(message []byte, signature Signature) bool {
pub := ed25519.PublicKey(p[:])
return ed25519.Verify(pub, message, signature[:])
}
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
}
// MPK is a convenience alias for MustPublicKeyFromBase58
func MPK(in string) PublicKey {
return MustPublicKeyFromBase58(in)
}
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) error {
return p.Set(string(data))
}
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
}
// MarshalBSON implements the bson.Marshaler interface.
func (p PublicKey) MarshalBSON() ([]byte, error) {
return bson.Marshal(p.String())
}
// UnmarshalBSON implements the bson.Unmarshaler interface.
func (p *PublicKey) UnmarshalBSON(data []byte) (err error) {
var s string
if err := bson.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 nil
}
// MarshalBSONValue implements the bson.ValueMarshaler interface.
func (p PublicKey) MarshalBSONValue() (bsontype.Type, []byte, error) {
return bson.MarshalValue(p.String())
}
// UnmarshalBSONValue implements the bson.ValueUnmarshaler interface.
func (p *PublicKey) UnmarshalBSONValue(t bsontype.Type, data []byte) (err error) {
var s string
if err := bson.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 nil
}
func (p PublicKey) Equals(pb PublicKey) bool {
return p == pb
}
// IsAnyOf checks if p is equals to any of the provided keys.
func (p PublicKey) IsAnyOf(keys ...PublicKey) bool {
for _, k := range keys {
if p.Equals(k) {
return true
}
}
return false
}
// ToPointer returns a pointer to the pubkey.
func (p PublicKey) ToPointer() *PublicKey {
return &p
}
func (p PublicKey) Bytes() []byte {
return []byte(p[:])
}
// Check if a `Pubkey` is on the ed25519 curve.
func (p PublicKey) IsOnCurve() bool {
return IsOnCurve(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) Set(s string) (err error) {
*p, err = PublicKeyFromBase58(s)
if err != nil {
return fmt.Errorf("invalid public key %s: %w", s, err)
}
return
}
func (p PublicKey) String() string {
return base58.Encode(p[:])
}
// Short returns a shortened pubkey string,
// only including the first n chars, ellipsis, and the last n characters.
// NOTE: this is ONLY for visual representation for humans,
// and cannot be used for anything else.
func (p PublicKey) Short(n int) string {
return formatShortPubkey(n, p)
}
func formatShortPubkey(n int, pubkey PublicKey) string {
str := pubkey.String()
if n > (len(str)/2)-1 {
n = (len(str) / 2) - 1
}
if n < 2 {
n = 2
}
return str[:n] + "..." + str[len(str)-n:]
}
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(pubkeys ...PublicKey) {
*slice = append(*slice, pubkeys...)
}
func (slice PublicKeySlice) Has(pubkey PublicKey) bool {
for _, key := range slice {
if key.Equals(pubkey) {
return true
}
}
return false
}
func (slice PublicKeySlice) Len() int {
return len(slice)
}
func (slice PublicKeySlice) Less(i, j int) bool {
return bytes.Compare(slice[i][:], slice[j][:]) < 0
}
func (slice PublicKeySlice) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Sort sorts the slice.
func (slice PublicKeySlice) Sort() {
sort.Sort(slice)
}
// Dedupe returns a new slice with all duplicate pubkeys removed.
func (slice PublicKeySlice) Dedupe() PublicKeySlice {
slice.Sort()
deduped := make(PublicKeySlice, 0)
for i := 0; i < len(slice); i++ {
if i == 0 || !slice[i].Equals(slice[i-1]) {
deduped = append(deduped, slice[i])
}
}
return deduped
}
// Contains returns true if the slice contains the provided pubkey.
func (slice PublicKeySlice) Contains(pubkey PublicKey) bool {
for _, key := range slice {
if key.Equals(pubkey) {
return true
}
}
return false
}
// ContainsAll returns true if all the provided pubkeys are present in the slice.
func (slice PublicKeySlice) ContainsAll(pubkeys PublicKeySlice) bool {
for _, pubkey := range pubkeys {
if !slice.Contains(pubkey) {
return false
}
}
return true
}
// ContainsAny returns true if any of the provided pubkeys are present in the slice.
func (slice PublicKeySlice) ContainsAny(pubkeys ...PublicKey) bool {
for _, pubkey := range pubkeys {
if slice.Contains(pubkey) {
return true
}
}
return false
}
func (slice PublicKeySlice) ToBase58() []string {
out := make([]string, len(slice))
for i, pubkey := range slice {
out[i] = pubkey.String()
}
return out
}
func (slice PublicKeySlice) ToBytes() [][]byte {
out := make([][]byte, len(slice))
for i, pubkey := range slice {
out[i] = pubkey.Bytes()
}
return out
}
func (slice PublicKeySlice) ToPointers() []*PublicKey {
out := make([]*PublicKey, len(slice))
for i, pubkey := range slice {
out[i] = pubkey.ToPointer()
}
return out
}
// Removed returns the elements that are present in `a` but not in `b`.
func (a PublicKeySlice) Removed(b PublicKeySlice) PublicKeySlice {
var diff PublicKeySlice
for _, pubkey := range a {
if !b.Contains(pubkey) {
diff = append(diff, pubkey)
}
}
return diff.Dedupe()
}
// Added returns the elements that are present in `b` but not in `a`.
func (a PublicKeySlice) Added(b PublicKeySlice) PublicKeySlice {
return b.Removed(a)
}
// Intersect returns the intersection of two PublicKeySlices, i.e. the elements
// that are in both PublicKeySlices.
// The returned PublicKeySlice is sorted and deduped.
func (prev PublicKeySlice) Intersect(next PublicKeySlice) PublicKeySlice {
var intersect PublicKeySlice
for _, pubkey := range prev {
if next.Contains(pubkey) {
intersect = append(intersect, pubkey)
}
}
return intersect.Dedupe()
}
// Equals returns true if the two PublicKeySlices are equal (same order of same keys).
func (slice PublicKeySlice) Equals(other PublicKeySlice) bool {
if len(slice) != len(other) {
return false
}
for i, pubkey := range slice {
if !pubkey.Equals(other[i]) {
return false
}
}
return true
}
// Same returns true if the two slices contain the same public keys,
// but not necessarily in the same order.
func (slice PublicKeySlice) Same(other PublicKeySlice) bool {
if len(slice) != len(other) {
return false
}
for _, pubkey := range slice {
if !other.Contains(pubkey) {
return false
}
}
return true
}
// Split splits the slice into chunks of the specified size.
func (slice PublicKeySlice) Split(chunkSize int) []PublicKeySlice {
divided := make([]PublicKeySlice, 0)
if len(slice) == 0 || chunkSize < 1 {
return divided
}
if len(slice) == 1 {
return append(divided, slice)
}
for i := 0; i < len(slice); i += chunkSize {
end := i + chunkSize
if end > len(slice) {
end = len(slice)
}
divided = append(divided, slice[i:end])
}
return divided
}
// Last returns the last element of the slice.
// Returns nil if the slice is empty.
func (slice PublicKeySlice) Last() *PublicKey {
if len(slice) == 0 {
return nil
}
return slice[len(slice)-1].ToPointer()
}
// First returns the first element of the slice.
// Returns nil if the slice is empty.
func (slice PublicKeySlice) First() *PublicKey {
if len(slice) == 0 {
return nil
}
return slice[0].ToPointer()
}
// GetAddedRemoved compares to the `next` pubkey slice, and returns
// two slices:
// - `added` is the slice of pubkeys that are present in `next` but NOT present in `previous`.
// - `removed` is the slice of pubkeys that are present in `previous` but are NOT present in `next`.
func (prev PublicKeySlice) GetAddedRemoved(next PublicKeySlice) (added PublicKeySlice, removed PublicKeySlice) {
return next.Removed(prev), prev.Removed(next)
}
// GetAddedRemovedPubkeys accepts two slices of pubkeys (`previous` and `next`), and returns
// two slices:
// - `added` is the slice of pubkeys that are present in `next` but NOT present in `previous`.
// - `removed` is the slice of pubkeys that are present in `previous` but are NOT present in `next`.
func GetAddedRemovedPubkeys(previous PublicKeySlice, next PublicKeySlice) (added PublicKeySlice, removed PublicKeySlice) {
added = make(PublicKeySlice, 0)
removed = make(PublicKeySlice, 0)
for _, prev := range previous {
if !next.Has(prev) {
removed = append(removed, prev)
}
}
for _, nx := range next {
if !previous.Has(nx) {
added = append(added, nx)
}
}
return
}
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
/// Number of bytes in a signature.
SignatureLength = 64
// // 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{}, ErrMaxSeedLengthExceeded
}
// 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"
var ErrMaxSeedLengthExceeded = errors.New("max seed length exceeded")
// 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{}, ErrMaxSeedLengthExceeded
}
for _, seed := range seeds {
if len(seed) > MaxSeedLength {
return PublicKey{}, ErrMaxSeedLengthExceeded
}
}
buf := []byte{}
for _, seed := range seeds {
buf = append(buf, seed...)
}
buf = append(buf, programID[:]...)
buf = append(buf, []byte(PDA_MARKER)...)
hash := sha256.Sum256(buf)
if IsOnCurve(hash[:]) {
return PublicKey{}, errors.New("invalid seeds; address must fall off the curve")
}
return PublicKeyFromBytes(hash[:]), nil
}
// Check if the provided `b` is on the ed25519 curve.
func IsOnCurve(b []byte) bool {
_, err := new(edwards25519.Point).SetBytes(b)
isOnCurve := err == nil
return isOnCurve
}
// 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(
wallet PublicKey,
mint PublicKey,
) (PublicKey, uint8, error) {
return findAssociatedTokenAddressAndBumpSeed(
wallet,
mint,
SPLAssociatedTokenAccountProgramID,
)
}
func findAssociatedTokenAddressAndBumpSeed(
walletAddress PublicKey,
splTokenMintAddress PublicKey,
programID PublicKey,
) (PublicKey, uint8, error) {
return FindProgramAddress([][]byte{
walletAddress[:],
TokenProgramID[:],
splTokenMintAddress[:],
},
programID,
)
}
// FindTokenMetadataAddress returns the token metadata program-derived address given a SPL token mint address.
func FindTokenMetadataAddress(mint PublicKey) (PublicKey, uint8, error) {
seed := [][]byte{
[]byte("metadata"),
TokenMetadataProgramID[:],
mint[:],
}
return FindProgramAddress(seed, TokenMetadataProgramID)
}