summaryrefslogtreecommitdiff
path: root/daemon/algod/api/server/v2/handlers.go
blob: 0282594f4f5dda6281e682f10414f3a7f95e3f47 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
// Copyright (C) 2019-2023 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"
	"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

// 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)
	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 != (crypto.OneTimeSignatureVerifier{}) {
		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,
		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,
	}
	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)
}

// 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 {
		return internalError(ctx, err, errFailedRetrievingNodeStatus, v2.Log)
	}
	if stat.StoppedAtUnsupportedRound {
		return badRequest(ctx, err, errRequestedRoundInUnsupportedRound, v2.Log)
	}
	if stat.Catchpoint != "" {
		// node is currently catching up to the requested catchpoint.
		return serviceUnavailable(ctx, fmt.Errorf("WaitForBlock failed as the node was catchpoint catchuping"), errOperationNotAvailableDuringCatchup, v2.Log)
	}

	latestBlkHdr, err := ledger.BlockHdr(ledger.Latest())
	if err != nil {
		return internalError(ctx, err, errFailedRetrievingLatestBlockHeaderStatus, v2.Log)
	}
	if latestBlkHdr.NextProtocol != "" {
		if _, nextProtocolSupported := config.Consensus[latestBlkHdr.NextProtocol]; !nextProtocolSupported {
			// see if the desired protocol switch is expect to happen before or after the above point.
			if latestBlkHdr.NextProtocolSwitchOn <= basics.Round(round+1) {
				// we would never reach to this round, since this round would happen after the (unsupported) protocol upgrade.
				return badRequest(ctx, err, errRequestedRoundInUnsupportedRound, v2.Log)
			}
		}
	}

	// Wait
	ledgerWaitCh, cancelLedgerWait := ledger.WaitWithCancel(basics.Round(round + 1))
	defer cancelLedgerWait()
	select {
	case <-v2.Shutdown:
		return internalError(ctx, err, errServiceShuttingDown, v2.Log)
	case <-ctx.Request().Context().Done():
		return ctx.NoContent(http.StatusRequestTimeout)
	case <-time.After(WaitForBlockTimeout):
	case <-ledgerWaitCh:
	}

	// Return status after the wait
	return v2.GetStatus(ctx)
}

// decodeTxGroup attempts to decode a request body containing a transaction group.
func decodeTxGroup(body io.Reader, maxTxGroupSize int) ([]transactions.SignedTxn, error) {
	var txgroup []transactions.SignedTxn
	dec := protocol.NewDecoder(body)
	for {
		var st transactions.SignedTxn
		err := dec.Decode(&st)
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
		txgroup = append(txgroup, st)

		if len(txgroup) > maxTxGroupSize {
			err := fmt.Errorf("max group size is %d", maxTxGroupSize)
			return nil, err
		}
	}

	if len(txgroup) == 0 {
		return nil, errors.New("empty txgroup")
	}

	return txgroup, nil
}

// RawTransaction broadcasts a raw transaction to the network.
// (POST /v2/transactions)
func (v2 *Handlers) RawTransaction(ctx echo.Context) error {
	stat, err := v2.Node.Status()
	if err != nil {
		return internalError(ctx, err, errFailedRetrievingNodeStatus, v2.Log)
	}
	if stat.Catchpoint != "" {
		// node is currently catching up to the requested catchpoint.
		return serviceUnavailable(ctx, fmt.Errorf("RawTransaction failed as the node was catchpoint catchuping"), errOperationNotAvailableDuringCatchup, v2.Log)
	}
	proto := config.Consensus[stat.LastVersion]

	txgroup, err := decodeTxGroup(ctx.Request().Body, proto.MaxTxGroupSize)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}

	err = v2.Node.BroadcastSignedTxGroup(txgroup)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}

	// For backwards compatibility, return txid of first tx in group
	txid := txgroup[0].ID()
	return ctx.JSON(http.StatusOK, model.PostTransactionsResponse{TxId: txid.String()})
}

// RawTransactionAsync broadcasts a raw transaction to the network without ensuring it is accepted by transaction pool.
// (POST /v2/transactions/async)
func (v2 *Handlers) RawTransactionAsync(ctx echo.Context) error {
	if !v2.Node.Config().EnableExperimentalAPI {
		return ctx.String(http.StatusNotFound, "/transactions/async was not enabled in the configuration file by setting the EnableExperimentalAPI to true")
	}
	txgroup, err := decodeTxGroup(ctx.Request().Body, config.MaxTxGroupSize)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}
	err = v2.Node.AsyncBroadcastSignedTxGroup(txgroup)
	if err != nil {
		return serviceUnavailable(ctx, err, err.Error(), v2.Log)
	}
	return ctx.NoContent(http.StatusOK)
}

// PreEncodedSimulateTxnResult mirrors model.SimulateTransactionResult
type PreEncodedSimulateTxnResult struct {
	Txn                      PreEncodedTxInfo                        `codec:"txn-result"`
	AppBudgetConsumed        *uint64                                 `codec:"app-budget-consumed,omitempty"`
	LogicSigBudgetConsumed   *uint64                                 `codec:"logic-sig-budget-consumed,omitempty"`
	TransactionTrace         *model.SimulationTransactionExecTrace   `codec:"exec-trace,omitempty"`
	UnnamedResourcesAccessed *model.SimulateUnnamedResourcesAccessed `codec:"unnamed-resources-accessed,omitempty"`
}

// PreEncodedSimulateTxnGroupResult mirrors model.SimulateTransactionGroupResult
type PreEncodedSimulateTxnGroupResult struct {
	AppBudgetAdded           *uint64                                 `codec:"app-budget-added,omitempty"`
	AppBudgetConsumed        *uint64                                 `codec:"app-budget-consumed,omitempty"`
	FailedAt                 *[]uint64                               `codec:"failed-at,omitempty"`
	FailureMessage           *string                                 `codec:"failure-message,omitempty"`
	UnnamedResourcesAccessed *model.SimulateUnnamedResourcesAccessed `codec:"unnamed-resources-accessed,omitempty"`
	Txns                     []PreEncodedSimulateTxnResult           `codec:"txn-results"`
}

// PreEncodedSimulateResponse mirrors model.SimulateResponse
type PreEncodedSimulateResponse struct {
	Version         uint64                             `codec:"version"`
	LastRound       uint64                             `codec:"last-round"`
	TxnGroups       []PreEncodedSimulateTxnGroupResult `codec:"txn-groups"`
	EvalOverrides   *model.SimulationEvalOverrides     `codec:"eval-overrides,omitempty"`
	ExecTraceConfig simulation.ExecTraceConfig         `codec:"exec-trace-config,omitempty"`
	InitialStates   *model.SimulateInitialStates       `codec:"initial-states,omitempty"`
}

// PreEncodedSimulateRequestTransactionGroup mirrors model.SimulateRequestTransactionGroup
type PreEncodedSimulateRequestTransactionGroup struct {
	Txns []transactions.SignedTxn `codec:"txns"`
}

// PreEncodedSimulateRequest mirrors model.SimulateRequest
type PreEncodedSimulateRequest struct {
	TxnGroups             []PreEncodedSimulateRequestTransactionGroup `codec:"txn-groups"`
	Round                 basics.Round                                `codec:"round,omitempty"`
	AllowEmptySignatures  bool                                        `codec:"allow-empty-signatures,omitempty"`
	AllowMoreLogging      bool                                        `codec:"allow-more-logging,omitempty"`
	AllowUnnamedResources bool                                        `codec:"allow-unnamed-resources,omitempty"`
	ExtraOpcodeBudget     uint64                                      `codec:"extra-opcode-budget,omitempty"`
	ExecTraceConfig       simulation.ExecTraceConfig                  `codec:"exec-trace-config,omitempty"`
}

// SimulateTransaction simulates broadcasting a raw transaction to the network, returning relevant simulation results.
// (POST /v2/transactions/simulate)
func (v2 *Handlers) SimulateTransaction(ctx echo.Context, params model.SimulateTransactionParams) error {
	stat, err := v2.Node.Status()
	if err != nil {
		return internalError(ctx, err, errFailedRetrievingNodeStatus, v2.Log)
	}
	if stat.Catchpoint != "" {
		// node is currently catching up to the requested catchpoint.
		return serviceUnavailable(ctx, fmt.Errorf("SimulateTransaction failed as the node was catchpoint catchuping"), errOperationNotAvailableDuringCatchup, v2.Log)
	}
	proto := config.Consensus[stat.LastVersion]

	requestBuffer := new(bytes.Buffer)
	requestBodyReader := http.MaxBytesReader(nil, ctx.Request().Body, MaxTealDryrunBytes)
	_, err = requestBuffer.ReadFrom(requestBodyReader)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}
	requestData := requestBuffer.Bytes()

	var simulateRequest PreEncodedSimulateRequest
	err = decode(protocol.CodecHandle, requestData, &simulateRequest)
	if err != nil {
		err = decode(protocol.JSONStrictHandle, requestData, &simulateRequest)
		if err != nil {
			return badRequest(ctx, err, err.Error(), v2.Log)
		}
	}

	for _, txgroup := range simulateRequest.TxnGroups {
		if len(txgroup.Txns) == 0 {
			err = errors.New("empty txgroup")
			return badRequest(ctx, err, err.Error(), v2.Log)
		}
		if len(txgroup.Txns) > proto.MaxTxGroupSize {
			err = fmt.Errorf("transaction group size %d exceeds protocol max %d", len(txgroup.Txns), proto.MaxTxGroupSize)
			return badRequest(ctx, err, err.Error(), v2.Log)
		}
	}

	// Simulate transaction
	simulationResult, err := v2.Node.Simulate(convertSimulationRequest(simulateRequest))
	if err != nil {
		var invalidTxErr simulation.InvalidRequestError
		switch {
		case errors.As(err, &invalidTxErr):
			return badRequest(ctx, invalidTxErr, invalidTxErr.Error(), v2.Log)
		default:
			return internalError(ctx, err, err.Error(), v2.Log)
		}
	}

	response := convertSimulationResult(simulationResult)

	handle, contentType, err := getCodecHandle((*string)(params.Format))
	if err != nil {
		return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
	}
	responseData, err := encode(handle, &response)
	if err != nil {
		return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
	}

	return ctx.Blob(http.StatusOK, contentType, responseData)
}

// TealDryrun takes transactions and additional simulated ledger state and returns debugging information.
// (POST /v2/teal/dryrun)
func (v2 *Handlers) TealDryrun(ctx echo.Context) error {
	if !v2.Node.Config().EnableDeveloperAPI {
		return ctx.String(http.StatusNotFound, "/teal/dryrun was not enabled in the configuration file by setting the EnableDeveloperAPI to true")
	}
	req := ctx.Request()
	buf := new(bytes.Buffer)
	req.Body = http.MaxBytesReader(nil, req.Body, MaxTealDryrunBytes)
	_, err := buf.ReadFrom(ctx.Request().Body)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}
	data := buf.Bytes()

	var dr DryrunRequest
	var gdr model.DryrunRequest
	err = decode(protocol.JSONStrictHandle, data, &gdr)
	if err == nil {
		dr, err = DryrunRequestFromGenerated(&gdr)
		if err != nil {
			return badRequest(ctx, err, err.Error(), v2.Log)
		}
	} else {
		err = decode(protocol.CodecHandle, data, &dr)
		if err != nil {
			return badRequest(ctx, err, err.Error(), v2.Log)
		}
	}

	// fetch previous block header just once to prevent racing with network
	var hdr bookkeeping.BlockHeader
	if dr.ProtocolVersion == "" || dr.Round == 0 || dr.LatestTimestamp == 0 {
		actualLedger := v2.Node.LedgerForAPI()
		hdr, err = actualLedger.BlockHdr(actualLedger.Latest())
		if err != nil {
			return internalError(ctx, err, "current block error", v2.Log)
		}
	}

	var response model.DryrunResponse

	var protocolVersion protocol.ConsensusVersion
	if dr.ProtocolVersion != "" {
		var ok bool
		_, ok = config.Consensus[protocol.ConsensusVersion(dr.ProtocolVersion)]
		if !ok {
			return badRequest(ctx, nil, "unsupported protocol version", v2.Log)
		}
		protocolVersion = protocol.ConsensusVersion(dr.ProtocolVersion)
	} else {
		protocolVersion = hdr.CurrentProtocol
	}
	dr.ProtocolVersion = string(protocolVersion)

	if dr.Round == 0 {
		dr.Round = uint64(hdr.Round + 1)
	}

	if dr.LatestTimestamp == 0 {
		dr.LatestTimestamp = hdr.TimeStamp
	}

	doDryrunRequest(&dr, &response)
	response.ProtocolVersion = string(protocolVersion)
	return ctx.JSON(http.StatusOK, response)
}

// UnsetSyncRound removes the sync round restriction from the ledger.
// (DELETE /v2/ledger/sync)
func (v2 *Handlers) UnsetSyncRound(ctx echo.Context) error {
	v2.Node.UnsetSyncRound()
	return ctx.NoContent(http.StatusOK)
}

// SetSyncRound sets the sync round on the ledger.
// (POST /v2/ledger/sync/{round})
func (v2 *Handlers) SetSyncRound(ctx echo.Context, round uint64) error {
	err := v2.Node.SetSyncRound(round)
	if err != nil {
		switch err {
		case catchup.ErrSyncRoundInvalid:
			return badRequest(ctx, err, errFailedSettingSyncRound, v2.Log)
		default:
			return internalError(ctx, err, errFailedSettingSyncRound, v2.Log)
		}
	}
	return ctx.NoContent(http.StatusOK)
}

// GetSyncRound gets the sync round from the ledger.
// (GET /v2/ledger/sync)
func (v2 *Handlers) GetSyncRound(ctx echo.Context) error {
	rnd := v2.Node.GetSyncRound()
	if rnd == 0 {
		return notFound(ctx, fmt.Errorf("sync round is not set"), errFailedRetrievingSyncRound, v2.Log)
	}
	return ctx.JSON(http.StatusOK, model.GetSyncRoundResponse{Round: rnd})
}

// GetLedgerStateDelta returns the deltas for a given round.
// This should be a representation of the ledgercore.StateDelta object.
// (GET /v2/deltas/{round})
func (v2 *Handlers) GetLedgerStateDelta(ctx echo.Context, round uint64, params model.GetLedgerStateDeltaParams) error {
	handle, contentType, err := getCodecHandle((*string)(params.Format))
	if err != nil {
		return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
	}
	sDelta, err := v2.Node.LedgerForAPI().GetStateDeltaForRound(basics.Round(round))
	if err != nil {
		return notFound(ctx, err, fmt.Sprintf(errFailedRetrievingStateDelta, err), v2.Log)
	}
	data, err := encode(handle, sDelta)
	if err != nil {
		return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
	}
	return ctx.Blob(http.StatusOK, contentType, data)
}

// TransactionParams returns the suggested parameters for constructing a new transaction.
// (GET /v2/transactions/params)
func (v2 *Handlers) TransactionParams(ctx echo.Context) error {
	stat, err := v2.Node.Status()
	if err != nil {
		return internalError(ctx, err, errFailedRetrievingNodeStatus, v2.Log)
	}
	if stat.Catchpoint != "" {
		// node is currently catching up to the requested catchpoint.
		return serviceUnavailable(ctx, fmt.Errorf("TransactionParams failed as the node was catchpoint catchuping"), errOperationNotAvailableDuringCatchup, v2.Log)
	}

	gh := v2.Node.GenesisHash()
	proto := config.Consensus[stat.LastVersion]

	response := model.TransactionParametersResponse{
		ConsensusVersion: string(stat.LastVersion),
		Fee:              v2.Node.SuggestedFee().Raw,
		GenesisHash:      gh[:],
		GenesisId:        v2.Node.GenesisID(),
		LastRound:        uint64(stat.LastRound),
		MinFee:           proto.MinTxnFee,
	}

	return ctx.JSON(http.StatusOK, response)
}

// PreEncodedTxInfo represents the PendingTransaction response before it is
// encoded to a format.
type PreEncodedTxInfo struct {
	AssetIndex         *uint64                    `codec:"asset-index,omitempty"`
	AssetClosingAmount *uint64                    `codec:"asset-closing-amount,omitempty"`
	ApplicationIndex   *uint64                    `codec:"application-index,omitempty"`
	CloseRewards       *uint64                    `codec:"close-rewards,omitempty"`
	ClosingAmount      *uint64                    `codec:"closing-amount,omitempty"`
	ConfirmedRound     *uint64                    `codec:"confirmed-round,omitempty"`
	GlobalStateDelta   *model.StateDelta          `codec:"global-state-delta,omitempty"`
	LocalStateDelta    *[]model.AccountStateDelta `codec:"local-state-delta,omitempty"`
	PoolError          string                     `codec:"pool-error"`
	ReceiverRewards    *uint64                    `codec:"receiver-rewards,omitempty"`
	SenderRewards      *uint64                    `codec:"sender-rewards,omitempty"`
	Txn                transactions.SignedTxn     `codec:"txn"`
	Logs               *[][]byte                  `codec:"logs,omitempty"`
	Inners             *[]PreEncodedTxInfo        `codec:"inner-txns,omitempty"`
}

// PendingTransactionInformation returns a transaction with the specified txID
// from the transaction pool. If not found looks for the transaction in the
// last proto.MaxTxnLife rounds
// (GET /v2/transactions/pending/{txid})
func (v2 *Handlers) PendingTransactionInformation(ctx echo.Context, txid string, params model.PendingTransactionInformationParams) error {

	stat, err := v2.Node.Status()
	if err != nil {
		return internalError(ctx, err, errFailedRetrievingNodeStatus, v2.Log)
	}
	if stat.Catchpoint != "" {
		// node is currently catching up to the requested catchpoint.
		return serviceUnavailable(ctx, fmt.Errorf("PendingTransactionInformation failed as the node was catchpoint catchuping"), errOperationNotAvailableDuringCatchup, v2.Log)
	}

	txID := transactions.Txid{}
	if err := txID.UnmarshalText([]byte(txid)); err != nil {
		return badRequest(ctx, err, errNoValidTxnSpecified, v2.Log)
	}

	txn, ok := v2.Node.GetPendingTransaction(txID)

	// We didn't find it, return a failure
	if !ok {
		err := errors.New(errTransactionNotFound)
		return notFound(ctx, err, err.Error(), v2.Log)
	}

	// Encoding wasn't working well without embedding "real" objects.
	response := PreEncodedTxInfo{
		Txn:       txn.Txn,
		PoolError: txn.PoolError,
	}

	if txn.ConfirmedRound != 0 {
		r := uint64(txn.ConfirmedRound)
		response.ConfirmedRound = &r

		response.ClosingAmount = &txn.ApplyData.ClosingAmount.Raw
		response.AssetClosingAmount = &txn.ApplyData.AssetClosingAmount
		response.SenderRewards = &txn.ApplyData.SenderRewards.Raw
		response.ReceiverRewards = &txn.ApplyData.ReceiverRewards.Raw
		response.CloseRewards = &txn.ApplyData.CloseRewards.Raw
		response.AssetIndex = computeAssetIndexFromTxn(txn, v2.Node.LedgerForAPI())
		response.ApplicationIndex = computeAppIndexFromTxn(txn, v2.Node.LedgerForAPI())
		response.LocalStateDelta, response.GlobalStateDelta = convertToDeltas(txn)
		response.Logs = convertLogs(txn)
		response.Inners = convertInners(&txn)
	}

	handle, contentType, err := getCodecHandle((*string)(params.Format))
	if err != nil {
		return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
	}
	data, err := encode(handle, response)
	if err != nil {
		return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
	}

	return ctx.Blob(http.StatusOK, contentType, data)
}

// getPendingTransactions returns to the provided context a list of uncomfirmed transactions currently in the transaction pool with optional Max/Address filters.
func (v2 *Handlers) getPendingTransactions(ctx echo.Context, max *uint64, format *string, addrFilter *string) error {

	stat, err := v2.Node.Status()
	if err != nil {
		return internalError(ctx, err, errFailedRetrievingNodeStatus, v2.Log)
	}
	if stat.Catchpoint != "" {
		// node is currently catching up to the requested catchpoint.
		return serviceUnavailable(ctx, fmt.Errorf("PendingTransactionInformation failed as the node was catchpoint catchuping"), errOperationNotAvailableDuringCatchup, v2.Log)
	}

	var addrPtr *basics.Address

	if addrFilter != nil {
		addr, err := basics.UnmarshalChecksumAddress(*addrFilter)
		if err != nil {
			return badRequest(ctx, err, errFailedToParseAddress, v2.Log)
		}
		addrPtr = &addr
	}

	handle, contentType, err := getCodecHandle(format)
	if err != nil {
		return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
	}

	txnPool, err := v2.Node.GetPendingTxnsFromPool()
	if err != nil {
		return internalError(ctx, err, errFailedLookingUpTransactionPool, v2.Log)
	}

	// MatchAddress uses this to check FeeSink, we don't care about that here.
	spec := transactions.SpecialAddresses{
		FeeSink:     basics.Address{},
		RewardsPool: basics.Address{},
	}

	txnLimit := uint64(math.MaxUint64)
	if max != nil && *max != 0 {
		txnLimit = *max
	}

	// Convert transactions to msgp / json strings
	topTxns := make([]transactions.SignedTxn, 0)
	for _, txn := range txnPool {
		// break out if we've reached the max number of transactions
		if uint64(len(topTxns)) >= txnLimit {
			break
		}

		// continue if we have an address filter and the address doesn't match the transaction.
		if addrPtr != nil && !txn.Txn.MatchAddress(*addrPtr, spec) {
			continue
		}

		topTxns = append(topTxns, txn)
	}

	// Encoding wasn't working well without embedding "real" objects.
	response := struct {
		TopTransactions   []transactions.SignedTxn `json:"top-transactions"`
		TotalTransactions uint64                   `json:"total-transactions"`
	}{
		TopTransactions:   topTxns,
		TotalTransactions: uint64(len(txnPool)),
	}

	data, err := encode(handle, response)
	if err != nil {
		return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
	}

	return ctx.Blob(http.StatusOK, contentType, data)
}

// startCatchup Given a catchpoint, it starts catching up to this catchpoint
func (v2 *Handlers) startCatchup(ctx echo.Context, catchpoint string, minRounds uint64) error {
	catchpointRound, _, err := ledgercore.ParseCatchpointLabel(catchpoint)
	if err != nil {
		return badRequest(ctx, err, errFailedToParseCatchpoint, v2.Log)
	}

	if minRounds > 0 {
		ledgerRound := v2.Node.LedgerForAPI().Latest()
		if catchpointRound < (ledgerRound + basics.Round(minRounds)) {
			v2.Log.Infof("Skipping catchup. Catchpoint round %d is not %d rounds ahead of the current round %d.", catchpointRound, minRounds, ledgerRound)
			return ctx.JSON(http.StatusOK, model.CatchpointStartResponse{
				CatchupMessage: errCatchpointWouldNotInitialize,
			})
		}
	}

	// Select 200/201, or return an error
	var code int
	err = v2.Node.StartCatchup(catchpoint)
	switch err.(type) {
	case nil:
		code = http.StatusCreated
	case *node.CatchpointAlreadyInProgressError:
		code = http.StatusOK
	case *node.CatchpointUnableToStartError:
		return badRequest(ctx, err, err.Error(), v2.Log)
	case *node.StartCatchpointError:
		return timeout(ctx, err, err.Error(), v2.Log)
	default:
		return internalError(ctx, err, fmt.Sprintf(errFailedToStartCatchup, err), v2.Log)
	}

	return ctx.JSON(code, model.CatchpointStartResponse{
		CatchupMessage: catchpoint,
	})
}

// abortCatchup Given a catchpoint, it aborts catching up to this catchpoint
func (v2 *Handlers) abortCatchup(ctx echo.Context, catchpoint string) error {
	_, _, err := ledgercore.ParseCatchpointLabel(catchpoint)
	if err != nil {
		return badRequest(ctx, err, errFailedToParseCatchpoint, v2.Log)
	}

	err = v2.Node.AbortCatchup(catchpoint)
	if err != nil {
		return internalError(ctx, err, fmt.Sprintf(errFailedToAbortCatchup, err), v2.Log)
	}

	return ctx.JSON(http.StatusOK, model.CatchpointAbortResponse{
		CatchupMessage: catchpoint,
	})
}

// GetPendingTransactions returns the list of unconfirmed transactions currently in the transaction pool.
// (GET /v2/transactions/pending)
func (v2 *Handlers) GetPendingTransactions(ctx echo.Context, params model.GetPendingTransactionsParams) error {
	return v2.getPendingTransactions(ctx, params.Max, (*string)(params.Format), nil)
}

// GetApplicationByID returns application information by app idx.
// (GET /v2/applications/{application-id})
func (v2 *Handlers) GetApplicationByID(ctx echo.Context, applicationID uint64) error {
	appIdx := basics.AppIndex(applicationID)
	ledger := v2.Node.LedgerForAPI()
	creator, ok, err := ledger.GetCreator(basics.CreatableIndex(appIdx), basics.AppCreatable)
	if err != nil {
		return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
	}
	if !ok {
		return notFound(ctx, errors.New(errAppDoesNotExist), errAppDoesNotExist, v2.Log)
	}

	lastRound := ledger.Latest()

	record, err := ledger.LookupApplication(lastRound, creator, basics.AppIndex(applicationID))
	if err != nil {
		return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
	}

	if record.AppParams == nil {
		return notFound(ctx, errors.New(errAppDoesNotExist), errAppDoesNotExist, v2.Log)
	}
	appParams := *record.AppParams
	app := AppParamsToApplication(creator.String(), appIdx, &appParams)
	response := model.ApplicationResponse(app)
	return ctx.JSON(http.StatusOK, response)
}

func applicationBoxesMaxKeys(requestedMax uint64, algodMax uint64) uint64 {
	if requestedMax == 0 {
		if algodMax == 0 {
			return math.MaxUint64 // unlimited results when both requested and algod max are 0
		}
		return algodMax + 1 // API limit dominates.  Increments by 1 to test if more than max supported results exist.
	}

	if requestedMax <= algodMax || algodMax == 0 {
		return requestedMax // requested limit dominates
	}

	return algodMax + 1 // API limit dominates.  Increments by 1 to test if more than max supported results exist.
}

// GetApplicationBoxes returns the box names of an application
// (GET /v2/applications/{application-id}/boxes)
func (v2 *Handlers) GetApplicationBoxes(ctx echo.Context, applicationID uint64, params model.GetApplicationBoxesParams) error {
	appIdx := basics.AppIndex(applicationID)
	ledger := v2.Node.LedgerForAPI()
	lastRound := ledger.Latest()
	keyPrefix := apps.MakeBoxKey(uint64(appIdx), "")

	requestedMax, algodMax := nilToZero(params.Max), v2.Node.Config().MaxAPIBoxPerApplication
	max := applicationBoxesMaxKeys(requestedMax, algodMax)

	if max != math.MaxUint64 {
		record, _, _, err := ledger.LookupAccount(ledger.Latest(), appIdx.Address())
		if err != nil {
			return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
		}
		if record.TotalBoxes > max {
			return ctx.JSON(http.StatusBadRequest, model.ErrorResponse{
				Message: "Result limit exceeded",
				Data: &map[string]interface{}{
					"max-api-box-per-application": algodMax,
					"max":                         requestedMax,
					"total-boxes":                 record.TotalBoxes,
				},
			})
		}
	}

	boxKeys, err := ledger.LookupKeysByPrefix(lastRound, keyPrefix, math.MaxUint64)
	if err != nil {
		return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
	}

	prefixLen := len(keyPrefix)
	responseBoxes := make([]model.BoxDescriptor, len(boxKeys))
	for i, boxKey := range boxKeys {
		responseBoxes[i] = model.BoxDescriptor{
			Name: []byte(boxKey[prefixLen:]),
		}
	}
	response := model.BoxesResponse{Boxes: responseBoxes}
	return ctx.JSON(http.StatusOK, response)
}

// GetApplicationBoxByName returns the value of an application's box
// (GET /v2/applications/{application-id}/box)
func (v2 *Handlers) GetApplicationBoxByName(ctx echo.Context, applicationID uint64, params model.GetApplicationBoxByNameParams) error {
	appIdx := basics.AppIndex(applicationID)
	ledger := v2.Node.LedgerForAPI()
	lastRound := ledger.Latest()

	encodedBoxName := params.Name
	boxNameBytes, err := apps.NewAppCallBytes(encodedBoxName)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}
	boxName, err := boxNameBytes.Raw()
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}

	value, err := ledger.LookupKv(lastRound, apps.MakeBoxKey(uint64(appIdx), string(boxName)))
	if err != nil {
		return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
	}
	if value == nil {
		return notFound(ctx, errors.New(errBoxDoesNotExist), errBoxDoesNotExist, v2.Log)
	}

	response := model.BoxResponse{
		Round: uint64(lastRound),
		Name:  boxName,
		Value: value,
	}
	return ctx.JSON(http.StatusOK, response)
}

// GetAssetByID returns application information by app idx.
// (GET /v2/assets/{asset-id})
func (v2 *Handlers) GetAssetByID(ctx echo.Context, assetID uint64) error {
	assetIdx := basics.AssetIndex(assetID)
	ledger := v2.Node.LedgerForAPI()
	creator, ok, err := ledger.GetCreator(basics.CreatableIndex(assetIdx), basics.AssetCreatable)
	if err != nil {
		return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
	}
	if !ok {
		return notFound(ctx, errors.New(errAssetDoesNotExist), errAssetDoesNotExist, v2.Log)
	}

	lastRound := ledger.Latest()
	record, err := ledger.LookupAsset(lastRound, creator, basics.AssetIndex(assetID))
	if err != nil {
		return internalError(ctx, err, errFailedLookingUpLedger, v2.Log)
	}

	if record.AssetParams == nil {
		return notFound(ctx, errors.New(errAssetDoesNotExist), errAssetDoesNotExist, v2.Log)
	}
	assetParams := *record.AssetParams
	asset := AssetParamsToAsset(creator.String(), assetIdx, &assetParams)
	response := model.AssetResponse(asset)
	return ctx.JSON(http.StatusOK, response)
}

// GetPendingTransactionsByAddress takes an Algorand address and returns its associated list of unconfirmed transactions currently in the transaction pool.
// (GET /v2/accounts/{address}/transactions/pending)
func (v2 *Handlers) GetPendingTransactionsByAddress(ctx echo.Context, addr string, params model.GetPendingTransactionsByAddressParams) error {
	return v2.getPendingTransactions(ctx, params.Max, (*string)(params.Format), &addr)
}

// StartCatchup Given a catchpoint, it starts catching up to this catchpoint
// (POST /v2/catchup/{catchpoint})
func (v2 *Handlers) StartCatchup(ctx echo.Context, catchpoint string, params model.StartCatchupParams) error {
	min := nilToZero(params.Min)
	return v2.startCatchup(ctx, catchpoint, min)
}

// AbortCatchup Given a catchpoint, it aborts catching up to this catchpoint
// (DELETE /v2/catchup/{catchpoint})
func (v2 *Handlers) AbortCatchup(ctx echo.Context, catchpoint string) error {
	return v2.abortCatchup(ctx, catchpoint)
}

// CompileResponseWithSourceMap overrides the sourcemap field in
// the CompileResponse for JSON marshalling.
type CompileResponseWithSourceMap struct {
	model.CompileResponse
	Sourcemap *logic.SourceMap `json:"sourcemap,omitempty"`
}

// TealCompile compiles TEAL code to binary, return both binary and hash
// (POST /v2/teal/compile)
func (v2 *Handlers) TealCompile(ctx echo.Context, params model.TealCompileParams) (err error) {
	// Return early if teal compile is not allowed in node config.
	if !v2.Node.Config().EnableDeveloperAPI {
		return ctx.String(http.StatusNotFound, "/teal/compile was not enabled in the configuration file by setting the EnableDeveloperAPI to true")
	}
	if params.Sourcemap == nil {
		// Backwards compatibility: set sourcemap flag to default false value.
		defaultValue := false
		params.Sourcemap = &defaultValue
	}

	buf := new(bytes.Buffer)
	ctx.Request().Body = http.MaxBytesReader(nil, ctx.Request().Body, MaxTealSourceBytes)
	_, err = buf.ReadFrom(ctx.Request().Body)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}
	source := buf.String()
	ops, err := logic.AssembleString(source)
	if err != nil {
		sb := strings.Builder{}
		ops.ReportMultipleErrors("", &sb)
		return badRequest(ctx, err, sb.String(), v2.Log)
	}
	pd := logic.HashProgram(ops.Program)
	addr := basics.Address(pd)

	// If source map flag is enabled, then return the map.
	var sourcemap *logic.SourceMap
	if *params.Sourcemap {
		rawmap := logic.GetSourceMap([]string{"<body>"}, ops.OffsetToSource)
		sourcemap = &rawmap
	}

	response := CompileResponseWithSourceMap{
		model.CompileResponse{
			Hash:   addr.String(),
			Result: base64.StdEncoding.EncodeToString(ops.Program),
		},
		sourcemap,
	}
	return ctx.JSON(http.StatusOK, response)
}

// GetStateProof returns the state proof for a given round.
// (GET /v2/stateproofs/{round})
func (v2 *Handlers) GetStateProof(ctx echo.Context, round uint64) error {
	ctxWithTimeout, cancel := context.WithTimeout(ctx.Request().Context(), time.Minute)
	defer cancel()

	ledger := v2.Node.LedgerForAPI()
	if ledger.Latest() < basics.Round(round) {
		return internalError(ctx, errors.New(errRoundGreaterThanTheLatest), errRoundGreaterThanTheLatest, v2.Log)
	}

	tx, err := GetStateProofTransactionForRound(ctxWithTimeout, ledger, basics.Round(round), ledger.Latest(), v2.Shutdown)
	if err != nil {
		return v2.wrapStateproofError(ctx, err)
	}

	response := model.StateProofResponse{
		StateProof: protocol.Encode(&tx.StateProof),
	}

	response.Message.BlockHeadersCommitment = tx.Message.BlockHeadersCommitment
	response.Message.VotersCommitment = tx.Message.VotersCommitment
	response.Message.LnProvenWeight = tx.Message.LnProvenWeight
	response.Message.FirstAttestedRound = tx.Message.FirstAttestedRound
	response.Message.LastAttestedRound = tx.Message.LastAttestedRound

	return ctx.JSON(http.StatusOK, response)
}

func (v2 *Handlers) wrapStateproofError(ctx echo.Context, err error) error {
	if errors.Is(err, ErrNoStateProofForRound) {
		return notFound(ctx, err, err.Error(), v2.Log)
	}
	if errors.Is(err, ErrTimeout) {
		return timeout(ctx, err, err.Error(), v2.Log)
	}
	return internalError(ctx, err, err.Error(), v2.Log)
}

// GetLightBlockHeaderProof Gets a proof of a light block header for a given round
// (GET /v2/blocks/{round}/lightheader/proof)
func (v2 *Handlers) GetLightBlockHeaderProof(ctx echo.Context, round uint64) error {
	ctxWithTimeout, cancel := context.WithTimeout(ctx.Request().Context(), time.Minute)
	defer cancel()
	ledger := v2.Node.LedgerForAPI()
	if ledger.Latest() < basics.Round(round) {
		return internalError(ctx, errors.New(errRoundGreaterThanTheLatest), errRoundGreaterThanTheLatest, v2.Log)
	}

	stateProof, err := GetStateProofTransactionForRound(ctxWithTimeout, ledger, basics.Round(round), ledger.Latest(), v2.Shutdown)
	if err != nil {
		return v2.wrapStateproofError(ctx, err)
	}

	lastAttestedRound := stateProof.Message.LastAttestedRound
	firstAttestedRound := stateProof.Message.FirstAttestedRound
	stateProofInterval := lastAttestedRound - firstAttestedRound + 1

	lightHeaders, err := stateproof.FetchLightHeaders(ledger, stateProofInterval, basics.Round(lastAttestedRound))
	if err != nil {
		return notFound(ctx, err, err.Error(), v2.Log)
	}

	blockIndex := round - firstAttestedRound
	leafproof, err := stateproof.GenerateProofOfLightBlockHeaders(stateProofInterval, lightHeaders, blockIndex)
	if err != nil {
		return internalError(ctx, err, err.Error(), v2.Log)
	}

	response := model.LightBlockHeaderProofResponse{
		Index:     blockIndex,
		Proof:     leafproof.GetConcatenatedProof(),
		Treedepth: uint64(leafproof.TreeDepth),
	}
	return ctx.JSON(http.StatusOK, response)
}

// TealDisassemble disassembles the program bytecode in base64 into TEAL code.
// (POST /v2/teal/disassemble)
func (v2 *Handlers) TealDisassemble(ctx echo.Context) error {
	// return early if teal compile is not allowed in node config
	if !v2.Node.Config().EnableDeveloperAPI {
		return ctx.String(http.StatusNotFound, "/teal/disassemble was not enabled in the configuration file by setting the EnableDeveloperAPI to true")
	}
	buf := new(bytes.Buffer)
	ctx.Request().Body = http.MaxBytesReader(nil, ctx.Request().Body, MaxTealSourceBytes)
	_, err := buf.ReadFrom(ctx.Request().Body)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}
	sourceProgram := buf.Bytes()
	program, err := logic.Disassemble(sourceProgram)
	if err != nil {
		return badRequest(ctx, err, err.Error(), v2.Log)
	}
	response := model.DisassembleResponse{
		Result: program,
	}
	return ctx.JSON(http.StatusOK, response)
}

// GetLedgerStateDeltaForTransactionGroup retrieves the delta for a specified transaction group.
// (GET /v2/deltas/txn/group/{id})
func (v2 *Handlers) GetLedgerStateDeltaForTransactionGroup(ctx echo.Context, id string, params model.GetLedgerStateDeltaForTransactionGroupParams) error {
	handle, contentType, err := getCodecHandle((*string)(params.Format))
	if err != nil {
		return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
	}
	idDigest, err := crypto.DigestFromString(id)
	if err != nil {
		return badRequest(ctx, err, errNoValidTxnSpecified, v2.Log)
	}
	tracer, ok := v2.Node.LedgerForAPI().GetTracer().(*eval.TxnGroupDeltaTracer)
	if !ok {
		return notImplemented(ctx, err, errFailedRetrievingTracer, v2.Log)
	}
	delta, err := tracer.GetDeltaForID(idDigest)
	if err != nil {
		return notFound(ctx, err, fmt.Sprintf(errFailedRetrievingStateDelta, err), v2.Log)
	}
	data, err := encode(handle, delta)
	if err != nil {
		return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
	}
	return ctx.Blob(http.StatusOK, contentType, data)
}

// GetTransactionGroupLedgerStateDeltasForRound retrieves the deltas for transaction groups in a given round.
// (GET /v2/deltas/{round}/txn/group)
func (v2 *Handlers) GetTransactionGroupLedgerStateDeltasForRound(ctx echo.Context, round uint64, params model.GetTransactionGroupLedgerStateDeltasForRoundParams) error {
	handle, contentType, err := getCodecHandle((*string)(params.Format))
	if err != nil {
		return badRequest(ctx, err, errFailedParsingFormatOption, v2.Log)
	}
	tracer, ok := v2.Node.LedgerForAPI().GetTracer().(*eval.TxnGroupDeltaTracer)
	if !ok {
		return notImplemented(ctx, err, errFailedRetrievingTracer, v2.Log)
	}
	deltas, err := tracer.GetDeltasForRound(basics.Round(round))
	if err != nil {
		return notFound(ctx, err, fmt.Sprintf(errFailedRetrievingStateDelta, err), v2.Log)
	}
	response := struct {
		Deltas []eval.TxnGroupDeltaWithIds
	}{
		Deltas: deltas,
	}
	data, err := encode(handle, response)
	if err != nil {
		return internalError(ctx, err, errFailedToEncodeResponse, v2.Log)
	}
	return ctx.Blob(http.StatusOK, contentType, data)
}

// ExperimentalCheck is only available when EnabledExperimentalAPI is true
func (v2 *Handlers) ExperimentalCheck(ctx echo.Context) error {
	return ctx.JSON(http.StatusOK, true)
}

// GetBlockTimeStampOffset gets the timestamp offset.
// This is only available in dev mode.
// (GET /v2/devmode/blocks/offset)
func (v2 *Handlers) GetBlockTimeStampOffset(ctx echo.Context) error {
	offset, err := v2.Node.GetBlockTimeStampOffset()
	if err != nil {
		err = fmt.Errorf("cannot get block timestamp offset because we are not in dev mode")
		return badRequest(ctx, err, fmt.Sprintf(errFailedRetrievingTimeStampOffset, err), v2.Log)
	} else if offset == nil {
		err = fmt.Errorf("block timestamp offset was never set, using real clock for timestamps")
		return notFound(ctx, err, fmt.Sprintf(errFailedRetrievingTimeStampOffset, err), v2.Log)
	}
	return ctx.JSON(http.StatusOK, model.GetBlockTimeStampOffsetResponse{Offset: uint64(*offset)})
}

// SetBlockTimeStampOffset sets the timestamp offset.
// This is only available in dev mode.
// (POST /v2/devmode/blocks/offset/{offset})
func (v2 *Handlers) SetBlockTimeStampOffset(ctx echo.Context, offset uint64) error {
	if offset > math.MaxInt64 {
		err := fmt.Errorf("block timestamp offset cannot be larger than max int64 value")
		return badRequest(ctx, err, fmt.Sprintf(errFailedSettingTimeStampOffset, err), v2.Log)
	}
	err := v2.Node.SetBlockTimeStampOffset(int64(offset))
	if err != nil {
		return badRequest(ctx, err, fmt.Sprintf(errFailedSettingTimeStampOffset, err), v2.Log)
	}
	return ctx.NoContent(http.StatusOK)
}