-
Notifications
You must be signed in to change notification settings - Fork 670
/
service.go
2842 lines (2444 loc) · 81.3 KB
/
service.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-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package platformvm
import (
"context"
"errors"
"fmt"
"math"
"net/http"
"time"
stdjson "encoding/json"
"go.uber.org/zap"
"golang.org/x/exp/maps"
"github.com/ava-labs/avalanchego/api"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow/validators"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
"github.com/ava-labs/avalanchego/utils/crypto/secp256k1"
"github.com/ava-labs/avalanchego/utils/formatting"
"github.com/ava-labs/avalanchego/utils/json"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/utils/set"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/components/keystore"
"github.com/ava-labs/avalanchego/vms/platformvm/fx"
"github.com/ava-labs/avalanchego/vms/platformvm/reward"
"github.com/ava-labs/avalanchego/vms/platformvm/signer"
"github.com/ava-labs/avalanchego/vms/platformvm/stakeable"
"github.com/ava-labs/avalanchego/vms/platformvm/state"
"github.com/ava-labs/avalanchego/vms/platformvm/status"
"github.com/ava-labs/avalanchego/vms/platformvm/txs"
"github.com/ava-labs/avalanchego/vms/platformvm/txs/builder"
"github.com/ava-labs/avalanchego/vms/platformvm/txs/executor"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
safemath "github.com/ava-labs/avalanchego/utils/math"
platformapi "github.com/ava-labs/avalanchego/vms/platformvm/api"
)
const (
// Max number of addresses that can be passed in as argument to GetUTXOs
maxGetUTXOsAddrs = 1024
// Max number of addresses that can be passed in as argument to GetStake
maxGetStakeAddrs = 256
// Minimum amount of delay to allow a transaction to be issued through the
// API
minAddStakerDelay = 2 * executor.SyncBound
// Note: Staker attributes cache should be large enough so that no evictions
// happen when the API loops through all stakers.
stakerAttributesCacheSize = 100_000
)
var (
errMissingDecisionBlock = errors.New("should have a decision block within the past two blocks")
errNoSubnetID = errors.New("argument 'subnetID' not provided")
errNoRewardAddress = errors.New("argument 'rewardAddress' not provided")
errInvalidDelegationRate = errors.New("argument 'delegationFeeRate' must be between 0 and 100, inclusive")
errNoAddresses = errors.New("no addresses provided")
errNoKeys = errors.New("user has no keys or funds")
errStartTimeTooSoon = fmt.Errorf("start time must be at least %s in the future", minAddStakerDelay)
errStartTimeTooLate = errors.New("start time is too far in the future")
errNamedSubnetCantBePrimary = errors.New("subnet validator attempts to validate primary network")
errNoAmount = errors.New("argument 'amount' must be > 0")
errMissingName = errors.New("argument 'name' not given")
errMissingVMID = errors.New("argument 'vmID' not given")
errMissingBlockchainID = errors.New("argument 'blockchainID' not given")
errMissingPrivateKey = errors.New("argument 'privateKey' not given")
errStartAfterEndTime = errors.New("start time must be before end time")
errStartTimeInThePast = errors.New("start time in the past")
)
// Service defines the API calls that can be made to the platform chain
type Service struct {
vm *VM
addrManager avax.AddressManager
stakerAttributesCache *cache.LRU[ids.ID, *stakerAttributes]
}
// All attributes are optional and may not be filled for each stakerTx.
type stakerAttributes struct {
shares uint32
rewardsOwner fx.Owner
validationRewardsOwner fx.Owner
delegationRewardsOwner fx.Owner
proofOfPossession *signer.ProofOfPossession
}
// GetHeight returns the height of the last accepted block
func (s *Service) GetHeight(r *http.Request, _ *struct{}, response *api.GetHeightResponse) error {
s.vm.ctx.Log.Debug("API called",
zap.String("service", "platform"),
zap.String("method", "getHeight"),
)
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
ctx := r.Context()
height, err := s.vm.GetCurrentHeight(ctx)
response.Height = json.Uint64(height)
return err
}
// ExportKeyArgs are arguments for ExportKey
type ExportKeyArgs struct {
api.UserPass
Address string `json:"address"`
}
// ExportKeyReply is the response for ExportKey
type ExportKeyReply struct {
// The decrypted PrivateKey for the Address provided in the arguments
PrivateKey *secp256k1.PrivateKey `json:"privateKey"`
}
// ExportKey returns a private key from the provided user
func (s *Service) ExportKey(_ *http.Request, args *ExportKeyArgs, reply *ExportKeyReply) error {
s.vm.ctx.Log.Warn("deprecated API called",
zap.String("service", "platform"),
zap.String("method", "exportKey"),
logging.UserString("username", args.Username),
)
address, err := avax.ParseServiceAddress(s.addrManager, args.Address)
if err != nil {
return fmt.Errorf("couldn't parse %s to address: %w", args.Address, err)
}
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
user, err := keystore.NewUserFromKeystore(s.vm.ctx.Keystore, args.Username, args.Password)
if err != nil {
return err
}
reply.PrivateKey, err = user.GetKey(address)
if err != nil {
// Drop any potential error closing the user to report the original
// error
_ = user.Close()
return fmt.Errorf("problem retrieving private key: %w", err)
}
return user.Close()
}
// ImportKeyArgs are arguments for ImportKey
type ImportKeyArgs struct {
api.UserPass
PrivateKey *secp256k1.PrivateKey `json:"privateKey"`
}
// ImportKey adds a private key to the provided user
func (s *Service) ImportKey(_ *http.Request, args *ImportKeyArgs, reply *api.JSONAddress) error {
s.vm.ctx.Log.Warn("deprecated API called",
zap.String("service", "platform"),
zap.String("method", "importKey"),
logging.UserString("username", args.Username),
)
if args.PrivateKey == nil {
return errMissingPrivateKey
}
var err error
reply.Address, err = s.addrManager.FormatLocalAddress(args.PrivateKey.PublicKey().Address())
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
user, err := keystore.NewUserFromKeystore(s.vm.ctx.Keystore, args.Username, args.Password)
if err != nil {
return err
}
defer user.Close()
if err := user.PutKeys(args.PrivateKey); err != nil {
return fmt.Errorf("problem saving key %w", err)
}
return user.Close()
}
/*
******************************************************
************* Balances / Addresses ******************
******************************************************
*/
type GetBalanceRequest struct {
Addresses []string `json:"addresses"`
}
// Note: We explicitly duplicate AVAX out of the maps to ensure backwards
// compatibility.
type GetBalanceResponse struct {
// Balance, in nAVAX, of the address
Balance json.Uint64 `json:"balance"`
Unlocked json.Uint64 `json:"unlocked"`
LockedStakeable json.Uint64 `json:"lockedStakeable"`
LockedNotStakeable json.Uint64 `json:"lockedNotStakeable"`
Balances map[ids.ID]json.Uint64 `json:"balances"`
Unlockeds map[ids.ID]json.Uint64 `json:"unlockeds"`
LockedStakeables map[ids.ID]json.Uint64 `json:"lockedStakeables"`
LockedNotStakeables map[ids.ID]json.Uint64 `json:"lockedNotStakeables"`
UTXOIDs []*avax.UTXOID `json:"utxoIDs"`
}
// GetBalance gets the balance of an address
func (s *Service) GetBalance(_ *http.Request, args *GetBalanceRequest, response *GetBalanceResponse) error {
s.vm.ctx.Log.Debug("deprecated API called",
zap.String("service", "platform"),
zap.String("method", "getBalance"),
logging.UserStrings("addresses", args.Addresses),
)
addrs, err := avax.ParseServiceAddresses(s.addrManager, args.Addresses)
if err != nil {
return err
}
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
utxos, err := avax.GetAllUTXOs(s.vm.state, addrs)
if err != nil {
return fmt.Errorf("couldn't get UTXO set of %v: %w", args.Addresses, err)
}
currentTime := s.vm.clock.Unix()
unlockeds := map[ids.ID]uint64{}
lockedStakeables := map[ids.ID]uint64{}
lockedNotStakeables := map[ids.ID]uint64{}
utxoFor:
for _, utxo := range utxos {
assetID := utxo.AssetID()
switch out := utxo.Out.(type) {
case *secp256k1fx.TransferOutput:
if out.Locktime <= currentTime {
newBalance, err := safemath.Add64(unlockeds[assetID], out.Amount())
if err != nil {
unlockeds[assetID] = math.MaxUint64
} else {
unlockeds[assetID] = newBalance
}
} else {
newBalance, err := safemath.Add64(lockedNotStakeables[assetID], out.Amount())
if err != nil {
lockedNotStakeables[assetID] = math.MaxUint64
} else {
lockedNotStakeables[assetID] = newBalance
}
}
case *stakeable.LockOut:
innerOut, ok := out.TransferableOut.(*secp256k1fx.TransferOutput)
switch {
case !ok:
s.vm.ctx.Log.Warn("unexpected output type in UTXO",
zap.String("type", fmt.Sprintf("%T", out.TransferableOut)),
)
continue utxoFor
case innerOut.Locktime > currentTime:
newBalance, err := safemath.Add64(lockedNotStakeables[assetID], out.Amount())
if err != nil {
lockedNotStakeables[assetID] = math.MaxUint64
} else {
lockedNotStakeables[assetID] = newBalance
}
case out.Locktime <= currentTime:
newBalance, err := safemath.Add64(unlockeds[assetID], out.Amount())
if err != nil {
unlockeds[assetID] = math.MaxUint64
} else {
unlockeds[assetID] = newBalance
}
default:
newBalance, err := safemath.Add64(lockedStakeables[assetID], out.Amount())
if err != nil {
lockedStakeables[assetID] = math.MaxUint64
} else {
lockedStakeables[assetID] = newBalance
}
}
default:
continue utxoFor
}
response.UTXOIDs = append(response.UTXOIDs, &utxo.UTXOID)
}
balances := maps.Clone(lockedStakeables)
for assetID, amount := range lockedNotStakeables {
newBalance, err := safemath.Add64(balances[assetID], amount)
if err != nil {
balances[assetID] = math.MaxUint64
} else {
balances[assetID] = newBalance
}
}
for assetID, amount := range unlockeds {
newBalance, err := safemath.Add64(balances[assetID], amount)
if err != nil {
balances[assetID] = math.MaxUint64
} else {
balances[assetID] = newBalance
}
}
response.Balances = newJSONBalanceMap(balances)
response.Unlockeds = newJSONBalanceMap(unlockeds)
response.LockedStakeables = newJSONBalanceMap(lockedStakeables)
response.LockedNotStakeables = newJSONBalanceMap(lockedNotStakeables)
response.Balance = response.Balances[s.vm.ctx.AVAXAssetID]
response.Unlocked = response.Unlockeds[s.vm.ctx.AVAXAssetID]
response.LockedStakeable = response.LockedStakeables[s.vm.ctx.AVAXAssetID]
response.LockedNotStakeable = response.LockedNotStakeables[s.vm.ctx.AVAXAssetID]
return nil
}
func newJSONBalanceMap(balanceMap map[ids.ID]uint64) map[ids.ID]json.Uint64 {
jsonBalanceMap := make(map[ids.ID]json.Uint64, len(balanceMap))
for assetID, amount := range balanceMap {
jsonBalanceMap[assetID] = json.Uint64(amount)
}
return jsonBalanceMap
}
// CreateAddress creates an address controlled by [args.Username]
// Returns the newly created address
func (s *Service) CreateAddress(_ *http.Request, args *api.UserPass, response *api.JSONAddress) error {
s.vm.ctx.Log.Warn("deprecated API called",
zap.String("service", "platform"),
zap.String("method", "createAddress"),
logging.UserString("username", args.Username),
)
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
user, err := keystore.NewUserFromKeystore(s.vm.ctx.Keystore, args.Username, args.Password)
if err != nil {
return err
}
defer user.Close()
key, err := keystore.NewKey(user)
if err != nil {
return err
}
response.Address, err = s.addrManager.FormatLocalAddress(key.PublicKey().Address())
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
return user.Close()
}
// ListAddresses returns the addresses controlled by [args.Username]
func (s *Service) ListAddresses(_ *http.Request, args *api.UserPass, response *api.JSONAddresses) error {
s.vm.ctx.Log.Warn("deprecated API called",
zap.String("service", "platform"),
zap.String("method", "listAddresses"),
logging.UserString("username", args.Username),
)
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
user, err := keystore.NewUserFromKeystore(s.vm.ctx.Keystore, args.Username, args.Password)
if err != nil {
return err
}
defer user.Close()
addresses, err := user.GetAddresses()
if err != nil {
return fmt.Errorf("couldn't get addresses: %w", err)
}
response.Addresses = make([]string, len(addresses))
for i, addr := range addresses {
response.Addresses[i], err = s.addrManager.FormatLocalAddress(addr)
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
}
return user.Close()
}
// Index is an address and an associated UTXO.
// Marks a starting or stopping point when fetching UTXOs. Used for pagination.
type Index struct {
Address string `json:"address"` // The address as a string
UTXO string `json:"utxo"` // The UTXO ID as a string
}
// GetUTXOs returns the UTXOs controlled by the given addresses
func (s *Service) GetUTXOs(_ *http.Request, args *api.GetUTXOsArgs, response *api.GetUTXOsReply) error {
s.vm.ctx.Log.Debug("API called",
zap.String("service", "platform"),
zap.String("method", "getUTXOs"),
)
if len(args.Addresses) == 0 {
return errNoAddresses
}
if len(args.Addresses) > maxGetUTXOsAddrs {
return fmt.Errorf("number of addresses given, %d, exceeds maximum, %d", len(args.Addresses), maxGetUTXOsAddrs)
}
var sourceChain ids.ID
if args.SourceChain == "" {
sourceChain = s.vm.ctx.ChainID
} else {
chainID, err := s.vm.ctx.BCLookup.Lookup(args.SourceChain)
if err != nil {
return fmt.Errorf("problem parsing source chainID %q: %w", args.SourceChain, err)
}
sourceChain = chainID
}
addrSet, err := avax.ParseServiceAddresses(s.addrManager, args.Addresses)
if err != nil {
return err
}
startAddr := ids.ShortEmpty
startUTXO := ids.Empty
if args.StartIndex.Address != "" || args.StartIndex.UTXO != "" {
startAddr, err = avax.ParseServiceAddress(s.addrManager, args.StartIndex.Address)
if err != nil {
return fmt.Errorf("couldn't parse start index address %q: %w", args.StartIndex.Address, err)
}
startUTXO, err = ids.FromString(args.StartIndex.UTXO)
if err != nil {
return fmt.Errorf("couldn't parse start index utxo: %w", err)
}
}
var (
utxos []*avax.UTXO
endAddr ids.ShortID
endUTXOID ids.ID
)
limit := int(args.Limit)
if limit <= 0 || builder.MaxPageSize < limit {
limit = builder.MaxPageSize
}
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
if sourceChain == s.vm.ctx.ChainID {
utxos, endAddr, endUTXOID, err = avax.GetPaginatedUTXOs(
s.vm.state,
addrSet,
startAddr,
startUTXO,
limit,
)
} else {
utxos, endAddr, endUTXOID, err = s.vm.atomicUtxosManager.GetAtomicUTXOs(
sourceChain,
addrSet,
startAddr,
startUTXO,
limit,
)
}
if err != nil {
return fmt.Errorf("problem retrieving UTXOs: %w", err)
}
response.UTXOs = make([]string, len(utxos))
for i, utxo := range utxos {
bytes, err := txs.Codec.Marshal(txs.Version, utxo)
if err != nil {
return fmt.Errorf("couldn't serialize UTXO %q: %w", utxo.InputID(), err)
}
response.UTXOs[i], err = formatting.Encode(args.Encoding, bytes)
if err != nil {
return fmt.Errorf("couldn't encode UTXO %s as %s: %w", utxo.InputID(), args.Encoding, err)
}
}
endAddress, err := s.addrManager.FormatLocalAddress(endAddr)
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
response.EndIndex.Address = endAddress
response.EndIndex.UTXO = endUTXOID.String()
response.NumFetched = json.Uint64(len(utxos))
response.Encoding = args.Encoding
return nil
}
/*
******************************************************
******************* Get Subnets **********************
******************************************************
*/
// APISubnet is a representation of a subnet used in API calls
type APISubnet struct {
// ID of the subnet
ID ids.ID `json:"id"`
// Each element of [ControlKeys] the address of a public key.
// A transaction to add a validator to this subnet requires
// signatures from [Threshold] of these keys to be valid.
ControlKeys []string `json:"controlKeys"`
Threshold json.Uint32 `json:"threshold"`
}
// GetSubnetsArgs are the arguments to GetSubnet
type GetSubnetsArgs struct {
// IDs of the subnets to retrieve information about
// If omitted, gets all subnets
IDs []ids.ID `json:"ids"`
}
// GetSubnetsResponse is the response from calling GetSubnets
type GetSubnetsResponse struct {
// Each element is a subnet that exists
// Null if there are no subnets other than the primary network
Subnets []APISubnet `json:"subnets"`
}
// GetSubnets returns the subnets whose ID are in [args.IDs]
// The response will include the primary network
func (s *Service) GetSubnets(_ *http.Request, args *GetSubnetsArgs, response *GetSubnetsResponse) error {
s.vm.ctx.Log.Debug("deprecated API called",
zap.String("service", "platform"),
zap.String("method", "getSubnets"),
)
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
getAll := len(args.IDs) == 0
if getAll {
subnets, err := s.vm.state.GetSubnets() // all subnets
if err != nil {
return fmt.Errorf("error getting subnets from database: %w", err)
}
response.Subnets = make([]APISubnet, len(subnets)+1)
for i, subnet := range subnets {
subnetID := subnet.ID()
if _, err := s.vm.state.GetSubnetTransformation(subnetID); err == nil {
response.Subnets[i] = APISubnet{
ID: subnetID,
ControlKeys: []string{},
Threshold: json.Uint32(0),
}
continue
}
unsignedTx := subnet.Unsigned.(*txs.CreateSubnetTx)
owner := unsignedTx.Owner.(*secp256k1fx.OutputOwners)
controlAddrs := []string{}
for _, controlKeyID := range owner.Addrs {
addr, err := s.addrManager.FormatLocalAddress(controlKeyID)
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
controlAddrs = append(controlAddrs, addr)
}
response.Subnets[i] = APISubnet{
ID: subnetID,
ControlKeys: controlAddrs,
Threshold: json.Uint32(owner.Threshold),
}
}
// Include primary network
response.Subnets[len(subnets)] = APISubnet{
ID: constants.PrimaryNetworkID,
ControlKeys: []string{},
Threshold: json.Uint32(0),
}
return nil
}
subnetSet := set.NewSet[ids.ID](len(args.IDs))
for _, subnetID := range args.IDs {
if subnetSet.Contains(subnetID) {
continue
}
subnetSet.Add(subnetID)
if subnetID == constants.PrimaryNetworkID {
response.Subnets = append(response.Subnets,
APISubnet{
ID: constants.PrimaryNetworkID,
ControlKeys: []string{},
Threshold: json.Uint32(0),
},
)
continue
}
if _, err := s.vm.state.GetSubnetTransformation(subnetID); err == nil {
response.Subnets = append(response.Subnets, APISubnet{
ID: subnetID,
ControlKeys: []string{},
Threshold: json.Uint32(0),
})
continue
}
subnetOwner, err := s.vm.state.GetSubnetOwner(subnetID)
if err == database.ErrNotFound {
continue
}
if err != nil {
return err
}
owner, ok := subnetOwner.(*secp256k1fx.OutputOwners)
if !ok {
return fmt.Errorf("expected *secp256k1fx.OutputOwners but got %T", subnetOwner)
}
controlAddrs := make([]string, len(owner.Addrs))
for i, controlKeyID := range owner.Addrs {
addr, err := s.addrManager.FormatLocalAddress(controlKeyID)
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
controlAddrs[i] = addr
}
response.Subnets = append(response.Subnets, APISubnet{
ID: subnetID,
ControlKeys: controlAddrs,
Threshold: json.Uint32(owner.Threshold),
})
}
return nil
}
// GetStakingAssetIDArgs are the arguments to GetStakingAssetID
type GetStakingAssetIDArgs struct {
SubnetID ids.ID `json:"subnetID"`
}
// GetStakingAssetIDResponse is the response from calling GetStakingAssetID
type GetStakingAssetIDResponse struct {
AssetID ids.ID `json:"assetID"`
}
// GetStakingAssetID returns the assetID of the token used to stake on the
// provided subnet
func (s *Service) GetStakingAssetID(_ *http.Request, args *GetStakingAssetIDArgs, response *GetStakingAssetIDResponse) error {
s.vm.ctx.Log.Debug("API called",
zap.String("service", "platform"),
zap.String("method", "getStakingAssetID"),
)
if args.SubnetID == constants.PrimaryNetworkID {
response.AssetID = s.vm.ctx.AVAXAssetID
return nil
}
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
transformSubnetIntf, err := s.vm.state.GetSubnetTransformation(args.SubnetID)
if err != nil {
return fmt.Errorf(
"failed fetching subnet transformation for %s: %w",
args.SubnetID,
err,
)
}
transformSubnet, ok := transformSubnetIntf.Unsigned.(*txs.TransformSubnetTx)
if !ok {
return fmt.Errorf(
"unexpected subnet transformation tx type fetched %T",
transformSubnetIntf.Unsigned,
)
}
response.AssetID = transformSubnet.AssetID
return nil
}
/*
******************************************************
**************** Get/Sample Validators ***************
******************************************************
*/
// GetCurrentValidatorsArgs are the arguments for calling GetCurrentValidators
type GetCurrentValidatorsArgs struct {
// Subnet we're listing the validators of
// If omitted, defaults to primary network
SubnetID ids.ID `json:"subnetID"`
// NodeIDs of validators to request. If [NodeIDs]
// is empty, it fetches all current validators. If
// some nodeIDs are not currently validators, they
// will be omitted from the response.
NodeIDs []ids.NodeID `json:"nodeIDs"`
}
// GetCurrentValidatorsReply are the results from calling GetCurrentValidators.
// Each validator contains a list of delegators to itself.
type GetCurrentValidatorsReply struct {
Validators []interface{} `json:"validators"`
}
func (s *Service) loadStakerTxAttributes(txID ids.ID) (*stakerAttributes, error) {
// Lookup tx from the cache first.
attr, found := s.stakerAttributesCache.Get(txID)
if found {
return attr, nil
}
// Tx not available in cache; pull it from disk and populate the cache.
tx, _, err := s.vm.state.GetTx(txID)
if err != nil {
return nil, err
}
switch stakerTx := tx.Unsigned.(type) {
case txs.ValidatorTx:
var pop *signer.ProofOfPossession
if staker, ok := stakerTx.(*txs.AddPermissionlessValidatorTx); ok {
if s, ok := staker.Signer.(*signer.ProofOfPossession); ok {
pop = s
}
}
attr = &stakerAttributes{
shares: stakerTx.Shares(),
validationRewardsOwner: stakerTx.ValidationRewardsOwner(),
delegationRewardsOwner: stakerTx.DelegationRewardsOwner(),
proofOfPossession: pop,
}
case txs.DelegatorTx:
attr = &stakerAttributes{
rewardsOwner: stakerTx.RewardsOwner(),
}
default:
return nil, fmt.Errorf("unexpected staker tx type %T", tx.Unsigned)
}
s.stakerAttributesCache.Put(txID, attr)
return attr, nil
}
// GetCurrentValidators returns the current validators. If a single nodeID
// is provided, full delegators information is also returned. Otherwise only
// delegators' number and total weight is returned.
func (s *Service) GetCurrentValidators(_ *http.Request, args *GetCurrentValidatorsArgs, reply *GetCurrentValidatorsReply) error {
s.vm.ctx.Log.Debug("API called",
zap.String("service", "platform"),
zap.String("method", "getCurrentValidators"),
)
reply.Validators = []interface{}{}
// Validator's node ID as string --> Delegators to them
vdrToDelegators := map[ids.NodeID][]platformapi.PrimaryDelegator{}
// Create set of nodeIDs
nodeIDs := set.Of(args.NodeIDs...)
s.vm.ctx.Lock.Lock()
defer s.vm.ctx.Lock.Unlock()
numNodeIDs := nodeIDs.Len()
targetStakers := make([]*state.Staker, 0, numNodeIDs)
if numNodeIDs == 0 { // Include all nodes
currentStakerIterator, err := s.vm.state.GetCurrentStakerIterator()
if err != nil {
return err
}
// TODO: avoid iterating over delegators here.
for currentStakerIterator.Next() {
staker := currentStakerIterator.Value()
if args.SubnetID != staker.SubnetID {
continue
}
targetStakers = append(targetStakers, staker)
}
currentStakerIterator.Release()
} else {
for nodeID := range nodeIDs {
staker, err := s.vm.state.GetCurrentValidator(args.SubnetID, nodeID)
switch err {
case nil:
case database.ErrNotFound:
// nothing to do, continue
continue
default:
return err
}
targetStakers = append(targetStakers, staker)
// TODO: avoid iterating over delegators when numNodeIDs > 1.
delegatorsIt, err := s.vm.state.GetCurrentDelegatorIterator(args.SubnetID, nodeID)
if err != nil {
return err
}
for delegatorsIt.Next() {
staker := delegatorsIt.Value()
targetStakers = append(targetStakers, staker)
}
delegatorsIt.Release()
}
}
for _, currentStaker := range targetStakers {
nodeID := currentStaker.NodeID
weight := json.Uint64(currentStaker.Weight)
apiStaker := platformapi.Staker{
TxID: currentStaker.TxID,
StartTime: json.Uint64(currentStaker.StartTime.Unix()),
EndTime: json.Uint64(currentStaker.EndTime.Unix()),
Weight: weight,
StakeAmount: &weight,
NodeID: nodeID,
}
potentialReward := json.Uint64(currentStaker.PotentialReward)
delegateeReward, err := s.vm.state.GetDelegateeReward(currentStaker.SubnetID, currentStaker.NodeID)
if err != nil {
return err
}
jsonDelegateeReward := json.Uint64(delegateeReward)
switch currentStaker.Priority {
case txs.PrimaryNetworkValidatorCurrentPriority, txs.SubnetPermissionlessValidatorCurrentPriority:
attr, err := s.loadStakerTxAttributes(currentStaker.TxID)
if err != nil {
return err
}
shares := attr.shares
delegationFee := json.Float32(100 * float32(shares) / float32(reward.PercentDenominator))
uptime, err := s.getAPIUptime(currentStaker)
if err != nil {
return err
}
connected := s.vm.uptimeManager.IsConnected(nodeID, args.SubnetID)
var (
validationRewardOwner *platformapi.Owner
delegationRewardOwner *platformapi.Owner
)
validationOwner, ok := attr.validationRewardsOwner.(*secp256k1fx.OutputOwners)
if ok {
validationRewardOwner, err = s.getAPIOwner(validationOwner)
if err != nil {
return err
}
}
delegationOwner, ok := attr.delegationRewardsOwner.(*secp256k1fx.OutputOwners)
if ok {
delegationRewardOwner, err = s.getAPIOwner(delegationOwner)
if err != nil {
return err
}
}
vdr := platformapi.PermissionlessValidator{
Staker: apiStaker,
Uptime: uptime,
Connected: connected,
PotentialReward: &potentialReward,
AccruedDelegateeReward: &jsonDelegateeReward,
RewardOwner: validationRewardOwner,
ValidationRewardOwner: validationRewardOwner,
DelegationRewardOwner: delegationRewardOwner,
DelegationFee: delegationFee,
Signer: attr.proofOfPossession,
}
reply.Validators = append(reply.Validators, vdr)
case txs.PrimaryNetworkDelegatorCurrentPriority, txs.SubnetPermissionlessDelegatorCurrentPriority:
var rewardOwner *platformapi.Owner
// If we are handling multiple nodeIDs, we don't return the
// delegator information.
if numNodeIDs == 1 {
attr, err := s.loadStakerTxAttributes(currentStaker.TxID)
if err != nil {
return err
}
owner, ok := attr.rewardsOwner.(*secp256k1fx.OutputOwners)
if ok {
rewardOwner, err = s.getAPIOwner(owner)
if err != nil {
return err
}
}
}
delegator := platformapi.PrimaryDelegator{
Staker: apiStaker,
RewardOwner: rewardOwner,
PotentialReward: &potentialReward,
}
vdrToDelegators[delegator.NodeID] = append(vdrToDelegators[delegator.NodeID], delegator)
case txs.SubnetPermissionedValidatorCurrentPriority:
uptime, err := s.getAPIUptime(currentStaker)
if err != nil {
return err
}
connected := s.vm.uptimeManager.IsConnected(nodeID, args.SubnetID)
reply.Validators = append(reply.Validators, platformapi.PermissionedValidator{
Staker: apiStaker,
Connected: connected,
Uptime: uptime,
})
default:
return fmt.Errorf("unexpected staker priority %d", currentStaker.Priority)
}
}
// handle delegators' information
for i, vdrIntf := range reply.Validators {
vdr, ok := vdrIntf.(platformapi.PermissionlessValidator)
if !ok {
continue
}
delegators, ok := vdrToDelegators[vdr.NodeID]
if !ok {
// If we are expected to populate the delegators field, we should
// always return a non-nil value.
delegators = []platformapi.PrimaryDelegator{}
}
delegatorCount := json.Uint64(len(delegators))
delegatorWeight := json.Uint64(0)
for _, d := range delegators {
delegatorWeight += d.Weight
}
vdr.DelegatorCount = &delegatorCount
vdr.DelegatorWeight = &delegatorWeight
if numNodeIDs == 1 {
// queried a specific validator, load all of its delegators
vdr.Delegators = &delegators
}
reply.Validators[i] = vdr
}
return nil
}
// GetPendingValidatorsArgs are the arguments for calling GetPendingValidators
type GetPendingValidatorsArgs struct {
// Subnet we're getting the pending validators of
// If omitted, defaults to primary network
SubnetID ids.ID `json:"subnetID"`
// NodeIDs of validators to request. If [NodeIDs]
// is empty, it fetches all pending validators. If
// some requested nodeIDs are not pending validators,
// they are omitted from the response.
NodeIDs []ids.NodeID `json:"nodeIDs"`
}
// GetPendingValidatorsReply are the results from calling GetPendingValidators.
type GetPendingValidatorsReply struct {
Validators []interface{} `json:"validators"`
Delegators []interface{} `json:"delegators"`
}
// GetPendingValidators returns the lists of pending validators and delegators.
func (s *Service) GetPendingValidators(_ *http.Request, args *GetPendingValidatorsArgs, reply *GetPendingValidatorsReply) error {
s.vm.ctx.Log.Debug("API called",
zap.String("service", "platform"),
zap.String("method", "getPendingValidators"),
)
reply.Validators = []interface{}{}
reply.Delegators = []interface{}{}