-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
671 lines (580 loc) · 19.6 KB
/
transaction.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
// 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"
"encoding/base64"
"fmt"
"sort"
"github.com/davecgh/go-spew/spew"
bin "github.com/gagliardetto/binary"
"github.com/gagliardetto/treeout"
"go.uber.org/zap"
"github.com/gagliardetto/solana-go/text"
)
type Transaction struct {
// A list of base-58 encoded signatures applied to the transaction.
// The list is always of length `message.header.numRequiredSignatures` and not empty.
// The signature at index `i` corresponds to the public key at index
// `i` in `message.account_keys`. The first one is used as the transaction id.
Signatures []Signature `json:"signatures"`
// Defines the content of the transaction.
Message Message `json:"message"`
}
// UnmarshalBase64 decodes a base64 encoded transaction.
func (tx *Transaction) UnmarshalBase64(b64 string) error {
b, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
return err
}
return tx.UnmarshalWithDecoder(bin.NewBinDecoder(b))
}
var _ bin.EncoderDecoder = &Transaction{}
func (t *Transaction) HasAccount(account PublicKey) (bool, error) {
return t.Message.HasAccount(account)
}
func (t *Transaction) IsSigner(account PublicKey) bool {
return t.Message.IsSigner(account)
}
func (t *Transaction) IsWritable(account PublicKey) (bool, error) {
return t.Message.IsWritable(account)
}
func (t *Transaction) AccountMetaList() ([]*AccountMeta, error) {
return t.Message.AccountMetaList()
}
func (t *Transaction) ResolveProgramIDIndex(programIDIndex uint16) (PublicKey, error) {
return t.Message.ResolveProgramIDIndex(programIDIndex)
}
// TransactionFromDecoder decodes a transaction from a decoder.
func TransactionFromDecoder(decoder *bin.Decoder) (*Transaction, error) {
var out *Transaction
err := decoder.Decode(&out)
if err != nil {
return nil, err
}
return out, nil
}
// MustTransactionFromDecoder decodes a transaction from a decoder.
// Panics on error.
func MustTransactionFromDecoder(decoder *bin.Decoder) *Transaction {
out, err := TransactionFromDecoder(decoder)
if err != nil {
panic(err)
}
return out
}
type CompiledInstruction struct {
// Index into the message.accountKeys array indicating the program account that executes this instruction.
// NOTE: it is actually a uint8, but using a uint16 because uint8 is treated as a byte everywhere,
// and that can be an issue.
ProgramIDIndex uint16 `json:"programIdIndex"`
// List of ordered indices into the message.accountKeys array indicating which accounts to pass to the program.
// NOTE: it is actually a []uint8, but using a uint16 because []uint8 is treated as a []byte everywhere,
// and that can be an issue.
Accounts []uint16 `json:"accounts"`
// The program input data encoded in a base-58 string.
Data Base58 `json:"data"`
}
func (ci *CompiledInstruction) ResolveInstructionAccounts(message *Message) ([]*AccountMeta, error) {
out := make([]*AccountMeta, len(ci.Accounts))
metas, err := message.AccountMetaList()
if err != nil {
return nil, err
}
for i, acct := range ci.Accounts {
out[i] = metas[acct]
}
return out, nil
}
type Instruction interface {
ProgramID() PublicKey // the programID the instruction acts on
Accounts() []*AccountMeta // returns the list of accounts the instructions requires
Data() ([]byte, error) // the binary encoded instructions
}
type TransactionOption interface {
apply(opts *transactionOptions)
}
type transactionOptions struct {
payer PublicKey
addressTables map[PublicKey]PublicKeySlice // [tablePubkey]addresses
}
type transactionOptionFunc func(opts *transactionOptions)
func (f transactionOptionFunc) apply(opts *transactionOptions) {
f(opts)
}
func TransactionPayer(payer PublicKey) TransactionOption {
return transactionOptionFunc(func(opts *transactionOptions) { opts.payer = payer })
}
func TransactionAddressTables(tables map[PublicKey]PublicKeySlice) TransactionOption {
return transactionOptionFunc(func(opts *transactionOptions) { opts.addressTables = tables })
}
var debugNewTransaction = false
type TransactionBuilder struct {
instructions []Instruction
recentBlockHash Hash
opts []TransactionOption
}
// NewTransactionBuilder creates a new instruction builder.
func NewTransactionBuilder() *TransactionBuilder {
return &TransactionBuilder{}
}
// AddInstruction adds the provided instruction to the builder.
func (builder *TransactionBuilder) AddInstruction(instruction Instruction) *TransactionBuilder {
builder.instructions = append(builder.instructions, instruction)
return builder
}
// SetRecentBlockHash sets the recent blockhash for the instruction builder.
func (builder *TransactionBuilder) SetRecentBlockHash(recentBlockHash Hash) *TransactionBuilder {
builder.recentBlockHash = recentBlockHash
return builder
}
// WithOpt adds a TransactionOption.
func (builder *TransactionBuilder) WithOpt(opt TransactionOption) *TransactionBuilder {
builder.opts = append(builder.opts, opt)
return builder
}
// Set transaction fee payer.
// If not set, defaults to first signer account of the first instruction.
func (builder *TransactionBuilder) SetFeePayer(feePayer PublicKey) *TransactionBuilder {
builder.opts = append(builder.opts, TransactionPayer(feePayer))
return builder
}
// Build builds and returns a *Transaction.
func (builder *TransactionBuilder) Build() (*Transaction, error) {
return NewTransaction(
builder.instructions,
builder.recentBlockHash,
builder.opts...,
)
}
type addressTablePubkeyWithIndex struct {
addressTable PublicKey
index uint8
}
func NewTransaction(instructions []Instruction, recentBlockHash Hash, opts ...TransactionOption) (*Transaction, error) {
if len(instructions) == 0 {
return nil, fmt.Errorf("requires at-least one instruction to create a transaction")
}
options := transactionOptions{}
for _, opt := range opts {
opt.apply(&options)
}
feePayer := options.payer
if feePayer.IsZero() {
found := false
for _, act := range instructions[0].Accounts() {
if act.IsSigner {
feePayer = act.PublicKey
found = true
break
}
}
if !found {
return nil, fmt.Errorf("cannot determine fee payer. You can ether pass the fee payer via the 'TransactionWithInstructions' option parameter or it falls back to the first instruction's first signer")
}
}
addressLookupKeysMap := make(map[PublicKey]addressTablePubkeyWithIndex) // all accounts from tables as map
for addressTablePubKey, addressTable := range options.addressTables {
if len(addressTable) > 256 {
return nil, fmt.Errorf("max lookup table index exceeded for %s table", addressTablePubKey)
}
for i, address := range addressTable {
_, ok := addressLookupKeysMap[address]
if ok {
continue
}
addressLookupKeysMap[address] = addressTablePubkeyWithIndex{
addressTable: addressTablePubKey,
index: uint8(i),
}
}
}
programIDs := make(PublicKeySlice, 0)
accounts := []*AccountMeta{}
for _, instruction := range instructions {
accounts = append(accounts, instruction.Accounts()...)
programIDs.UniqueAppend(instruction.ProgramID())
}
// for IsInvoked check
programIDsMap := make(map[PublicKey]struct{}, len(programIDs))
// Add programID to the account list
for _, programID := range programIDs {
accounts = append(accounts, &AccountMeta{
PublicKey: programID,
IsSigner: false,
IsWritable: false,
})
programIDsMap[programID] = struct{}{}
}
// Sort. Prioritizing first by signer, then by writable
sort.SliceStable(accounts, func(i, j int) bool {
return accounts[i].less(accounts[j])
})
uniqAccountsMap := map[PublicKey]uint64{}
uniqAccounts := []*AccountMeta{}
for _, acc := range accounts {
if index, found := uniqAccountsMap[acc.PublicKey]; found {
uniqAccounts[index].IsWritable = uniqAccounts[index].IsWritable || acc.IsWritable
continue
}
uniqAccounts = append(uniqAccounts, acc)
uniqAccountsMap[acc.PublicKey] = uint64(len(uniqAccounts) - 1)
}
if debugNewTransaction {
zlog.Debug("unique account sorted", zap.Int("account_count", len(uniqAccounts)))
}
// Move fee payer to the front
feePayerIndex := -1
for idx, acc := range uniqAccounts {
if acc.PublicKey.Equals(feePayer) {
feePayerIndex = idx
}
}
if debugNewTransaction {
zlog.Debug("current fee payer index", zap.Int("fee_payer_index", feePayerIndex))
}
accountCount := len(uniqAccounts)
if feePayerIndex < 0 {
// fee payer is not part of accounts we want to add it
accountCount++
}
allKeys := make([]*AccountMeta, accountCount)
itr := 1
for idx, uniqAccount := range uniqAccounts {
if idx == feePayerIndex {
uniqAccount.IsSigner = true
uniqAccount.IsWritable = true
allKeys[0] = uniqAccount
continue
}
allKeys[itr] = uniqAccount
itr++
}
if feePayerIndex < 0 {
// fee payer is not part of accounts we want to add it
feePayerAccount := &AccountMeta{
PublicKey: feePayer,
IsSigner: true,
IsWritable: true,
}
allKeys[0] = feePayerAccount
}
message := Message{
RecentBlockhash: recentBlockHash,
}
lookupsMap := make(map[PublicKey]struct { // extended MessageAddressTableLookup
AccountKey PublicKey // The account key of the address table.
WritableIndexes []uint8
Writable []PublicKey
ReadonlyIndexes []uint8
Readonly []PublicKey
})
for idx, acc := range allKeys {
if debugNewTransaction {
zlog.Debug("transaction account",
zap.Int("account_index", idx),
zap.Stringer("account_pub_key", acc.PublicKey),
)
}
addressLookupKeyEntry, isPresentedInTables := addressLookupKeysMap[acc.PublicKey]
_, isInvoked := programIDsMap[acc.PublicKey]
// skip fee payer
if isPresentedInTables && idx != 0 && !acc.IsSigner && !isInvoked {
lookup := lookupsMap[addressLookupKeyEntry.addressTable]
if acc.IsWritable {
lookup.WritableIndexes = append(lookup.WritableIndexes, addressLookupKeyEntry.index)
lookup.Writable = append(lookup.Writable, acc.PublicKey)
} else {
lookup.ReadonlyIndexes = append(lookup.ReadonlyIndexes, addressLookupKeyEntry.index)
lookup.Readonly = append(lookup.Readonly, acc.PublicKey)
}
lookupsMap[addressLookupKeyEntry.addressTable] = lookup
continue // prevent changing message.Header properties
}
message.AccountKeys = append(message.AccountKeys, acc.PublicKey)
if acc.IsSigner {
message.Header.NumRequiredSignatures++
if !acc.IsWritable {
message.Header.NumReadonlySignedAccounts++
}
continue
}
if !acc.IsWritable {
message.Header.NumReadonlyUnsignedAccounts++
}
}
var lookupsWritableKeys []PublicKey
var lookupsReadOnlyKeys []PublicKey
if len(lookupsMap) > 0 {
lookups := make([]MessageAddressTableLookup, 0, len(lookupsMap))
for tablePubKey, l := range lookupsMap {
lookupsWritableKeys = append(lookupsWritableKeys, l.Writable...)
lookupsReadOnlyKeys = append(lookupsReadOnlyKeys, l.Readonly...)
lookups = append(lookups, MessageAddressTableLookup{
AccountKey: tablePubKey,
WritableIndexes: l.WritableIndexes,
ReadonlyIndexes: l.ReadonlyIndexes,
})
}
// prevent error created in ResolveLookups
err := message.SetAddressTables(options.addressTables)
if err != nil {
return nil, fmt.Errorf("SetAddressTables: %s", err)
}
message.SetAddressTableLookups(lookups)
}
var idx uint16
accountKeyIndex := make(map[string]uint16, len(message.AccountKeys)+len(lookupsWritableKeys)+len(lookupsReadOnlyKeys))
for _, acc := range message.AccountKeys {
accountKeyIndex[acc.String()] = idx
idx++
}
for _, acc := range lookupsWritableKeys {
accountKeyIndex[acc.String()] = idx
idx++
}
for _, acc := range lookupsReadOnlyKeys {
accountKeyIndex[acc.String()] = idx
idx++
}
if debugNewTransaction {
zlog.Debug("message header compiled",
zap.Uint8("num_required_signatures", message.Header.NumRequiredSignatures),
zap.Uint8("num_readonly_signed_accounts", message.Header.NumReadonlySignedAccounts),
zap.Uint8("num_readonly_unsigned_accounts", message.Header.NumReadonlyUnsignedAccounts),
)
}
for txIdx, instruction := range instructions {
accounts = instruction.Accounts()
accountIndex := make([]uint16, len(accounts))
for idx, acc := range accounts {
accountIndex[idx] = accountKeyIndex[acc.PublicKey.String()]
}
data, err := instruction.Data()
if err != nil {
return nil, fmt.Errorf("unable to encode instructions [%d]: %w", txIdx, err)
}
message.Instructions = append(message.Instructions, CompiledInstruction{
ProgramIDIndex: accountKeyIndex[instruction.ProgramID().String()],
Accounts: accountIndex,
Data: data,
})
}
return &Transaction{
Message: message,
}, nil
}
type privateKeyGetter func(key PublicKey) *PrivateKey
func (tx *Transaction) MarshalBinary() ([]byte, error) {
messageContent, err := tx.Message.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("failed to encode tx.Message to binary: %w", err)
}
var signatureCount []byte
bin.EncodeCompactU16Length(&signatureCount, len(tx.Signatures))
output := make([]byte, 0, len(signatureCount)+len(signatureCount)*64+len(messageContent))
output = append(output, signatureCount...)
for _, sig := range tx.Signatures {
output = append(output, sig[:]...)
}
output = append(output, messageContent...)
return output, nil
}
func (tx Transaction) MarshalWithEncoder(encoder *bin.Encoder) error {
out, err := tx.MarshalBinary()
if err != nil {
return err
}
return encoder.WriteBytes(out, false)
}
func (tx *Transaction) UnmarshalWithDecoder(decoder *bin.Decoder) (err error) {
{
numSignatures, err := decoder.ReadCompactU16()
if err != nil {
return fmt.Errorf("unable to read numSignatures: %w", err)
}
if numSignatures > decoder.Remaining()/64 {
return fmt.Errorf("numSignatures %d is too large for remaining bytes %d", numSignatures, decoder.Remaining())
}
tx.Signatures = make([]Signature, numSignatures)
for i := 0; i < numSignatures; i++ {
_, err := decoder.Read(tx.Signatures[i][:])
if err != nil {
return fmt.Errorf("unable to read tx.Signatures[%d]: %w", i, err)
}
}
}
{
err := tx.Message.UnmarshalWithDecoder(decoder)
if err != nil {
return fmt.Errorf("unable to decode tx.Message: %w", err)
}
}
return nil
}
func (tx *Transaction) PartialSign(getter privateKeyGetter) (out []Signature, err error) {
messageContent, err := tx.Message.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("unable to encode message for signing: %w", err)
}
signerKeys := tx.Message.signerKeys()
signedSignatures := []Signature{}
for _, key := range signerKeys {
privateKey := getter(key)
if privateKey != nil {
s, err := privateKey.Sign(messageContent)
if err != nil {
return nil, fmt.Errorf("failed to signed with key %q: %w", key.String(), err)
}
signedSignatures = append(signedSignatures, s)
}
}
tx.Signatures = append(tx.Signatures, signedSignatures...)
return tx.Signatures, nil
}
func (tx *Transaction) Sign(getter privateKeyGetter) (out []Signature, err error) {
signerKeys := tx.Message.signerKeys()
for _, key := range signerKeys {
if getter(key) == nil {
return nil, fmt.Errorf("signer key %q not found. Ensure all the signer keys are in the vault", key.String())
}
}
return tx.PartialSign(getter)
}
func (tx *Transaction) EncodeTree(encoder *text.TreeEncoder) (int, error) {
tx.EncodeToTree(encoder)
return encoder.WriteString(encoder.Tree.String())
}
// String returns a human-readable string representation of the transaction data.
// To disable colors, set "github.com/gagliardetto/solana-go/text".DisableColors = true
func (tx *Transaction) String() string {
buf := new(bytes.Buffer)
_, err := tx.EncodeTree(text.NewTreeEncoder(buf, ""))
if err != nil {
panic(err)
}
return buf.String()
}
func (tx Transaction) ToBase64() (string, error) {
out, err := tx.MarshalBinary()
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(out), nil
}
func (tx Transaction) MustToBase64() string {
out, err := tx.ToBase64()
if err != nil {
panic(err)
}
return out
}
func (tx *Transaction) EncodeToTree(parent treeout.Branches) {
parent.ParentFunc(func(txTree treeout.Branches) {
txTree.Child(fmt.Sprintf("Signatures[len=%v]", len(tx.Signatures))).ParentFunc(func(signaturesBranch treeout.Branches) {
for _, sig := range tx.Signatures {
signaturesBranch.Child(sig.String())
}
})
txTree.Child("Message").ParentFunc(func(messageBranch treeout.Branches) {
tx.Message.EncodeToTree(messageBranch)
})
})
parent.Child(fmt.Sprintf("Instructions[len=%v]", len(tx.Message.Instructions))).ParentFunc(func(message treeout.Branches) {
for _, inst := range tx.Message.Instructions {
progKey, err := tx.ResolveProgramIDIndex(inst.ProgramIDIndex)
if err == nil {
accounts, err := inst.ResolveInstructionAccounts(&tx.Message)
if err != nil {
message.Child(fmt.Sprintf(text.RedBG("cannot ResolveInstructionAccounts: %s"), err))
return
}
decodedInstruction, err := DecodeInstruction(progKey, accounts, inst.Data)
if err == nil {
if enToTree, ok := decodedInstruction.(text.EncodableToTree); ok {
enToTree.EncodeToTree(message)
} else {
message.Child(spew.Sdump(decodedInstruction))
}
} else {
// TODO: log error?
message.Child(fmt.Sprintf(text.RedBG("cannot decode instruction for %s program: %s"), progKey, err)).
Child(text.IndigoBG("Program") + ": " + text.Bold("<unknown>") + " " + text.ColorizeBG(progKey.String())).
//
ParentFunc(func(programBranch treeout.Branches) {
programBranch.Child(text.Purple(text.Bold("Instruction")) + ": " + text.Bold("<unknown>")).
//
ParentFunc(func(instructionBranch treeout.Branches) {
// Data of the instruction call:
instructionBranch.Child(text.Sf("data[len=%v bytes]", len(inst.Data))).ParentFunc(func(paramsBranch treeout.Branches) {
paramsBranch.Child(bin.FormatByteSlice(inst.Data))
})
// Accounts of the instruction call:
instructionBranch.Child(text.Sf("accounts[len=%v]", len(accounts))).ParentFunc(func(accountsBranch treeout.Branches) {
for i := range accounts {
accountsBranch.Child(formatMeta(text.Sf("accounts[%v]", i), accounts[i]))
}
})
})
})
}
} else {
message.Child(fmt.Sprintf(text.RedBG("cannot ResolveProgramIDIndex: %s"), err))
}
}
})
}
func formatMeta(name string, meta *AccountMeta) string {
if meta == nil {
return text.Shakespeare(name) + ": " + "<nil>"
}
out := text.Shakespeare(name) + ": " + text.ColorizeBG(meta.PublicKey.String())
out += " ["
if meta.IsWritable {
out += "WRITE"
}
if meta.IsSigner {
if meta.IsWritable {
out += ", "
}
out += "SIGN"
}
out += "] "
return out
}
// VerifySignatures verifies all the signatures in the transaction
// against the pubkeys of the signers.
func (tx *Transaction) VerifySignatures() error {
msg, err := tx.Message.MarshalBinary()
if err != nil {
return err
}
signers := tx.Message.Signers()
if len(signers) != len(tx.Signatures) {
return fmt.Errorf(
"got %v signers, but %v signatures",
len(signers),
len(tx.Signatures),
)
}
for i, sig := range tx.Signatures {
if !sig.Verify(signers[i], msg) {
return fmt.Errorf("invalid signature by %s", signers[i].String())
}
}
return nil
}