forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.go
1498 lines (1342 loc) · 46.4 KB
/
handlers.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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package handlers
import (
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/vincentbdb/go-algorand/agreement"
"github.com/vincentbdb/go-algorand/config"
"github.com/vincentbdb/go-algorand/crypto"
"github.com/vincentbdb/go-algorand/daemon/algod/api/server/lib"
"github.com/vincentbdb/go-algorand/daemon/algod/api/spec/v1"
"github.com/vincentbdb/go-algorand/data"
"github.com/vincentbdb/go-algorand/data/basics"
"github.com/vincentbdb/go-algorand/data/bookkeeping"
"github.com/vincentbdb/go-algorand/data/transactions"
"github.com/vincentbdb/go-algorand/ledger"
"github.com/vincentbdb/go-algorand/node"
"github.com/vincentbdb/go-algorand/protocol"
)
func nodeStatus(node *node.AlgorandFullNode) (res v1.NodeStatus, err error) {
stat, err := node.Status()
if err != nil {
return v1.NodeStatus{}, err
}
return v1.NodeStatus{
LastRound: uint64(stat.LastRound),
LastVersion: string(stat.LastVersion),
NextVersion: string(stat.NextVersion),
NextVersionRound: uint64(stat.NextVersionRound),
NextVersionSupported: stat.NextVersionSupported,
TimeSinceLastRound: stat.TimeSinceLastRound().Nanoseconds(),
CatchupTime: stat.CatchupTime.Nanoseconds(),
}, nil
}
// decorateUnknownTransactionTypeError takes an error of type errUnknownTransactionType and converts it into
// either errInvalidTransactionTypeLedger or errInvalidTransactionTypePending as needed.
func decorateUnknownTransactionTypeError(err error, txs node.TxnWithStatus) error {
if err.Error() != errUnknownTransactionType {
return err
}
if txs.ConfirmedRound != basics.Round(0) {
return fmt.Errorf(errInvalidTransactionTypeLedger, txs.Txn.Txn.Type, txs.Txn.Txn.ID().String(), txs.ConfirmedRound)
}
return fmt.Errorf(errInvalidTransactionTypePending, txs.Txn.Txn.Type, txs.Txn.Txn.ID().String())
}
// txEncode copies the data fields of the internal transaction object and populate the v1.Transaction accordingly.
// if unexpected transaction type is encountered, an error is returned. The caller is expected to ignore the returned
// transaction when error is non-nil.
func txEncode(tx transactions.Transaction, ad transactions.ApplyData) (v1.Transaction, error) {
var res v1.Transaction
switch tx.Type {
case protocol.PaymentTx:
res = paymentTxEncode(tx, ad)
case protocol.KeyRegistrationTx:
res = keyregTxEncode(tx, ad)
case protocol.AssetConfigTx:
res = assetConfigTxEncode(tx, ad)
case protocol.AssetTransferTx:
res = assetTransferTxEncode(tx, ad)
case protocol.AssetFreezeTx:
res = assetFreezeTxEncode(tx, ad)
default:
return res, errors.New(errUnknownTransactionType)
}
res.Type = string(tx.Type)
res.TxID = tx.ID().String()
res.From = tx.Src().String()
res.Fee = tx.TxFee().Raw
res.FirstRound = uint64(tx.First())
res.LastRound = uint64(tx.Last())
res.Note = tx.Aux()
res.FromRewards = ad.SenderRewards.Raw
res.GenesisID = tx.GenesisID
res.GenesisHash = tx.GenesisHash[:]
res.Group = tx.Group[:]
return res, nil
}
func paymentTxEncode(tx transactions.Transaction, ad transactions.ApplyData) v1.Transaction {
payment := v1.PaymentTransactionType{
To: tx.Receiver.String(),
Amount: tx.TxAmount().Raw,
ToRewards: ad.ReceiverRewards.Raw,
CloseRewards: ad.CloseRewards.Raw,
}
if tx.CloseRemainderTo != (basics.Address{}) {
payment.CloseRemainderTo = tx.CloseRemainderTo.String()
payment.CloseAmount = ad.ClosingAmount.Raw
}
return v1.Transaction{
Payment: &payment,
}
}
func keyregTxEncode(tx transactions.Transaction, ad transactions.ApplyData) v1.Transaction {
keyreg := v1.KeyregTransactionType{
VotePK: tx.KeyregTxnFields.VotePK[:],
SelectionPK: tx.KeyregTxnFields.SelectionPK[:],
VoteFirst: uint64(tx.KeyregTxnFields.VoteFirst),
VoteLast: uint64(tx.KeyregTxnFields.VoteLast),
VoteKeyDilution: tx.KeyregTxnFields.VoteKeyDilution,
}
return v1.Transaction{
Keyreg: &keyreg,
}
}
func assetParams(creator basics.Address, params basics.AssetParams) v1.AssetParams {
paramsModel := v1.AssetParams{
Total: params.Total,
DefaultFrozen: params.DefaultFrozen,
}
paramsModel.UnitName = strings.TrimRight(string(params.UnitName[:]), "\x00")
paramsModel.AssetName = strings.TrimRight(string(params.AssetName[:]), "\x00")
paramsModel.URL = strings.TrimRight(string(params.URL[:]), "\x00")
if params.MetadataHash != [32]byte{} {
paramsModel.MetadataHash = params.MetadataHash[:]
}
if !creator.IsZero() {
paramsModel.Creator = creator.String()
}
if !params.Manager.IsZero() {
paramsModel.ManagerAddr = params.Manager.String()
}
if !params.Reserve.IsZero() {
paramsModel.ReserveAddr = params.Reserve.String()
}
if !params.Freeze.IsZero() {
paramsModel.FreezeAddr = params.Freeze.String()
}
if !params.Clawback.IsZero() {
paramsModel.ClawbackAddr = params.Clawback.String()
}
return paramsModel
}
func assetConfigTxEncode(tx transactions.Transaction, ad transactions.ApplyData) v1.Transaction {
params := assetParams(basics.Address{}, tx.AssetConfigTxnFields.AssetParams)
config := v1.AssetConfigTransactionType{
AssetID: uint64(tx.AssetConfigTxnFields.ConfigAsset),
Params: params,
}
return v1.Transaction{
AssetConfig: &config,
}
}
func assetTransferTxEncode(tx transactions.Transaction, ad transactions.ApplyData) v1.Transaction {
xfer := v1.AssetTransferTransactionType{
AssetID: uint64(tx.AssetTransferTxnFields.XferAsset),
Amount: tx.AssetTransferTxnFields.AssetAmount,
Receiver: tx.AssetTransferTxnFields.AssetReceiver.String(),
}
if !tx.AssetTransferTxnFields.AssetSender.IsZero() {
xfer.Sender = tx.AssetTransferTxnFields.AssetSender.String()
}
if !tx.AssetTransferTxnFields.AssetCloseTo.IsZero() {
xfer.CloseTo = tx.AssetTransferTxnFields.AssetCloseTo.String()
}
return v1.Transaction{
AssetTransfer: &xfer,
}
}
func assetFreezeTxEncode(tx transactions.Transaction, ad transactions.ApplyData) v1.Transaction {
freeze := v1.AssetFreezeTransactionType{
AssetID: uint64(tx.AssetFreezeTxnFields.FreezeAsset),
Account: tx.AssetFreezeTxnFields.FreezeAccount.String(),
NewFreezeStatus: tx.AssetFreezeTxnFields.AssetFrozen,
}
return v1.Transaction{
AssetFreeze: &freeze,
}
}
func txWithStatusEncode(tr node.TxnWithStatus) (v1.Transaction, error) {
s, err := txEncode(tr.Txn.Txn, tr.ApplyData)
if err != nil {
err = decorateUnknownTransactionTypeError(err, tr)
return v1.Transaction{}, err
}
s.ConfirmedRound = uint64(tr.ConfirmedRound)
s.PoolError = tr.PoolError
return s, nil
}
func computeAssetIndexInPayset(tx node.TxnWithStatus, txnCounter uint64, payset []transactions.SignedTxnWithAD) (aidx uint64) {
// Compute transaction index in block
offset := -1
for idx, stxnib := range payset {
if tx.Txn.Txn.ID() == stxnib.Txn.ID() {
offset = idx
break
}
}
// Sanity check that txn was in fetched block
if offset < 0 {
return 0
}
// Count into block to get created asset index
return txnCounter - uint64(len(payset)) + uint64(offset) + 1
}
// computeAssetIndexFromTxn returns the created asset index given a confirmed
// transaction whose confirmation block is available in the ledger. Note that
// 0 is an invalid asset index (they start at 1).
func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx uint64) {
// Must have ledger
if l == nil {
return 0
}
// Transaction must be confirmed
if tx.ConfirmedRound == 0 {
return 0
}
// Transaction must be AssetConfig transaction
if tx.Txn.Txn.AssetConfigTxnFields == (transactions.AssetConfigTxnFields{}) {
return 0
}
// Transaction must be creating an asset
if tx.Txn.Txn.AssetConfigTxnFields.ConfigAsset != 0 {
return 0
}
// Look up block where transaction was confirmed
blk, err := l.Block(tx.ConfirmedRound)
if err != nil {
return 0
}
payset, err := blk.DecodePaysetFlat()
if err != nil {
return 0
}
return computeAssetIndexInPayset(tx, blk.BlockHeader.TxnCounter, payset)
}
func blockEncode(b bookkeeping.Block, c agreement.Certificate) (v1.Block, error) {
block := v1.Block{
Hash: crypto.Digest(b.Hash()).String(),
PreviousBlockHash: crypto.Digest(b.Branch).String(),
Seed: crypto.Digest(b.Seed()).String(),
Proposer: c.Proposal.OriginalProposer.String(),
Round: uint64(b.Round()),
TransactionsRoot: b.TxnRoot.String(),
RewardsRate: b.RewardsRate,
RewardsLevel: b.RewardsLevel,
RewardsResidue: b.RewardsResidue,
Timestamp: b.TimeStamp,
UpgradeState: v1.UpgradeState{
CurrentProtocol: string(b.CurrentProtocol),
NextProtocol: string(b.NextProtocol),
NextProtocolApprovals: b.NextProtocolApprovals,
NextProtocolVoteBefore: uint64(b.NextProtocolVoteBefore),
NextProtocolSwitchOn: uint64(b.NextProtocolSwitchOn),
},
UpgradeVote: v1.UpgradeVote{
UpgradePropose: string(b.UpgradePropose),
UpgradeApprove: b.UpgradeApprove,
},
}
// Transactions
var txns []v1.Transaction
payset, err := b.DecodePaysetFlat()
if err != nil {
return v1.Block{}, err
}
for _, txn := range payset {
tx := node.TxnWithStatus{
Txn: txn.SignedTxn,
ConfirmedRound: b.Round(),
ApplyData: txn.ApplyData,
}
encTx, err := txWithStatusEncode(tx)
if err != nil {
return v1.Block{}, err
}
txns = append(txns, encTx)
}
block.Transactions = v1.TransactionList{Transactions: txns}
return block, nil
}
// Status is an httpHandler for route GET /v1/status
func Status(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/status GetStatus
//---
// Summary: Gets the current node status.
// Produces:
// - application/json
// Schemes:
// - http
// Responses:
// 200:
// "$ref": '#/responses/StatusResponse'
// 500:
// description: Internal Error
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
nodeStatus, err := nodeStatus(ctx.Node)
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedRetrievingNodeStatus, ctx.Log)
return
}
response := StatusResponse{&nodeStatus}
SendJSON(response, w, ctx.Log)
}
// WaitForBlock is an httpHandler for route GET /v1/status/wait-for-block-after/{round:[0-9]+}
func WaitForBlock(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/status/wait-for-block-after/{round}/ WaitForBlock
// ---
// Summary: Gets the node status after waiting for the given round.
// Description: Waits for a block to appear after round {round} and returns the node's status at the time.
// Produces:
// - application/json
// Schemes:
// - http
// Parameters:
// - name: round
// in: path
// type: integer
// format: int64
// minimum: 0
// required: true
// description: The round to wait until returning status
// Responses:
// 200:
// "$ref": '#/responses/StatusResponse'
// 400:
// description: Bad Request
// schema: {type: string}
// 500:
// description: Internal Error
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
queryRound, err := strconv.ParseUint(mux.Vars(r)["round"], 10, 64)
if err != nil {
lib.ErrorResponse(w, http.StatusBadRequest, err, errFailedParsingRoundNumber, ctx.Log)
return
}
select {
case <-time.After(1 * time.Minute):
case <-ctx.Node.Ledger().Wait(basics.Round(queryRound + 1)):
}
nodeStatus, err := nodeStatus(ctx.Node)
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedRetrievingNodeStatus, ctx.Log)
return
}
response := StatusResponse{&nodeStatus}
SendJSON(response, w, ctx.Log)
}
// RawTransaction is an httpHandler for route POST /v1/transactions
func RawTransaction(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /v1/transactions RawTransaction
// ---
// Summary: Broadcasts a raw transaction to the network.
// Produces:
// - application/json
// Consumes:
// - application/x-binary
// Schemes:
// - http
// Parameters:
// - name: rawtxn
// in: body
// schema:
// type: string
// format: binary
// required: true
// description: The byte encoded signed transaction to broadcast to network
// Responses:
// 200:
// "$ref": "#/responses/TransactionIDResponse"
// 400:
// description: Bad Request
// schema: {type: string}
// 500:
// description: Internal Error
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
var txgroup []transactions.SignedTxn
dec := protocol.NewDecoder(r.Body)
for {
var st transactions.SignedTxn
err := dec.Decode(&st)
if err == io.EOF {
break
}
if err != nil {
lib.ErrorResponse(w, http.StatusBadRequest, err, err.Error(), ctx.Log)
return
}
txgroup = append(txgroup, st)
}
if len(txgroup) == 0 {
err := errors.New("empty txgroup")
lib.ErrorResponse(w, http.StatusBadRequest, err, err.Error(), ctx.Log)
return
}
err := ctx.Node.BroadcastSignedTxGroup(txgroup)
if err != nil {
lib.ErrorResponse(w, http.StatusBadRequest, err, err.Error(), ctx.Log)
return
}
// For backwards compatibility, return txid of first tx in group
txid := txgroup[0].ID()
SendJSON(TransactionIDResponse{&v1.TransactionID{TxID: txid.String()}}, w, ctx.Log)
}
// AccountInformation is an httpHandler for route GET /v1/account/{addr:[A-Z0-9]{KeyLength}}
func AccountInformation(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/account/{address} AccountInformation
// ---
// Summary: Get account information.
// Description: Given a specific account public key, this call returns the accounts status, balance and spendable amounts
// Produces:
// - application/json
// Schemes:
// - http
// Parameters:
// - name: address
// in: path
// type: string
// pattern: "[A-Z0-9]{58}"
// required: true
// description: An account public key
// Responses:
// 200:
// "$ref": '#/responses/AccountInformationResponse'
// 400:
// description: Bad Request
// schema: {type: string}
// 500:
// description: Internal Error
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
queryAddr := mux.Vars(r)["addr"]
if queryAddr == "" {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errNoAccountSpecified), errNoAccountSpecified, ctx.Log)
return
}
addr, err := basics.UnmarshalChecksumAddress(queryAddr)
if err != nil {
lib.ErrorResponse(w, http.StatusBadRequest, err, errFailedToParseAddress, ctx.Log)
return
}
myLedger := ctx.Node.Ledger()
lastRound := myLedger.Latest()
record, err := myLedger.Lookup(lastRound, basics.Address(addr))
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedLookingUpLedger, ctx.Log)
return
}
recordWithoutPendingRewards, err := myLedger.LookupWithoutRewards(lastRound, basics.Address(addr))
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedLookingUpLedger, ctx.Log)
return
}
amount := record.MicroAlgos
amountWithoutPendingRewards := recordWithoutPendingRewards.MicroAlgos
pendingRewards, overflowed := basics.OSubA(amount, amountWithoutPendingRewards)
if overflowed {
err = fmt.Errorf("overflowed pending rewards: %v - %v", amount, amountWithoutPendingRewards)
lib.ErrorResponse(w, http.StatusInternalServerError, err, errInternalFailure, ctx.Log)
return
}
var assets map[uint64]v1.AssetHolding
if len(record.Assets) > 0 {
assets = make(map[uint64]v1.AssetHolding)
for curid, holding := range record.Assets {
var creator string
creatorAddr, err := myLedger.GetAssetCreator(curid)
if err == nil {
creator = creatorAddr.String()
} else {
// Asset may have been deleted, so we can no
// longer fetch the creator
creator = ""
}
assets[uint64(curid)] = v1.AssetHolding{
Creator: creator,
Amount: holding.Amount,
Frozen: holding.Frozen,
}
}
}
var thisAssetParams map[uint64]v1.AssetParams
if len(record.AssetParams) > 0 {
thisAssetParams = make(map[uint64]v1.AssetParams)
for idx, params := range record.AssetParams {
thisAssetParams[uint64(idx)] = assetParams(addr, params)
}
}
apiParticipation := v1.Participation{
ParticipationPK: record.VoteID[:],
VRFPK: record.SelectionID[:],
VoteFirst: uint64(record.VoteFirstValid),
VoteLast: uint64(record.VoteLastValid),
VoteKeyDilution: record.VoteKeyDilution,
}
accountInfo := v1.Account{
Round: uint64(lastRound),
Address: addr.String(),
Amount: amount.Raw,
PendingRewards: pendingRewards.Raw,
AmountWithoutPendingRewards: amountWithoutPendingRewards.Raw,
Rewards: record.RewardedMicroAlgos.Raw,
Status: record.Status.String(),
Participation: apiParticipation,
AssetParams: thisAssetParams,
Assets: assets,
}
SendJSON(AccountInformationResponse{&accountInfo}, w, ctx.Log)
}
// TransactionInformation is an httpHandler for route GET /v1/account/{addr:[A-Z0-9]{KeyLength}}/transaction/{txid:[A-Z0-9]+}
func TransactionInformation(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/account/{address}/transaction/{txid} TransactionInformation
// ---
// Summary: Get a specific confirmed transaction.
// Description: >
// Given a wallet address and a transaction id, it returns the confirmed transaction
// information. This call scans up to <CurrentProtocol>.MaxTxnLife blocks in the past.
// Produces:
// - application/json
// Schemes:
// - http
// Parameters:
// - name: address
// in: path
// type: string
// pattern: "[A-Z0-9]{58}"
// required: true
// description: An account public key
// - name: txid
// in: path
// type: string
// pattern: "[A-Z0-9]+"
// required: true
// description: A transaction id
// Responses:
// 200:
// "$ref": '#/responses/TransactionResponse'
// 400:
// description: Bad Request
// schema: {type: string}
// 404:
// description: Transaction Not Found
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
queryTxID := mux.Vars(r)["txid"]
if queryTxID == "" {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errNoTxnSpecified), errNoTxnSpecified, ctx.Log)
return
}
txID := transactions.Txid{}
if txID.UnmarshalText([]byte(queryTxID)) != nil {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errNoTxnSpecified), errNoTxnSpecified, ctx.Log)
return
}
queryAddr := mux.Vars(r)["addr"]
if queryAddr == "" {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errNoAccountSpecified), errNoAccountSpecified, ctx.Log)
return
}
addr, err := basics.UnmarshalChecksumAddress(queryAddr)
if err != nil {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errFailedToParseAddress), errFailedToParseAddress, ctx.Log)
return
}
ledger := ctx.Node.Ledger()
latestRound := ledger.Latest()
stat, err := ctx.Node.Status()
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedRetrievingNodeStatus, ctx.Log)
return
}
proto := config.Consensus[stat.LastVersion]
// non-Archival nodes keep proto.MaxTxnLife blocks around,
// so without the + 1 in the below calculation,
// Node.GetTransaction will query 1 round more than is kept around
start := latestRound - basics.Round(proto.MaxTxnLife) + 1
if latestRound < basics.Round(proto.MaxTxnLife) {
start = 0
}
if txn, ok := ctx.Node.GetTransaction(addr, txID, start, latestRound); ok {
var responseTxs v1.Transaction
responseTxs, err = txWithStatusEncode(txn)
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedToParseTransaction, ctx.Log)
return
}
response := TransactionResponse{
Body: &responseTxs,
}
SendJSON(response, w, ctx.Log)
return
}
// We didn't find it, return a failure
lib.ErrorResponse(w, http.StatusNotFound, errors.New(errTransactionNotFound), errTransactionNotFound, ctx.Log)
return
}
// PendingTransactionInformation is an httpHandler for route GET /v1/transactions/pending/{txid:[A-Z0-9]+}
func PendingTransactionInformation(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/transactions/pending/{txid} PendingTransactionInformation
// ---
// Summary: Get a specific pending transaction.
// Description: >
// Given a transaction id of a recently submitted transaction, it returns information
// about it. There are several cases when this might succeed:
//
// - transaction committed (committed round > 0)
// - transaction still in the pool (committed round = 0, pool error = "")
// - transaction removed from pool due to error (committed round = 0, pool error != "")
//
// Or the transaction may have happened sufficiently long ago that the
// node no longer remembers it, and this will return an error.
// Produces:
// - application/json
// Schemes:
// - http
// Parameters:
// - name: txid
// in: path
// type: string
// pattern: "[A-Z0-9]+"
// required: true
// description: A transaction id
// Responses:
// 200:
// "$ref": '#/responses/TransactionResponse'
// 400:
// description: Bad Request
// schema: {type: string}
// 404:
// description: Transaction Not Found
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
queryTxID := mux.Vars(r)["txid"]
if queryTxID == "" {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errNoTxnSpecified), errNoTxnSpecified, ctx.Log)
return
}
txID := transactions.Txid{}
if txID.UnmarshalText([]byte(queryTxID)) != nil {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errNoTxnSpecified), errNoTxnSpecified, ctx.Log)
return
}
if txn, ok := ctx.Node.GetPendingTransaction(txID); ok {
ledger := ctx.Node.Ledger()
responseTxs, err := txWithStatusEncode(txn)
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedToParseTransaction, ctx.Log)
return
}
responseTxs.TransactionResults = &v1.TransactionResults{
// This field will be omitted for transactions that did not
// create an asset (or for which we could not look up the block
// it was created in), because computeAssetIndexFromTxn will
// return 0 in that case.
CreatedAssetIndex: computeAssetIndexFromTxn(txn, ledger),
}
response := TransactionResponse{
Body: &responseTxs,
}
SendJSON(response, w, ctx.Log)
return
}
// We didn't find it, return a failure
lib.ErrorResponse(w, http.StatusNotFound, errors.New(errTransactionNotFound), errTransactionNotFound, ctx.Log)
return
}
// GetPendingTransactions is an httpHandler for route GET /v1/transactions/pending.
func GetPendingTransactions(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/transactions/pending GetPendingTransactions
// ---
// Summary: Get a list of unconfirmed transactions currently in the transaction pool.
// Description: >
// Get the list of pending transactions, sorted by priority,
// in decreasing order, truncated at the end at MAX. If MAX = 0,
// returns all pending transactions.
// Produces:
// - application/json
// Schemes:
// - http
// Parameters:
// - name: max
// in: query
// type: integer
// format: int64
// minimum: 0
// required: false
// description: Truncated number of transactions to display. If max=0, returns all pending txns.
// Responses:
// "200":
// "$ref": '#/responses/PendingTransactionsResponse'
// 500:
// description: Internal Error
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
max, err := strconv.ParseUint(r.FormValue("max"), 10, 64)
if err != nil {
max = 0
}
txs, err := ctx.Node.GetPendingTxnsFromPool()
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedLookingUpTransactionPool, ctx.Log)
return
}
totalTxns := uint64(len(txs))
if max > 0 && totalTxns > max {
// we expose this truncating mechanism for the client only, for the flexibility
// to avoid dumping the whole pool over REST or in a cli. There is no need to optimize
// fetching a smaller transaction set at a lower level.
txs = txs[:max]
}
responseTxs := make([]v1.Transaction, len(txs))
for i, twr := range txs {
responseTxs[i], err = txEncode(twr.Txn, transactions.ApplyData{})
if err != nil {
// update the error as needed
err = decorateUnknownTransactionTypeError(err, node.TxnWithStatus{Txn: twr})
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedLookingUpTransactionPool, ctx.Log)
return
}
}
response := PendingTransactionsResponse{
Body: &v1.PendingTransactions{
TruncatedTxns: v1.TransactionList{
Transactions: responseTxs,
},
TotalTxns: totalTxns,
},
}
SendJSON(response, w, ctx.Log)
}
// GetPendingTransactionsByAddress is an httpHandler for route GET /v1/account/addr:[A-Z0-9]{KeyLength}}/transactions/pending.
func GetPendingTransactionsByAddress(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/account/{addr}/transactions/pending GetPendingTransactionsByAddress
// ---
// Summary: Get a list of unconfirmed transactions currently in the transaction pool by address.
// Description: >
// Get the list of pending transactions by address, sorted by priority,
// in decreasing order, truncated at the end at MAX. If MAX = 0,
// returns all pending transactions.
// Produces:
// - application/json
// Schemes:
// - http
// Parameters:
// - name: addr
// in: path
// type: string
// pattern: "[A-Z0-9]{58}"
// required: true
// description: An account public key
// - name: max
// in: query
// type: integer
// format: int64
// minimum: 0
// required: false
// description: Truncated number of transactions to display. If max=0, returns all pending txns.
// Responses:
// "200":
// "$ref": '#/responses/PendingTransactionsResponse'
// 500:
// description: Internal Error
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
queryMax := r.FormValue("max")
max, err := strconv.ParseUint(queryMax, 10, 64)
if queryMax != "" && err != nil {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errFailedToParseMaxValue), errFailedToParseMaxValue, ctx.Log)
return
}
queryAddr := mux.Vars(r)["addr"]
if queryAddr == "" {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errNoAccountSpecified), errNoAccountSpecified, ctx.Log)
return
}
addr, err := basics.UnmarshalChecksumAddress(queryAddr)
if err != nil {
lib.ErrorResponse(w, http.StatusBadRequest, err, errFailedToParseAddress, ctx.Log)
return
}
txs, err := ctx.Node.GetPendingTxnsFromPool()
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedLookingUpTransactionPool, ctx.Log)
return
}
responseTxs := make([]v1.Transaction, 0)
for i, twr := range txs {
if twr.Txn.Sender == addr || twr.Txn.Receiver == addr {
// truncate in case max was passed
if max > 0 && uint64(i) > max {
break
}
tx, err := txEncode(twr.Txn, transactions.ApplyData{})
responseTxs = append(responseTxs, tx)
if err != nil {
// update the error as needed
err = decorateUnknownTransactionTypeError(err, node.TxnWithStatus{Txn: twr})
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedLookingUpTransactionPool, ctx.Log)
return
}
}
}
response := PendingTransactionsResponse{
Body: &v1.PendingTransactions{
TruncatedTxns: v1.TransactionList{
Transactions: responseTxs,
},
TotalTxns: uint64(len(responseTxs)),
},
}
SendJSON(response, w, ctx.Log)
}
// AssetInformation is an httpHandler for route GET /v1/asset/{index:[0-9]+}
func AssetInformation(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/asset/{index} AssetInformation
// ---
// Summary: Get asset information.
// Description: >
// Given the asset's unique index, this call returns the asset's creator,
// manager, reserve, freeze, and clawback addresses
// Produces:
// - application/json
// Schemes:
// - http
// Parameters:
// - name: index
// in: path
// type: integer
// format: int64
// required: true
// description: Asset index
// Responses:
// 200:
// "$ref": '#/responses/AssetInformationResponse'
// 400:
// description: Bad Request
// schema: {type: string}
// 500:
// description: Internal Error
// schema: {type: string}
// 401: { description: Invalid API Token }
// default: { description: Unknown Error }
queryIndex, err := strconv.ParseUint(mux.Vars(r)["index"], 10, 64)
if err != nil {
lib.ErrorResponse(w, http.StatusBadRequest, err, errFailedToParseAssetIndex, ctx.Log)
return
}
ledger := ctx.Node.Ledger()
aidx := basics.AssetIndex(queryIndex)
creator, err := ledger.GetAssetCreator(aidx)
if err != nil {
lib.ErrorResponse(w, http.StatusNotFound, err, errFailedToGetAssetCreator, ctx.Log)
return
}
lastRound := ledger.Latest()
record, err := ledger.Lookup(lastRound, creator)
if err != nil {
lib.ErrorResponse(w, http.StatusInternalServerError, err, errFailedLookingUpLedger, ctx.Log)
return
}
if asset, ok := record.AssetParams[aidx]; ok {
thisAssetParams := assetParams(creator, asset)
SendJSON(AssetInformationResponse{&thisAssetParams}, w, ctx.Log)
} else {
lib.ErrorResponse(w, http.StatusBadRequest, fmt.Errorf(errFailedRetrievingAsset), errFailedRetrievingAsset, ctx.Log)
return
}
}
// Assets is an httpHandler for route GET /v1/assets
func Assets(ctx lib.ReqContext, w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v1/assets Assets
// ---
// Summary: List assets
// Description: Returns list of up to `max` assets, where the maximum assetIdx is <= `assetIdx`
// Produces:
// - application/json