-
Notifications
You must be signed in to change notification settings - Fork 451
/
handlers.go
2085 lines (1795 loc) · 74.5 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-2024 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 v2
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"math"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
"golang.org/x/sync/semaphore"
"github.com/algorand/avm-abi/apps"
"github.com/algorand/go-codec/codec"
"github.com/algorand/go-algorand/agreement"
"github.com/algorand/go-algorand/catchup"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/crypto/merklearray"
"github.com/algorand/go-algorand/daemon/algod/api/server/v2/generated/model"
specv2 "github.com/algorand/go-algorand/daemon/algod/api/spec/v2"
"github.com/algorand/go-algorand/data/account"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/data/transactions/logic"
"github.com/algorand/go-algorand/ledger/eval"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/ledger/simulation"
"github.com/algorand/go-algorand/libgoal/participation"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/node"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/rpcs"
"github.com/algorand/go-algorand/stateproof"
)
// MaxTealSourceBytes sets a size limit for TEAL source programs for requests
// Max TEAL program size is currently 8k
// but we allow for comments, spacing, and repeated consts
// in the source TEAL, so we allow up to 200KB
const MaxTealSourceBytes = 200_000
// MaxTealDryrunBytes sets a size limit for dryrun requests
// With the ability to hold unlimited assets DryrunRequests can
// become quite large, so we allow up to 1MB
const MaxTealDryrunBytes = 1_000_000
// MaxAssetResults sets a size limit for the number of assets returned in a single request to the
// /v2/accounts/{address}/assets endpoint
const MaxAssetResults = 1000
// DefaultAssetResults sets a default size limit for the number of assets returned in a single request to the
// /v2/accounts/{address}/assets endpoint
const DefaultAssetResults = uint64(1000)
const (
errInvalidLimit = "limit parameter must be a positive integer"
errUnableToParseNext = "unable to parse next token"
)
// WaitForBlockTimeout is the timeout for the WaitForBlock endpoint.
var WaitForBlockTimeout = 1 * time.Minute
// Handlers is an implementation to the V2 route handler interface defined by the generated code.
type Handlers struct {
Node NodeInterface
Log logging.Logger
Shutdown <-chan struct{}
// KeygenLimiter is used to limit the number of concurrent key generation requests.
KeygenLimiter *semaphore.Weighted
}
// LedgerForAPI describes the Ledger methods used by the v2 API.
type LedgerForAPI interface {
LookupAccount(round basics.Round, addr basics.Address) (ledgercore.AccountData, basics.Round, basics.MicroAlgos, error)
LookupLatest(addr basics.Address) (basics.AccountData, basics.Round, basics.MicroAlgos, error)
LookupKv(round basics.Round, key string) ([]byte, error)
LookupKeysByPrefix(round basics.Round, keyPrefix string, maxKeyNum uint64) ([]string, error)
ConsensusParams(r basics.Round) (config.ConsensusParams, error)
Latest() basics.Round
LookupAsset(rnd basics.Round, addr basics.Address, aidx basics.AssetIndex) (ledgercore.AssetResource, error)
LookupAssets(addr basics.Address, assetIDGT basics.AssetIndex, limit uint64) ([]ledgercore.AssetResourceWithIDs, basics.Round, error)
LookupApplication(rnd basics.Round, addr basics.Address, aidx basics.AppIndex) (ledgercore.AppResource, error)
BlockCert(rnd basics.Round) (blk bookkeeping.Block, cert agreement.Certificate, err error)
LatestTotals() (basics.Round, ledgercore.AccountTotals, error)
BlockHdr(rnd basics.Round) (blk bookkeeping.BlockHeader, err error)
Wait(r basics.Round) chan struct{}
WaitWithCancel(r basics.Round) (chan struct{}, func())
GetCreator(cidx basics.CreatableIndex, ctype basics.CreatableType) (basics.Address, bool, error)
EncodedBlockCert(rnd basics.Round) (blk []byte, cert []byte, err error)
Block(rnd basics.Round) (blk bookkeeping.Block, err error)
AddressTxns(id basics.Address, r basics.Round) ([]transactions.SignedTxnWithAD, error)
GetStateDeltaForRound(rnd basics.Round) (ledgercore.StateDelta, error)
GetTracer() logic.EvalTracer
}
// NodeInterface represents node fns used by the handlers.
type NodeInterface interface {
LedgerForAPI() LedgerForAPI
Status() (s node.StatusReport, err error)
GenesisID() string
GenesisHash() crypto.Digest
BroadcastSignedTxGroup(txgroup []transactions.SignedTxn) error
AsyncBroadcastSignedTxGroup(txgroup []transactions.SignedTxn) error
Simulate(request simulation.Request) (result simulation.Result, err error)
GetPendingTransaction(txID transactions.Txid) (res node.TxnWithStatus, found bool)
GetPendingTxnsFromPool() ([]transactions.SignedTxn, error)
SuggestedFee() basics.MicroAlgos
StartCatchup(catchpoint string) error
AbortCatchup(catchpoint string) error
Config() config.Local
InstallParticipationKey(partKeyBinary []byte) (account.ParticipationID, error)
ListParticipationKeys() ([]account.ParticipationRecord, error)
GetParticipationKey(account.ParticipationID) (account.ParticipationRecord, error)
RemoveParticipationKey(account.ParticipationID) error
AppendParticipationKeys(id account.ParticipationID, keys account.StateProofKeys) error
SetSyncRound(rnd uint64) error
GetSyncRound() uint64
UnsetSyncRound()
GetBlockTimeStampOffset() (*int64, error)
SetBlockTimeStampOffset(int64) error
}
func roundToPtrOrNil(value basics.Round) *uint64 {
if value == 0 {
return nil
}
result := uint64(value)
return &result
}
func convertParticipationRecord(record account.ParticipationRecord) model.ParticipationKey {
participationKey := model.ParticipationKey{
Id: record.ParticipationID.String(),
Address: record.Account.String(),
Key: model.AccountParticipation{
VoteFirstValid: uint64(record.FirstValid),
VoteLastValid: uint64(record.LastValid),
VoteKeyDilution: record.KeyDilution,
},
}
if record.StateProof != nil {
tmp := record.StateProof.Commitment[:]
participationKey.Key.StateProofKey = &tmp
}
// These are pointers but should always be present.
if record.Voting != nil {
participationKey.Key.VoteParticipationKey = record.Voting.OneTimeSignatureVerifier[:]
}
if record.VRF != nil {
participationKey.Key.SelectionParticipationKey = record.VRF.PK[:]
}
// Optional fields.
if record.EffectiveLast != 0 && record.EffectiveFirst == 0 {
// Special case for first valid on round 0
zero := uint64(0)
participationKey.EffectiveFirstValid = &zero
} else {
participationKey.EffectiveFirstValid = roundToPtrOrNil(record.EffectiveFirst)
}
participationKey.EffectiveLastValid = roundToPtrOrNil(record.EffectiveLast)
participationKey.LastVote = roundToPtrOrNil(record.LastVote)
participationKey.LastBlockProposal = roundToPtrOrNil(record.LastBlockProposal)
participationKey.LastVote = roundToPtrOrNil(record.LastVote)
participationKey.LastStateProof = roundToPtrOrNil(record.LastStateProof)
return participationKey
}
// ErrNoStateProofForRound returned when a state proof transaction could not be found
var ErrNoStateProofForRound = errors.New("no state proof can be found for that round")
// ErrTimeout indicates a task took too long, and the server canceled it.
var ErrTimeout = errors.New("timed out on request")
// ErrShutdown represents the error for the string errServiceShuttingDown
var ErrShutdown = errors.New(errServiceShuttingDown)
// GetStateProofTransactionForRound searches for a state proof transaction that can be used to prove on the given round (i.e the round is within the
// attestation period). the latestRound should be provided as an upper bound for the search
func GetStateProofTransactionForRound(ctx context.Context, txnFetcher LedgerForAPI, round, latestRound basics.Round, stop <-chan struct{}) (transactions.Transaction, error) {
hdr, err := txnFetcher.BlockHdr(round)
if err != nil {
return transactions.Transaction{}, err
}
if config.Consensus[hdr.CurrentProtocol].StateProofInterval == 0 {
return transactions.Transaction{}, ErrNoStateProofForRound
}
for i := round + 1; i <= latestRound; i++ {
select {
case <-stop:
return transactions.Transaction{}, ErrShutdown
case <-ctx.Done():
return transactions.Transaction{}, ErrTimeout
default:
}
txns, err := txnFetcher.AddressTxns(transactions.StateProofSender, i)
if err != nil {
return transactions.Transaction{}, err
}
for _, txn := range txns {
if txn.Txn.Type != protocol.StateProofTx {
continue
}
if txn.Txn.StateProofTxnFields.Message.FirstAttestedRound <= uint64(round) &&
uint64(round) <= txn.Txn.StateProofTxnFields.Message.LastAttestedRound {
return txn.Txn, nil
}
}
}
return transactions.Transaction{}, ErrNoStateProofForRound
}
// GetParticipationKeys Return a list of participation keys
// (GET /v2/participation)
func (v2 *Handlers) GetParticipationKeys(ctx echo.Context) error {
partKeys, err := v2.Node.ListParticipationKeys()
if err != nil {
return badRequest(ctx, err, err.Error(), v2.Log)
}
var response []model.ParticipationKey
for _, participationRecord := range partKeys {
response = append(response, convertParticipationRecord(participationRecord))
}
return ctx.JSON(http.StatusOK, response)
}
func (v2 *Handlers) generateKeyHandler(address string, params model.GenerateParticipationKeysParams) error {
installFunc := func(path string) error {
bytes, err := os.ReadFile(path)
if err != nil {
return err
}
partKeyBinary := bytes
if len(partKeyBinary) == 0 {
return fmt.Errorf("cannot install partkey '%s' is empty", partKeyBinary)
}
partID, err := v2.Node.InstallParticipationKey(partKeyBinary)
v2.Log.Infof("Installed participation key %s", partID)
return err
}
_, _, err := participation.GenParticipationKeysTo(address, params.First, params.Last, nilToZero(params.Dilution), "", installFunc)
return err
}
// GenerateParticipationKeys generates and installs participation keys to the node.
// (POST /v2/participation/generate/{address})
func (v2 *Handlers) GenerateParticipationKeys(ctx echo.Context, address string, params model.GenerateParticipationKeysParams) error {
if !v2.KeygenLimiter.TryAcquire(1) {
err := fmt.Errorf("participation key generation already in progress")
return badRequest(ctx, err, err.Error(), v2.Log)
}
// Semaphore was acquired, generate the key.
go func() {
defer v2.KeygenLimiter.Release(1)
err := v2.generateKeyHandler(address, params)
if err != nil {
v2.Log.Warnf("Error generating participation keys: %v", err)
}
}()
// Empty object. In the future we may want to add a field for the participation ID.
return ctx.String(http.StatusOK, "{}")
}
// AddParticipationKey Add a participation key to the node
// (POST /v2/participation)
func (v2 *Handlers) AddParticipationKey(ctx echo.Context) error {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(ctx.Request().Body)
if err != nil {
return badRequest(ctx, err, err.Error(), v2.Log)
}
partKeyBinary := buf.Bytes()
if len(partKeyBinary) == 0 {
lenErr := fmt.Errorf(errRESTPayloadZeroLength)
return badRequest(ctx, lenErr, lenErr.Error(), v2.Log)
}
partID, err := v2.Node.InstallParticipationKey(partKeyBinary)
if err != nil {
return badRequest(ctx, err, err.Error(), v2.Log)
}
response := model.PostParticipationResponse{PartId: partID.String()}
return ctx.JSON(http.StatusOK, response)
}
// DeleteParticipationKeyByID Delete a given participation key by id
// (DELETE /v2/participation/{participation-id})
func (v2 *Handlers) DeleteParticipationKeyByID(ctx echo.Context, participationID string) error {
decodedParticipationID, err := account.ParseParticipationID(participationID)
if err != nil {
return badRequest(ctx, err, err.Error(), v2.Log)
}
err = v2.Node.RemoveParticipationKey(decodedParticipationID)
if err != nil {
if errors.Is(err, account.ErrParticipationIDNotFound) {
return notFound(ctx, account.ErrParticipationIDNotFound, "participation id not found", v2.Log)
}
return internalError(ctx, err, err.Error(), v2.Log)
}
return ctx.NoContent(http.StatusOK)
}
// GetParticipationKeyByID Get participation key info by id
// (GET /v2/participation/{participation-id})
func (v2 *Handlers) GetParticipationKeyByID(ctx echo.Context, participationID string) error {
decodedParticipationID, err := account.ParseParticipationID(participationID)
if err != nil {
return badRequest(ctx, err, err.Error(), v2.Log)
}
participationRecord, err := v2.Node.GetParticipationKey(decodedParticipationID)
if err != nil {
return internalError(ctx, err, err.Error(), v2.Log)
}
if participationRecord.IsZero() {
return notFound(ctx, account.ErrParticipationIDNotFound, account.ErrParticipationIDNotFound.Error(), v2.Log)
}
response := convertParticipationRecord(participationRecord)
return ctx.JSON(http.StatusOK, response)
}
// AppendKeys Append state proof keys to a participation key
// (POST /v2/participation/{participation-id})
func (v2 *Handlers) AppendKeys(ctx echo.Context, participationID string) error {
decodedParticipationID, err := account.ParseParticipationID(participationID)
if err != nil {
return badRequest(ctx, err, err.Error(), v2.Log)
}
var keys account.StateProofKeys
dec := protocol.NewDecoder(ctx.Request().Body)
err = dec.Decode(&keys)
if err != nil {
err = fmt.Errorf("unable to parse keys from body: %w", err)
return badRequest(ctx, err, err.Error(), v2.Log)
}
if len(keys) == 0 {
err = errors.New("empty request, please attach keys to request body")
return badRequest(ctx, err, err.Error(), v2.Log)
}
err = v2.Node.AppendParticipationKeys(decodedParticipationID, keys)
if err != nil {
return internalError(ctx, err, err.Error(), v2.Log)
}
return nil
}
// ShutdownNode shuts down the node.
// (POST /v2/shutdown)
func (v2 *Handlers) ShutdownNode(ctx echo.Context, params model.ShutdownNodeParams) error {
// TODO: shutdown endpoint
return ctx.String(http.StatusNotImplemented, "Endpoint not implemented.")
}
// AccountInformation gets account information for a given account.
// (GET /v2/accounts/{address})
func (v2 *Handlers) AccountInformation(ctx echo.Context, address string, params model.AccountInformationParams) error {
handle, contentType, err := getCodecHandle((*string)(params.Format))
if err != nil {
return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
}
addr, err := basics.UnmarshalChecksumAddress(address)
if err != nil {
return badRequest(ctx, err, errFailedToParseAddress, v2.Log)
}
// should we skip fetching apps and assets?
if params.Exclude != nil {
switch *params.Exclude {
case "all":
return v2.basicAccountInformation(ctx, addr, handle, contentType)
case "none", "":
default:
return badRequest(ctx, err, errFailedToParseExclude, v2.Log)
}
}
myLedger := v2.Node.LedgerForAPI()
// count total # of resources, if max limit is set
if maxResults := v2.Node.Config().MaxAPIResourcesPerAccount; maxResults != 0 {
record, _, _, lookupErr := myLedger.LookupAccount(myLedger.Latest(), addr)
if lookupErr != nil {
return internalError(ctx, lookupErr, errFailedLookingUpLedger, v2.Log)
}
totalResults := record.TotalAssets + record.TotalAssetParams + record.TotalAppLocalStates + record.TotalAppParams
if totalResults > maxResults {
v2.Log.Infof("MaxAccountAPIResults limit %d exceeded, total results %d", maxResults, totalResults)
extraData := map[string]interface{}{
"max-results": maxResults,
"total-assets-opted-in": record.TotalAssets,
"total-created-assets": record.TotalAssetParams,
"total-apps-opted-in": record.TotalAppLocalStates,
"total-created-apps": record.TotalAppParams,
}
return ctx.JSON(http.StatusBadRequest, model.ErrorResponse{
Message: "Result limit exceeded",
Data: &extraData,
})
}
}
record, lastRound, amountWithoutPendingRewards, err := myLedger.LookupLatest(addr)
if err != nil {
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
// check against configured total limit on assets/apps
if handle == protocol.CodecHandle {
data, err := encode(handle, record)
if err != nil {
return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
}
return ctx.Blob(http.StatusOK, contentType, data)
}
consensus, err := myLedger.ConsensusParams(lastRound)
if err != nil {
return internalError(ctx, err, fmt.Sprintf("could not retrieve consensus information for last round (%d)", lastRound), v2.Log)
}
account, err := AccountDataToAccount(address, &record, lastRound, &consensus, amountWithoutPendingRewards)
if err != nil {
return internalError(ctx, err, errInternalFailure, v2.Log)
}
response := model.AccountResponse(account)
return ctx.JSON(http.StatusOK, response)
}
// basicAccountInformation handles the case when no resources (assets or apps) are requested.
func (v2 *Handlers) basicAccountInformation(ctx echo.Context, addr basics.Address, handle codec.Handle, contentType string) error {
myLedger := v2.Node.LedgerForAPI()
record, lastRound, amountWithoutPendingRewards, err := myLedger.LookupAccount(myLedger.Latest(), addr)
if err != nil {
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
if handle == protocol.CodecHandle {
data, encErr := encode(handle, record)
if encErr != nil {
return internalError(ctx, encErr, errFailedToEncodeResponse, v2.Log)
}
return ctx.Blob(http.StatusOK, contentType, data)
}
consensus, err := myLedger.ConsensusParams(lastRound)
if err != nil {
return internalError(ctx, err, fmt.Sprintf("could not retrieve consensus information for last round (%d)", lastRound), v2.Log)
}
var apiParticipation *model.AccountParticipation
if !record.VoteID.IsEmpty() {
apiParticipation = &model.AccountParticipation{
VoteParticipationKey: record.VoteID[:],
SelectionParticipationKey: record.SelectionID[:],
VoteFirstValid: uint64(record.VoteFirstValid),
VoteLastValid: uint64(record.VoteLastValid),
VoteKeyDilution: uint64(record.VoteKeyDilution),
}
if !record.StateProofID.IsEmpty() {
tmp := record.StateProofID[:]
apiParticipation.StateProofKey = &tmp
}
}
pendingRewards, overflowed := basics.OSubA(record.MicroAlgos, amountWithoutPendingRewards)
if overflowed {
return internalError(ctx, errors.New("overflow on pending reward calculation"), errInternalFailure, v2.Log)
}
account := model.Account{
SigType: nil,
Round: uint64(lastRound),
Address: addr.String(),
Amount: record.MicroAlgos.Raw,
PendingRewards: pendingRewards.Raw,
AmountWithoutPendingRewards: amountWithoutPendingRewards.Raw,
Rewards: record.RewardedMicroAlgos.Raw,
Status: record.Status.String(),
RewardBase: &record.RewardsBase,
Participation: apiParticipation,
IncentiveEligible: omitEmpty(record.IncentiveEligible),
TotalCreatedAssets: record.TotalAssetParams,
TotalCreatedApps: record.TotalAppParams,
TotalAssetsOptedIn: record.TotalAssets,
AuthAddr: addrOrNil(record.AuthAddr),
TotalAppsOptedIn: record.TotalAppLocalStates,
AppsTotalSchema: &model.ApplicationStateSchema{
NumByteSlice: record.TotalAppSchema.NumByteSlice,
NumUint: record.TotalAppSchema.NumUint,
},
AppsTotalExtraPages: omitEmpty(uint64(record.TotalExtraAppPages)),
TotalBoxes: omitEmpty(record.TotalBoxes),
TotalBoxBytes: omitEmpty(record.TotalBoxBytes),
MinBalance: record.MinBalance(&consensus).Raw,
LastProposed: omitEmpty(uint64(record.LastProposed)),
LastHeartbeat: omitEmpty(uint64(record.LastHeartbeat)),
}
response := model.AccountResponse(account)
return ctx.JSON(http.StatusOK, response)
}
// AccountAssetInformation gets account information about a given asset.
// (GET /v2/accounts/{address}/assets/{asset-id})
func (v2 *Handlers) AccountAssetInformation(ctx echo.Context, address string, assetID uint64, params model.AccountAssetInformationParams) error {
handle, contentType, err := getCodecHandle((*string)(params.Format))
if err != nil {
return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
}
addr, err := basics.UnmarshalChecksumAddress(address)
if err != nil {
return badRequest(ctx, err, errFailedToParseAddress, v2.Log)
}
ledger := v2.Node.LedgerForAPI()
lastRound := ledger.Latest()
record, err := ledger.LookupAsset(lastRound, addr, basics.AssetIndex(assetID))
if err != nil {
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
if record.AssetParams == nil && record.AssetHolding == nil {
return notFound(ctx, errors.New(errAccountAssetDoesNotExist), errAccountAssetDoesNotExist, v2.Log)
}
// return msgpack response
if handle == protocol.CodecHandle {
data, err := encode(handle, specv2.AssetResourceToAccountAssetModel(record))
if err != nil {
return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
}
return ctx.Blob(http.StatusOK, contentType, data)
}
// prepare JSON response
response := model.AccountAssetResponse{Round: uint64(lastRound)}
if record.AssetParams != nil {
asset := AssetParamsToAsset(addr.String(), basics.AssetIndex(assetID), record.AssetParams)
response.CreatedAsset = &asset.Params
}
if record.AssetHolding != nil {
response.AssetHolding = &model.AssetHolding{
Amount: record.AssetHolding.Amount,
AssetID: uint64(assetID),
IsFrozen: record.AssetHolding.Frozen,
}
}
return ctx.JSON(http.StatusOK, response)
}
// AccountApplicationInformation gets account information about a given app.
// (GET /v2/accounts/{address}/applications/{application-id})
func (v2 *Handlers) AccountApplicationInformation(ctx echo.Context, address string, applicationID uint64, params model.AccountApplicationInformationParams) error {
handle, contentType, err := getCodecHandle((*string)(params.Format))
if err != nil {
return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
}
addr, err := basics.UnmarshalChecksumAddress(address)
if err != nil {
return badRequest(ctx, err, errFailedToParseAddress, v2.Log)
}
ledger := v2.Node.LedgerForAPI()
lastRound := ledger.Latest()
record, err := ledger.LookupApplication(lastRound, addr, basics.AppIndex(applicationID))
if err != nil {
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
if record.AppParams == nil && record.AppLocalState == nil {
return notFound(ctx, errors.New(errAccountAppDoesNotExist), errAccountAppDoesNotExist, v2.Log)
}
// return msgpack response
if handle == protocol.CodecHandle {
data, err := encode(handle, specv2.AppResourceToAccountApplicationModel(record))
if err != nil {
return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
}
return ctx.Blob(http.StatusOK, contentType, data)
}
// prepare JSON response
response := model.AccountApplicationResponse{Round: uint64(lastRound)}
if record.AppParams != nil {
app := AppParamsToApplication(addr.String(), basics.AppIndex(applicationID), record.AppParams)
response.CreatedApp = &app.Params
}
if record.AppLocalState != nil {
localState := convertTKVToGenerated(&record.AppLocalState.KeyValue)
response.AppLocalState = &model.ApplicationLocalState{
Id: uint64(applicationID),
KeyValue: localState,
Schema: model.ApplicationStateSchema{
NumByteSlice: record.AppLocalState.Schema.NumByteSlice,
NumUint: record.AppLocalState.Schema.NumUint,
},
}
}
return ctx.JSON(http.StatusOK, response)
}
// GetBlock gets the block for the given round.
// (GET /v2/blocks/{round})
func (v2 *Handlers) GetBlock(ctx echo.Context, round uint64, params model.GetBlockParams) error {
handle, contentType, err := getCodecHandle((*string)(params.Format))
if err != nil {
return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
}
// msgpack format uses 'RawBlockBytes' and attaches a custom header.
if handle == protocol.CodecHandle {
blockbytes, blockErr := rpcs.RawBlockBytes(v2.Node.LedgerForAPI(), basics.Round(round))
if blockErr != nil {
switch blockErr.(type) {
case ledgercore.ErrNoEntry:
return notFound(ctx, blockErr, errFailedLookingUpLedger, v2.Log)
default:
return internalError(ctx, blockErr, blockErr.Error(), v2.Log)
}
}
ctx.Response().Writer.Header().Add("X-Algorand-Struct", "block-v1")
return ctx.Blob(http.StatusOK, contentType, blockbytes)
}
ledger := v2.Node.LedgerForAPI()
block, err := ledger.Block(basics.Round(round))
if err != nil {
switch err.(type) {
case ledgercore.ErrNoEntry:
return notFound(ctx, err, errFailedLookingUpLedger, v2.Log)
default:
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
}
// Encoding wasn't working well without embedding "real" objects.
response := struct {
Block bookkeeping.Block `codec:"block"`
}{
Block: block,
}
data, err := encode(handle, response)
if err != nil {
return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
}
return ctx.Blob(http.StatusOK, contentType, data)
}
// GetBlockTxids gets all top level TxIDs in a block for the given round.
// (GET /v2/blocks/{round}/txids)
func (v2 *Handlers) GetBlockTxids(ctx echo.Context, round uint64) error {
ledger := v2.Node.LedgerForAPI()
block, err := ledger.Block(basics.Round(round))
if err != nil {
switch err.(type) {
case ledgercore.ErrNoEntry:
return notFound(ctx, err, errFailedLookingUpLedger, v2.Log)
default:
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
}
txns, err := block.DecodePaysetFlat()
if err != nil {
return internalError(ctx, err, "decoding transactions", v2.Log)
}
txids := make([]string, 0, len(txns))
for ids := range txns {
txids = append(txids, txns[ids].ID().String())
}
response := model.BlockTxidsResponse{BlockTxids: txids}
return ctx.JSON(http.StatusOK, response)
}
// NewAppCallLogs generates a new model.AppCallLogs struct.
func NewAppCallLogs(txid string, logs []string, appIndex uint64) model.AppCallLogs {
return model.AppCallLogs{
TxId: txid,
Logs: convertSlice(logs, func(s string) []byte { return []byte(s) }),
ApplicationIndex: appIndex,
}
}
func getAppIndexFromTxn(txn transactions.SignedTxnWithAD) uint64 {
appIndex := uint64(txn.SignedTxn.Txn.ApplicationID)
if appIndex == 0 {
appIndex = uint64(txn.ApplyData.ApplicationID)
}
return appIndex
}
func appendLogsFromTxns(blockLogs []model.AppCallLogs, txns []transactions.SignedTxnWithAD, outerTxnID string) []model.AppCallLogs {
for _, txn := range txns {
if len(txn.EvalDelta.Logs) > 0 {
blockLogs = append(
blockLogs,
NewAppCallLogs(outerTxnID, txn.EvalDelta.Logs, getAppIndexFromTxn(txn)),
)
}
blockLogs = appendLogsFromTxns(blockLogs, txn.EvalDelta.InnerTxns, outerTxnID)
}
return blockLogs
}
// GetBlockLogs gets all of the logs (inner and outer app calls) for a given block
// (GET /v2/blocks/{round}/logs)
func (v2 *Handlers) GetBlockLogs(ctx echo.Context, round uint64) error {
ledger := v2.Node.LedgerForAPI()
block, err := ledger.Block(basics.Round(round))
if err != nil {
switch err.(type) {
case ledgercore.ErrNoEntry:
return notFound(ctx, err, errFailedLookingUpLedger, v2.Log)
default:
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
}
txns, err := block.DecodePaysetFlat()
if err != nil {
return internalError(ctx, err, "decoding transactions", v2.Log)
}
blockLogs := []model.AppCallLogs{}
for _, txn := range txns {
blockLogs = appendLogsFromTxns(blockLogs, []transactions.SignedTxnWithAD{txn}, txn.ID().String())
}
response := model.BlockLogsResponse{Logs: blockLogs}
return ctx.JSON(http.StatusOK, response)
}
// GetBlockHash gets the block hash for the given round.
// (GET /v2/blocks/{round}/hash)
func (v2 *Handlers) GetBlockHash(ctx echo.Context, round uint64) error {
ledger := v2.Node.LedgerForAPI()
block, err := ledger.Block(basics.Round(round))
if err != nil {
switch err.(type) {
case ledgercore.ErrNoEntry:
return notFound(ctx, err, errFailedLookingUpLedger, v2.Log)
default:
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
}
response := model.BlockHashResponse{BlockHash: crypto.Digest(block.Hash()).String()}
return ctx.JSON(http.StatusOK, response)
}
// GetTransactionProof generates a Merkle proof for a transaction in a block.
// (GET /v2/blocks/{round}/transactions/{txid}/proof)
func (v2 *Handlers) GetTransactionProof(ctx echo.Context, round uint64, txid string, params model.GetTransactionProofParams) error {
var txID transactions.Txid
err := txID.UnmarshalText([]byte(txid))
if err != nil {
return badRequest(ctx, err, errNoValidTxnSpecified, v2.Log)
}
if params.Hashtype != nil && *params.Hashtype != "sha512_256" && *params.Hashtype != "sha256" {
return badRequest(ctx, nil, errInvalidHashType, v2.Log)
}
ledger := v2.Node.LedgerForAPI()
block, err := ledger.Block(basics.Round(round))
if err != nil {
return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
}
proto := config.Consensus[block.CurrentProtocol]
if proto.PaysetCommit != config.PaysetCommitMerkle {
return notFound(ctx, err, "protocol does not support Merkle proofs", v2.Log)
}
hashtype := "sha512_256" // default hash type for proof
if params.Hashtype != nil {
hashtype = string(*params.Hashtype)
}
if hashtype == "sha256" && !proto.EnableSHA256TxnCommitmentHeader {
return badRequest(ctx, err, "protocol does not support sha256 vector commitment proofs", v2.Log)
}
txns, err := block.DecodePaysetFlat()
if err != nil {
return internalError(ctx, err, "decoding transactions", v2.Log)
}
for idx := range txns {
if txns[idx].ID() != txID {
continue // skip
}
var tree *merklearray.Tree
var stibhash crypto.Digest
switch hashtype {
case "sha256":
tree, err = block.TxnMerkleTreeSHA256()
if err != nil {
return internalError(ctx, err, "building Vector Commitment (SHA256)", v2.Log)
}
stibhash = block.Payset[idx].HashSHA256()
case "sha512_256":
tree, err = block.TxnMerkleTree()
if err != nil {
return internalError(ctx, err, "building Merkle tree", v2.Log)
}
stibhash = block.Payset[idx].Hash()
default:
return badRequest(ctx, err, "unsupported hash type", v2.Log)
}
proof, proofErr := tree.ProveSingleLeaf(uint64(idx))
if proofErr != nil {
return internalError(ctx, proofErr, "generating proof", v2.Log)
}
response := model.TransactionProofResponse{
Proof: proof.GetConcatenatedProof(),
Stibhash: stibhash[:],
Idx: uint64(idx),
Treedepth: uint64(proof.TreeDepth),
Hashtype: model.TransactionProofResponseHashtype(hashtype),
}
return ctx.JSON(http.StatusOK, response)
}
err = errors.New(errTransactionNotFound)
return notFound(ctx, err, err.Error(), v2.Log)
}
// GetSupply gets the current supply reported by the ledger.
// (GET /v2/ledger/supply)
func (v2 *Handlers) GetSupply(ctx echo.Context) error {
latest, totals, err := v2.Node.LedgerForAPI().LatestTotals()
if err != nil {
err = fmt.Errorf("GetSupply(): round %d, failed: %v", latest, err)
return internalError(ctx, err, errInternalFailure, v2.Log)
}
supply := model.SupplyResponse{
CurrentRound: uint64(latest),
TotalMoney: totals.Participating().Raw,
OnlineMoney: totals.Online.Money.Raw,
}
return ctx.JSON(http.StatusOK, supply)
}
// GetStatus gets the current node status.
// (GET /v2/status)
func (v2 *Handlers) GetStatus(ctx echo.Context) error {
stat, err := v2.Node.Status()
if err != nil {
return internalError(ctx, err, errFailedRetrievingNodeStatus, v2.Log)
}
response := model.NodeStatusResponse{
LastRound: uint64(stat.LastRound),
LastVersion: string(stat.LastVersion),
NextVersion: string(stat.NextVersion),
NextVersionRound: uint64(stat.NextVersionRound),
NextVersionSupported: stat.NextVersionSupported,
TimeSinceLastRound: uint64(stat.TimeSinceLastRound().Nanoseconds()),
CatchupTime: uint64(stat.CatchupTime.Nanoseconds()),
StoppedAtUnsupportedRound: stat.StoppedAtUnsupportedRound,
LastCatchpoint: &stat.LastCatchpoint,
Catchpoint: &stat.Catchpoint,
CatchpointTotalAccounts: &stat.CatchpointCatchupTotalAccounts,
CatchpointProcessedAccounts: &stat.CatchpointCatchupProcessedAccounts,
CatchpointVerifiedAccounts: &stat.CatchpointCatchupVerifiedAccounts,
CatchpointTotalKvs: &stat.CatchpointCatchupTotalKVs,
CatchpointProcessedKvs: &stat.CatchpointCatchupProcessedKVs,
CatchpointVerifiedKvs: &stat.CatchpointCatchupVerifiedKVs,
CatchpointTotalBlocks: &stat.CatchpointCatchupTotalBlocks,
CatchpointAcquiredBlocks: &stat.CatchpointCatchupAcquiredBlocks,
}
// Make sure a vote is happening
if stat.NextProtocolVoteBefore > 0 {
votesToGo := uint64(0)
// Check if the vote window is still open.
if stat.NextProtocolVoteBefore > stat.LastRound {
// subtract 1 because the variables are referring to "Last" round and "VoteBefore"
votesToGo = uint64(stat.NextProtocolVoteBefore - stat.LastRound - 1)
}
consensus := config.Consensus[protocol.ConsensusCurrentVersion]
upgradeVoteRounds := consensus.UpgradeVoteRounds
upgradeThreshold := consensus.UpgradeThreshold
votes := consensus.UpgradeVoteRounds - votesToGo
votesYes := stat.NextProtocolApprovals
votesNo := votes - votesYes
upgradeDelay := stat.UpgradeDelay
response.UpgradeVotesRequired = &upgradeThreshold
response.UpgradeNodeVote = &stat.UpgradeApprove
response.UpgradeDelay = &upgradeDelay
response.UpgradeVotes = &votes
response.UpgradeYesVotes = &votesYes
response.UpgradeNoVotes = &votesNo
response.UpgradeNextProtocolVoteBefore = omitEmpty(uint64(stat.NextProtocolVoteBefore))
response.UpgradeVoteRounds = &upgradeVoteRounds
}
return ctx.JSON(http.StatusOK, response)
}
// WaitForBlock returns the node status after waiting for the given round.
// (GET /v2/status/wait-for-block-after/{round}/)
func (v2 *Handlers) WaitForBlock(ctx echo.Context, round uint64) error {
ledger := v2.Node.LedgerForAPI()
stat, err := v2.Node.Status()
if err != nil {