-
Notifications
You must be signed in to change notification settings - Fork 672
/
service.go
2345 lines (2040 loc) · 70.6 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-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package platformvm
import (
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/ava-labs/avalanchego/api"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/crypto"
"github.com/ava-labs/avalanchego/utils/formatting"
"github.com/ava-labs/avalanchego/utils/json"
"github.com/ava-labs/avalanchego/utils/math"
"github.com/ava-labs/avalanchego/utils/wrappers"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/components/keystore"
"github.com/ava-labs/avalanchego/vms/platformvm/reward"
"github.com/ava-labs/avalanchego/vms/platformvm/stakeable"
"github.com/ava-labs/avalanchego/vms/platformvm/status"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
)
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 * syncBound
// Max number of items allowed in a page
maxPageSize = 1024
)
var (
errMissingDecisionBlock = errors.New("should have a decision block within the past two blocks")
errNoFunds = errors.New("no spendable funds were found")
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")
errNoPrimaryValidators = errors.New("no default subnet validators")
errNoValidators = errors.New("no subnet validators")
errCorruptedReason = errors.New("tx validity corrupted")
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")
errTotalOverflow = errors.New("overflow while calculating total balance")
errUnlockedOverflow = errors.New("overflow while calculating unlocked balance")
errLockedOverflow = errors.New("overflow while calculating locked balance")
errNotStakeableOverflow = errors.New("overflow while calculating locked not stakeable balance")
errLockedNotStakeableOverflow = errors.New("overflow while calculating locked not stakeable balance")
errUnlockedStakeableOverflow = errors.New("overflow while calculating unlocked stakeable balance")
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")
)
// Service defines the API calls that can be made to the platform chain
type Service struct{ vm *VM }
type GetHeightResponse struct {
Height json.Uint64 `json:"height"`
}
// GetHeight returns the height of the last accepted block
func (service *Service) GetHeight(r *http.Request, args *struct{}, response *GetHeightResponse) error {
lastAcceptedID, err := service.vm.LastAccepted()
if err != nil {
return fmt.Errorf("couldn't get last accepted block ID: %w", err)
}
lastAccepted, err := service.vm.getBlock(lastAcceptedID)
if err != nil {
return fmt.Errorf("couldn't get last accepted block: %w", err)
}
response.Height = json.Uint64(lastAccepted.Height())
return nil
}
// 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 string `json:"privateKey"`
}
// ExportKey returns a private key from the provided user
func (service *Service) ExportKey(r *http.Request, args *ExportKeyArgs, reply *ExportKeyReply) error {
service.vm.ctx.Log.Debug("Platform: ExportKey called")
address, err := service.vm.ParseLocalAddress(args.Address)
if err != nil {
return fmt.Errorf("couldn't parse %s to address: %w", args.Address, err)
}
user, err := keystore.NewUserFromKeystore(service.vm.ctx.Keystore, args.Username, args.Password)
if err != nil {
return err
}
sk, 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)
}
// We assume that the maximum size of a byte slice that
// can be stringified is at least the length of a SECP256K1 private key
privKeyStr, _ := formatting.EncodeWithChecksum(formatting.CB58, sk.Bytes())
reply.PrivateKey = constants.SecretKeyPrefix + privKeyStr
return user.Close()
}
// ImportKeyArgs are arguments for ImportKey
type ImportKeyArgs struct {
api.UserPass
PrivateKey string `json:"privateKey"`
}
// ImportKey adds a private key to the provided user
func (service *Service) ImportKey(r *http.Request, args *ImportKeyArgs, reply *api.JSONAddress) error {
service.vm.ctx.Log.Debug("Platform: ImportKey called for user '%s'", args.Username)
if !strings.HasPrefix(args.PrivateKey, constants.SecretKeyPrefix) {
return fmt.Errorf("private key missing %s prefix", constants.SecretKeyPrefix)
}
trimmedPrivateKey := strings.TrimPrefix(args.PrivateKey, constants.SecretKeyPrefix)
privKeyBytes, err := formatting.Decode(formatting.CB58, trimmedPrivateKey)
if err != nil {
return fmt.Errorf("problem parsing private key: %w", err)
}
skIntf, err := service.vm.factory.ToPrivateKey(privKeyBytes)
if err != nil {
return fmt.Errorf("problem parsing private key: %w", err)
}
sk := skIntf.(*crypto.PrivateKeySECP256K1R)
reply.Address, err = service.vm.FormatLocalAddress(sk.PublicKey().Address())
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
user, err := keystore.NewUserFromKeystore(service.vm.ctx.Keystore, args.Username, args.Password)
if err != nil {
return err
}
defer user.Close()
if err := user.PutKeys(sk); err != nil {
return fmt.Errorf("problem saving key %w", err)
}
return user.Close()
}
/*
******************************************************
************* Balances / Addresses ******************
******************************************************
*/
type GetBalanceRequest struct {
// TODO: remove Address
Address *string `json:"address,omitempty"`
Addresses []string `json:"addresses"`
}
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"`
UTXOIDs []*avax.UTXOID `json:"utxoIDs"`
}
// GetBalance gets the balance of an address
func (service *Service) GetBalance(_ *http.Request, args *GetBalanceRequest, response *GetBalanceResponse) error {
if args.Address != nil {
args.Addresses = append(args.Addresses, *args.Address)
}
service.vm.ctx.Log.Debug("Platform: GetBalance called for addresses %v", args.Addresses)
addrs := ids.ShortSet{}
for _, addrStr := range args.Addresses {
// Parse to address
addr, err := service.vm.ParseLocalAddress(addrStr)
if err != nil {
return fmt.Errorf("couldn't parse argument %q to address: %w", addrStr, err)
}
addrs.Add(addr)
}
utxos, err := avax.GetAllUTXOs(service.vm.internalState, addrs)
if err != nil {
return fmt.Errorf("couldn't get UTXO set of %v: %w", args.Addresses, err)
}
currentTime := service.vm.clock.Unix()
unlocked := uint64(0)
lockedStakeable := uint64(0)
lockedNotStakeable := uint64(0)
utxoFor:
for _, utxo := range utxos {
switch out := utxo.Out.(type) {
case *secp256k1fx.TransferOutput:
if out.Locktime <= currentTime {
newBalance, err := math.Add64(unlocked, out.Amount())
if err != nil {
return errUnlockedOverflow
}
unlocked = newBalance
} else {
newBalance, err := math.Add64(lockedNotStakeable, out.Amount())
if err != nil {
return errNotStakeableOverflow
}
lockedNotStakeable = newBalance
}
case *stakeable.LockOut:
innerOut, ok := out.TransferableOut.(*secp256k1fx.TransferOutput)
switch {
case !ok:
service.vm.ctx.Log.Warn("Unexpected Output type in UTXO: %T",
out.TransferableOut)
continue utxoFor
case innerOut.Locktime > currentTime:
newBalance, err := math.Add64(lockedNotStakeable, out.Amount())
if err != nil {
return errLockedNotStakeableOverflow
}
lockedNotStakeable = newBalance
case out.Locktime <= currentTime:
newBalance, err := math.Add64(unlocked, out.Amount())
if err != nil {
return errUnlockedOverflow
}
unlocked = newBalance
default:
newBalance, err := math.Add64(lockedStakeable, out.Amount())
if err != nil {
return errUnlockedStakeableOverflow
}
lockedStakeable = newBalance
}
default:
continue utxoFor
}
response.UTXOIDs = append(response.UTXOIDs, &utxo.UTXOID)
}
lockedBalance, err := math.Add64(lockedStakeable, lockedNotStakeable)
if err != nil {
return errLockedOverflow
}
balance, err := math.Add64(unlocked, lockedBalance)
if err != nil {
return errTotalOverflow
}
response.Balance = json.Uint64(balance)
response.Unlocked = json.Uint64(unlocked)
response.LockedStakeable = json.Uint64(lockedStakeable)
response.LockedNotStakeable = json.Uint64(lockedNotStakeable)
return nil
}
// CreateAddress creates an address controlled by [args.Username]
// Returns the newly created address
func (service *Service) CreateAddress(_ *http.Request, args *api.UserPass, response *api.JSONAddress) error {
service.vm.ctx.Log.Debug("Platform: CreateAddress called")
user, err := keystore.NewUserFromKeystore(service.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 = service.vm.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 (service *Service) ListAddresses(_ *http.Request, args *api.UserPass, response *api.JSONAddresses) error {
service.vm.ctx.Log.Debug("Platform: ListAddresses called")
user, err := keystore.NewUserFromKeystore(service.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 = service.vm.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
}
// GetUTXOsArgs are arguments for passing into GetUTXOs.
// Gets the UTXOs that reference at least one address in [Addresses].
// If specified, [SourceChain] is the chain where the atomic UTXOs were exported from. If empty,
// or the Platform Chain ID is specified, then GetUTXOs fetches the native UTXOs.
// Returns at most [limit] addresses.
// If [limit] == 0 or > [maxUTXOsToFetch], fetches up to [maxUTXOsToFetch].
// [StartIndex] defines where to start fetching UTXOs (for pagination.)
// UTXOs fetched are from addresses equal to or greater than [StartIndex.Address]
// For address [StartIndex.Address], only UTXOs with IDs greater than [StartIndex.UTXO] will be returned.
// If [StartIndex] is omitted, gets all UTXOs.
// If GetUTXOs is called multiple times, with our without [StartIndex], it is not guaranteed
// that returned UTXOs are unique. That is, the same UTXO may appear in the response of multiple calls.
// [Encoding] defines the encoding format to use for the returned UTXOs. Can be either "cb58" or "hex"
type GetUTXOsArgs struct {
Addresses []string `json:"addresses"`
SourceChain string `json:"sourceChain"`
Limit json.Uint32 `json:"limit"`
StartIndex Index `json:"startIndex"`
Encoding formatting.Encoding `json:"encoding"`
}
// GetUTXOsResponse defines the GetUTXOs replies returned from the API
type GetUTXOsResponse struct {
// Number of UTXOs returned
NumFetched json.Uint64 `json:"numFetched"`
// The UTXOs
UTXOs []string `json:"utxos"`
// The last UTXO that was returned, and the address it corresponds to.
// Used for pagination. To get the rest of the UTXOs, call GetUTXOs
// again and set [StartIndex] to this value.
EndIndex Index `json:"endIndex"`
// Encoding specifies the format the UTXOs are returned in
Encoding formatting.Encoding `json:"encoding"`
}
// GetUTXOs returns the UTXOs controlled by the given addresses
func (service *Service) GetUTXOs(_ *http.Request, args *GetUTXOsArgs, response *GetUTXOsResponse) error {
service.vm.ctx.Log.Debug("Platform: GetUTXOs called")
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 = service.vm.ctx.ChainID
} else {
chainID, err := service.vm.ctx.BCLookup.Lookup(args.SourceChain)
if err != nil {
return fmt.Errorf("problem parsing source chainID %q: %w", args.SourceChain, err)
}
sourceChain = chainID
}
addrSet := ids.ShortSet{}
for _, addrStr := range args.Addresses {
addr, err := service.vm.ParseLocalAddress(addrStr)
if err != nil {
return fmt.Errorf("couldn't parse address %q: %w", addrStr, err)
}
addrSet.Add(addr)
}
startAddr := ids.ShortEmpty
startUTXO := ids.Empty
if args.StartIndex.Address != "" || args.StartIndex.UTXO != "" {
var err error
startAddr, err = service.vm.ParseLocalAddress(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
err error
)
limit := int(args.Limit)
if limit <= 0 || maxPageSize < limit {
limit = maxPageSize
}
if sourceChain == service.vm.ctx.ChainID {
utxos, endAddr, endUTXOID, err = avax.GetPaginatedUTXOs(
service.vm.internalState,
addrSet,
startAddr,
startUTXO,
limit,
)
} else {
utxos, endAddr, endUTXOID, err = service.vm.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 := Codec.Marshal(CodecVersion, utxo)
if err != nil {
return fmt.Errorf("couldn't serialize UTXO %q: %w", utxo.InputID(), err)
}
response.UTXOs[i], err = formatting.EncodeWithChecksum(args.Encoding, bytes)
if err != nil {
return fmt.Errorf("couldn't encode UTXO %s as string: %w", utxo.InputID(), err)
}
}
endAddress, err := service.vm.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 (service *Service) GetSubnets(_ *http.Request, args *GetSubnetsArgs, response *GetSubnetsResponse) error {
service.vm.ctx.Log.Debug("Platform: GetSubnets called")
getAll := len(args.IDs) == 0
if getAll {
subnets, err := service.vm.internalState.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 {
unsignedTx := subnet.UnsignedTx.(*UnsignedCreateSubnetTx)
owner := unsignedTx.Owner.(*secp256k1fx.OutputOwners)
controlAddrs := []string{}
for _, controlKeyID := range owner.Addrs {
addr, err := service.vm.FormatLocalAddress(controlKeyID)
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
controlAddrs = append(controlAddrs, addr)
}
response.Subnets[i] = APISubnet{
ID: subnet.ID(),
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 := ids.NewSet(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
}
subnetTx, _, err := service.vm.internalState.GetTx(subnetID)
if err == database.ErrNotFound {
continue
}
if err != nil {
return err
}
subnet, ok := subnetTx.UnsignedTx.(*UnsignedCreateSubnetTx)
if !ok {
return errWrongTxType
}
owner, ok := subnet.Owner.(*secp256k1fx.OutputOwners)
if !ok {
return errUnknownOwners
}
controlAddrs := make([]string, len(owner.Addrs))
for i, controlKeyID := range owner.Addrs {
addr, err := service.vm.FormatLocalAddress(controlKeyID)
if err != nil {
return fmt.Errorf("problem formatting address: %w", err)
}
controlAddrs[i] = addr
}
response.Subnets = append(response.Subnets,
APISubnet{
ID: subnet.ID(),
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 (service *Service) GetStakingAssetID(_ *http.Request, args *GetStakingAssetIDArgs, response *GetStakingAssetIDResponse) error {
service.vm.ctx.Log.Debug("Platform: GetStakingAssetID called")
if args.SubnetID != constants.PrimaryNetworkID {
return fmt.Errorf("Subnet %s doesn't have a valid staking token",
args.SubnetID)
}
response.AssetID = service.vm.ctx.AVAXAssetID
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"`
}
// GetCurrentValidators returns current validators and delegators
func (service *Service) GetCurrentValidators(_ *http.Request, args *GetCurrentValidatorsArgs, reply *GetCurrentValidatorsReply) error {
service.vm.ctx.Log.Debug("Platform: GetCurrentValidators called")
reply.Validators = []interface{}{}
// Validator's node ID as string --> Delegators to them
vdrToDelegators := map[ids.NodeID][]APIPrimaryDelegator{}
// Create set of nodeIDs
nodeIDs := ids.NodeIDSet{}
nodeIDs.Add(args.NodeIDs...)
includeAllNodes := nodeIDs.Len() == 0
currentValidators := service.vm.internalState.CurrentStakerChainState()
// TODO: do not iterate over all stakers when nodeIDs given. Use currentValidators.ValidatorSet for iteration
for _, tx := range currentValidators.Stakers() { // Iterates in order of increasing stop time
_, rewardAmount, err := currentValidators.GetStaker(tx.ID())
if err != nil {
return err
}
switch staker := tx.UnsignedTx.(type) {
case *UnsignedAddDelegatorTx:
if args.SubnetID != constants.PrimaryNetworkID {
continue
}
if !includeAllNodes && !nodeIDs.Contains(staker.Validator.ID()) {
continue
}
weight := json.Uint64(staker.Validator.Weight())
var rewardOwner *APIOwner
owner, ok := staker.RewardsOwner.(*secp256k1fx.OutputOwners)
if ok {
rewardOwner = &APIOwner{
Locktime: json.Uint64(owner.Locktime),
Threshold: json.Uint32(owner.Threshold),
}
for _, addr := range owner.Addrs {
addrStr, err := service.vm.FormatLocalAddress(addr)
if err != nil {
return err
}
rewardOwner.Addresses = append(rewardOwner.Addresses, addrStr)
}
}
potentialReward := json.Uint64(rewardAmount)
delegator := APIPrimaryDelegator{
APIStaker: APIStaker{
TxID: tx.ID(),
StartTime: json.Uint64(staker.StartTime().Unix()),
EndTime: json.Uint64(staker.EndTime().Unix()),
StakeAmount: &weight,
NodeID: staker.Validator.ID(),
},
RewardOwner: rewardOwner,
PotentialReward: &potentialReward,
}
vdrToDelegators[delegator.NodeID] = append(vdrToDelegators[delegator.NodeID], delegator)
case *UnsignedAddValidatorTx:
if args.SubnetID != constants.PrimaryNetworkID {
continue
}
if !includeAllNodes && !nodeIDs.Contains(staker.Validator.ID()) {
continue
}
nodeID := staker.Validator.ID()
startTime := staker.StartTime()
weight := json.Uint64(staker.Validator.Weight())
potentialReward := json.Uint64(rewardAmount)
delegationFee := json.Float32(100 * float32(staker.Shares) / float32(reward.PercentDenominator))
rawUptime, err := service.vm.uptimeManager.CalculateUptimePercentFrom(nodeID, startTime)
if err != nil {
return err
}
uptime := json.Float32(rawUptime)
connected := service.vm.uptimeManager.IsConnected(nodeID)
var rewardOwner *APIOwner
owner, ok := staker.RewardsOwner.(*secp256k1fx.OutputOwners)
if ok {
rewardOwner = &APIOwner{
Locktime: json.Uint64(owner.Locktime),
Threshold: json.Uint32(owner.Threshold),
}
for _, addr := range owner.Addrs {
addrStr, err := service.vm.FormatLocalAddress(addr)
if err != nil {
return err
}
rewardOwner.Addresses = append(rewardOwner.Addresses, addrStr)
}
}
reply.Validators = append(reply.Validators, APIPrimaryValidator{
APIStaker: APIStaker{
TxID: tx.ID(),
NodeID: nodeID,
StartTime: json.Uint64(startTime.Unix()),
EndTime: json.Uint64(staker.EndTime().Unix()),
StakeAmount: &weight,
},
Uptime: &uptime,
Connected: connected,
PotentialReward: &potentialReward,
RewardOwner: rewardOwner,
DelegationFee: delegationFee,
})
case *UnsignedAddSubnetValidatorTx:
if args.SubnetID != staker.Validator.Subnet {
continue
}
if !includeAllNodes && !nodeIDs.Contains(staker.Validator.ID()) {
continue
}
nodeID := staker.Validator.ID()
weight := json.Uint64(staker.Validator.Weight())
connected := service.vm.uptimeManager.IsConnected(nodeID)
tracksSubnet := service.vm.SubnetTracker.TracksSubnet(nodeID, args.SubnetID)
reply.Validators = append(reply.Validators, APISubnetValidator{
APIStaker: APIStaker{
NodeID: nodeID,
TxID: tx.ID(),
StartTime: json.Uint64(staker.StartTime().Unix()),
EndTime: json.Uint64(staker.EndTime().Unix()),
Weight: &weight,
},
Connected: connected && tracksSubnet,
})
default:
return fmt.Errorf("expected validator but got %T", tx.UnsignedTx)
}
}
for i, vdrIntf := range reply.Validators {
vdr, ok := vdrIntf.(APIPrimaryValidator)
if !ok {
continue
}
if delegators, ok := vdrToDelegators[vdr.NodeID]; ok {
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.
// Unlike GetCurrentValidatorsReply, each validator has a null delegator list.
type GetPendingValidatorsReply struct {
Validators []interface{} `json:"validators"`
Delegators []interface{} `json:"delegators"`
}
// GetPendingValidators returns the list of pending validators
func (service *Service) GetPendingValidators(_ *http.Request, args *GetPendingValidatorsArgs, reply *GetPendingValidatorsReply) error {
service.vm.ctx.Log.Debug("Platform: GetPendingValidators called")
reply.Validators = []interface{}{}
reply.Delegators = []interface{}{}
// Create set of nodeIDs
nodeIDs := ids.NodeIDSet{}
nodeIDs.Add(args.NodeIDs...)
includeAllNodes := nodeIDs.Len() == 0
pendingValidators := service.vm.internalState.PendingStakerChainState()
for _, tx := range pendingValidators.Stakers() { // Iterates in order of increasing start time
switch staker := tx.UnsignedTx.(type) {
case *UnsignedAddDelegatorTx:
if args.SubnetID != constants.PrimaryNetworkID {
continue
}
if !includeAllNodes && !nodeIDs.Contains(staker.Validator.ID()) {
continue
}
weight := json.Uint64(staker.Validator.Weight())
reply.Delegators = append(reply.Delegators, APIStaker{
TxID: tx.ID(),
NodeID: staker.Validator.ID(),
StartTime: json.Uint64(staker.StartTime().Unix()),
EndTime: json.Uint64(staker.EndTime().Unix()),
StakeAmount: &weight,
})
case *UnsignedAddValidatorTx:
if args.SubnetID != constants.PrimaryNetworkID {
continue
}
if !includeAllNodes && !nodeIDs.Contains(staker.Validator.ID()) {
continue
}
nodeID := staker.Validator.ID()
weight := json.Uint64(staker.Validator.Weight())
delegationFee := json.Float32(100 * float32(staker.Shares) / float32(reward.PercentDenominator))
connected := service.vm.uptimeManager.IsConnected(nodeID)
reply.Validators = append(reply.Validators, APIPrimaryValidator{
APIStaker: APIStaker{
TxID: tx.ID(),
NodeID: staker.Validator.ID(),
StartTime: json.Uint64(staker.StartTime().Unix()),
EndTime: json.Uint64(staker.EndTime().Unix()),
StakeAmount: &weight,
},
DelegationFee: delegationFee,
Connected: connected,
})
case *UnsignedAddSubnetValidatorTx:
if args.SubnetID != staker.Validator.Subnet {
continue
}
if !includeAllNodes && !nodeIDs.Contains(staker.Validator.ID()) {
continue
}
nodeID := staker.Validator.ID()
weight := json.Uint64(staker.Validator.Weight())
connected := service.vm.uptimeManager.IsConnected(nodeID)
tracksSubnet := service.vm.SubnetTracker.TracksSubnet(nodeID, args.SubnetID)
reply.Validators = append(reply.Validators, APISubnetValidator{
APIStaker: APIStaker{
NodeID: nodeID,
TxID: tx.ID(),
StartTime: json.Uint64(staker.StartTime().Unix()),
EndTime: json.Uint64(staker.EndTime().Unix()),
Weight: &weight,
},
Connected: connected && tracksSubnet,
})
default:
return fmt.Errorf("expected validator but got %T", tx.UnsignedTx)
}
}
return nil
}
// GetCurrentSupplyReply are the results from calling GetCurrentSupply
type GetCurrentSupplyReply struct {
Supply json.Uint64 `json:"supply"`
}
// GetCurrentSupply returns an upper bound on the supply of AVAX in the system
func (service *Service) GetCurrentSupply(_ *http.Request, _ *struct{}, reply *GetCurrentSupplyReply) error {
service.vm.ctx.Log.Debug("Platform: GetCurrentSupply called")
reply.Supply = json.Uint64(service.vm.internalState.GetCurrentSupply())
return nil
}
// SampleValidatorsArgs are the arguments for calling SampleValidators
type SampleValidatorsArgs struct {
// Number of validators in the sample
Size json.Uint16 `json:"size"`
// ID of subnet to sample validators from
// If omitted, defaults to the primary network
SubnetID ids.ID `json:"subnetID"`
}
// SampleValidatorsReply are the results from calling Sample
type SampleValidatorsReply struct {
Validators []ids.NodeID `json:"validators"`
}
// SampleValidators returns a sampling of the list of current validators
func (service *Service) SampleValidators(_ *http.Request, args *SampleValidatorsArgs, reply *SampleValidatorsReply) error {
service.vm.ctx.Log.Debug("Platform: SampleValidators called with Size = %d", args.Size)
validators, ok := service.vm.Validators.GetValidators(args.SubnetID)
if !ok {
return fmt.Errorf(
"couldn't get validators of subnet %q. Is it being validated?",
args.SubnetID,
)
}
sample, err := validators.Sample(int(args.Size))
if err != nil {
return fmt.Errorf("sampling errored with %w", err)
}
reply.Validators = make([]ids.NodeID, int(args.Size))
for i, vdr := range sample {
reply.Validators[i] = vdr.ID()
}
ids.SortNodeIDs(reply.Validators)
return nil
}
/*
******************************************************
************ Add Validators to Subnets ***************
******************************************************
*/
// AddValidatorArgs are the arguments to AddValidator
type AddValidatorArgs struct {
// User, password, from addrs, change addr
api.JSONSpendHeader
APIStaker
// The address the staking reward, if applicable, will go to
RewardAddress string `json:"rewardAddress"`
DelegationFeeRate json.Float32 `json:"delegationFeeRate"`
}
// AddValidator creates and signs and issues a transaction to add a validator to
// the primary network
func (service *Service) AddValidator(_ *http.Request, args *AddValidatorArgs, reply *api.JSONTxIDChangeAddr) error {
service.vm.ctx.Log.Debug("Platform: AddValidator called")
now := service.vm.clock.Time()
minAddStakerTime := now.Add(minAddStakerDelay)
minAddStakerUnix := json.Uint64(minAddStakerTime.Unix())
maxAddStakerTime := now.Add(maxFutureStartTime)
maxAddStakerUnix := json.Uint64(maxAddStakerTime.Unix())
if args.StartTime == 0 {
args.StartTime = minAddStakerUnix
}
switch {
case args.RewardAddress == "":
return errNoRewardAddress
case args.StartTime < minAddStakerUnix:
return errStartTimeTooSoon