/
rpc.go
3278 lines (2828 loc) · 86.5 KB
/
rpc.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
package rpc
import (
"encoding/json"
"errors"
"fmt"
"github.com/meshplus/gosdk/account"
"github.com/meshplus/gosdk/common/types"
"github.com/meshplus/gosdk/config"
"io/ioutil"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/meshplus/gosdk/common"
"github.com/spf13/viper"
)
const (
// TRANSACTION type
TRANSACTION = "tx_"
// CONTRACT type
CONTRACT = "contract_"
// CONTRACT type
CROSS_CHAIN = "crosschain_"
// BLOCK type
BLOCK = "block_"
// ACCOUNT type
ACCOUNT = "account_"
// NODE type
NODE = "node_"
// CERT type
CERT = "cert_"
// SUB type
SUB = "sub_"
// ARCHIVE type
ARCHIVE = "archive_"
// MQ type
MQ = "mq_"
// RADAR type
RADAR = "radar_"
// CONFIG type
CONFIG = "config_"
// FILE type
FILE = "fm_"
// AUTH type
AUTH = "auth_"
// SIMULATE type
SIMULATE = "simulate_"
//DID type
DID = "did_"
// PROOF type
PROOF = "proof_"
DefaultNamespace = "global"
DefaultResendTime = 10
DefaultFirstPollInterval = 100
DefaultFirstPollTime = 10
DefaultSecondPollInterval = 1000
DefaultSecondPollTime = 10
DefaultReConnectTime = 10000
DefaultTxVersion = "3.0"
)
type CrossChainMethod string
const (
// InvokeAnchorContract method used for normal cross chain request
InvokeAnchorContract CrossChainMethod = "invokeAnchorContract"
// InvokeTimeoutContract method used for timeout cross chain request
InvokeTimeoutContract CrossChainMethod = "invokeTimeoutContract"
)
func (c CrossChainMethod) String() string {
return string(c)
}
var (
logger = common.GetLogger("rpc")
once = sync.Once{}
TxVersion = DefaultTxVersion
GasPrice int64 = 0
)
// RPC represents rpc apis
type RPC struct {
hrm httpRequestManager
namespace string
resTime int64
firstPollInterval int64
firstPollTime int64
secondPollInterval int64
secondPollTime int64
reConnTime int64
txVersion string
chainID string
gasPrice int64
im *inspectorManager
config *config.Config
}
type inspectorManager struct {
enable bool
key account.Key
}
func (rpc *RPC) String() string {
nodes := rpc.hrm.nodes
var nodeString string
nodeString += "["
for i, v := range nodes {
nodeString += "{\"index\":" + strconv.Itoa(i) + ", \"url:\"" + v.url + "}"
if i < len(nodes)-1 {
nodeString += ", "
}
}
nodeString += "]"
return "\"namespace\":" + rpc.namespace + ", \"nodeUrl\":" + nodeString
}
func (rpc *RPC) GetChainID() string {
return rpc.chainID
}
// NewRPC get a RPC instance with default conf directory path "../conf"
func NewRPC() *RPC {
return NewRPCWithPath(common.DefaultConfRootPath)
}
// NewRPCWithPath get a RPC instance with user defined root conf directory path
// the default conf root file structure should like this:
//
// conf
// ├── certs
// │ ├── ecert.cert
// │ ├── ecert.priv
// │ ├── sdkcert.cert
// │ ├── sdkcert.priv
// │ ├── tls
// │ │ ├── tls_peer.cert
// │ │ ├── tls_peer.priv
// │ │ └── tlsca.ca
// │ ├── unique.priv
// │ └── unique.pub
// └── hpc.toml
func NewRPCWithPath(confRootPath string) *RPC {
cf, err := config.NewFromFile(confRootPath)
if err != nil {
panic(err)
}
im := newInspectorManager(cf, confRootPath)
httpRequestManager := newHTTPRequestManager(cf, confRootPath)
rpc := &RPC{
hrm: *httpRequestManager,
namespace: cf.GetNamespace(),
resTime: cf.GetResendTime(),
firstPollInterval: cf.GetFirstPollingInterval(),
firstPollTime: cf.GetFirstPollingTimes(),
secondPollInterval: cf.GetSecondPollingInterval(),
secondPollTime: cf.GetSecondPollingTimes(),
reConnTime: cf.GetReConnectTime(),
im: im,
config: cf,
}
rpc.initGlobal()
return rpc
}
func (rpc *RPC) initGlobal() {
txVersion, err := rpc.GetTxVersion()
if err != nil {
logger.Info("use config txVersion, for", err.Error())
txVersion = rpc.config.GetTxVersion()
}
gasPrice, err1 := rpc.GetGasPrice()
if err1 != nil {
logger.Info("get gas price, for", err1.Error())
}
TxVersion = txVersion
rpc.txVersion = txVersion
rpc.hrm.txVersion = txVersion
rpc.gasPrice = gasPrice
GasPrice = gasPrice
logger.Info("set TxVersion to " + TxVersion)
}
func newInspectorManager(cf *config.Config, confRootPath string) (im *inspectorManager) {
inspectorEnable := cf.IsInspectorEnable()
logger.Debugf("[CONFIG]: %s = %v", common.InspectorEnable, inspectorEnable)
im = &inspectorManager{
enable: inspectorEnable,
}
if !inspectorEnable {
return
}
accountPath := strings.Join([]string{confRootPath, cf.GetInspectorDefaultAccount()}, "/")
logger.Debugf("[CONFIG]: %s = %v", common.InspectorAccountPath, accountPath)
data, err := ioutil.ReadFile(accountPath)
if err != nil {
logger.Errorf("read %s:%s err:%v", common.InspectorAccountPath, accountPath, err)
return
}
accountType := cf.GetInspectorAccountType()
logger.Debugf("[CONFIG]: %s = %v", common.InspectorAccountType, accountType)
var key account.Key
switch accountType {
case "ecdsa":
key, err = account.NewAccountFromAccountJSON(string(data), "")
case "sm2":
key, err = account.NewAccountSm2FromAccountJSON(string(data), "")
case "ecdsaPriv":
key, err = account.NewAccountFromPriv(string(data))
case "ecdsaPrivR1":
key, err = account.NewAccountR1FromPriv(string(data))
case "sm2Priv":
key, err = account.NewAccountSm2FromPriv(string(data))
default:
logger.Errorf("unsupport account type:%s", accountType)
return
}
if err != nil {
logger.Errorf("new account type %s from %s err:%v", accountType, accountPath, err)
return
}
im.key = key
return
}
// DefaultRPC return a *RPC with some default configs
func DefaultRPC(nodes ...*Node) *RPC {
rpc := &RPC{
namespace: DefaultNamespace,
resTime: DefaultResendTime,
firstPollInterval: DefaultFirstPollInterval,
firstPollTime: DefaultFirstPollTime,
secondPollInterval: DefaultSecondPollInterval,
secondPollTime: DefaultSecondPollTime,
reConnTime: DefaultReConnectTime,
hrm: *defaultHTTPRequestManager(),
txVersion: DefaultTxVersion,
config: config.Default(),
}
rpc.hrm.nodes = nodes
return rpc
}
// Namespace setter
func (rpc *RPC) Namespace(ns string) *RPC {
rpc.namespace = ns
return rpc
}
// Close close release goroutine and http connection
func (rpc *RPC) Close() {
rpc.hrm.client.CloseIdleConnections()
}
// ResendTimes setter
func (rpc *RPC) ResendTimes(resTime int64) *RPC {
rpc.resTime = resTime
return rpc
}
// FirstPollInterval setter
func (rpc *RPC) FirstPollInterval(fpi int64) *RPC {
rpc.firstPollInterval = fpi
return rpc
}
// FirstPollTime setter
func (rpc *RPC) FirstPollTime(fpt int64) *RPC {
rpc.firstPollTime = fpt
return rpc
}
// SecondPollInterval setter
func (rpc *RPC) SecondPollInterval(spi int64) *RPC {
rpc.secondPollInterval = spi
return rpc
}
// SecondPollTime setter
func (rpc *RPC) SecondPollTime(spt int64) *RPC {
rpc.secondPollTime = spt
return rpc
}
// ReConnTime setter
func (rpc *RPC) ReConnTime(rct int64) *RPC {
rpc.reConnTime = rct
return rpc
}
// Https use sets the https related options
func (rpc *RPC) Https(tlscaPath, tlspeerCertPath, tlspeerPrivPath string) *RPC {
rpc.config.SetIsHttps(true)
rpc.config.SetTlscaPath(tlscaPath)
rpc.config.SetTlspeerCertPath(tlspeerCertPath)
rpc.config.SetTlspeerPrivPath(tlspeerPrivPath)
rpc.hrm.client = newHTTPClient(rpc.config, ".")
rpc.hrm.isHTTP = true
for i := 0; i < len(rpc.hrm.nodes); i++ {
rpc.hrm.nodes[i].url = "https://" + strings.Split(rpc.hrm.nodes[i].url, "//")[1]
}
return rpc
}
func (rpc *RPC) AddNode(url, rpcPort, wsPort string) *RPC {
rpc.hrm.nodes = append(rpc.hrm.nodes, newNode(url, rpcPort, wsPort, rpc.hrm.isHTTP))
return rpc
}
func (rpc *RPC) SetNodePriority(id int, priority int) *RPC {
if id == 0 {
rpc.hrm.nodes[id].SetNodePriority(priority)
} else {
rpc.hrm.nodes[id-1].SetNodePriority(priority)
}
return rpc
}
func (rpc *RPC) Tcert(cfca bool, sdkcertPath, sdkcertPrivPath, uniquePubPath, uniquePrivPath string) *RPC {
vip := viper.New()
vip.Set(common.PrivacyCfca, cfca)
vip.Set(common.PrivacySendTcert, true)
vip.Set(common.PrivacySDKcertPath, sdkcertPath)
vip.Set(common.PrivacySDKcertPrivPath, sdkcertPrivPath)
vip.Set(common.PrivacyUniquePubPath, uniquePubPath)
vip.Set(common.PrivacyUniquePrivPath, uniquePrivPath)
rpc.hrm.tcm = NewTCertManager(vip, ".")
return rpc
}
// BindNodes generate a new RPC instance that bind with given indexes
func (rpc *RPC) BindNodes(nodeIndexes ...int) (*RPC, error) {
if len(nodeIndexes) == 0 {
return rpc, nil
}
proxy := *rpc
proxy.hrm.nodes = make([]*Node, len(nodeIndexes))
proxy.hrm.nodeIndex = 0
limit := len(rpc.hrm.nodes)
for i := 0; i < len(nodeIndexes); i++ {
if nodeIndexes[i] > limit {
return nil, fmt.Errorf("nodeIndex %d is out of range", i)
}
proxy.hrm.nodes[i] = rpc.hrm.nodes[nodeIndexes[i]-1]
}
return &proxy, nil
}
// package method name and params to JsonRequest
func (rpc *RPC) jsonRPC(method string, params ...interface{}) *JSONRequest {
req := &JSONRequest{
Method: method,
Version: JSONRPCVersion,
ID: 1,
Namespace: rpc.namespace,
Params: params,
}
if rpc.im.enable {
auth := &Authentication{
Address: rpc.im.key.GetAddress(),
Timestamp: time.Now().UnixNano(),
}
sig, err := sign(rpc.im.key, authNeedHash(auth), false, false)
if err != nil {
logger.Errorf("sign auth fail")
}
auth.Signature = sig
req.Auth = auth
}
return req
}
func authNeedHash(auth *Authentication) string {
return "address=" + auth.Address.Hex() +
"×tamp=0x" + strconv.FormatInt(auth.Timestamp, 16)
}
// call is a function to get response result commodiously
func (rpc *RPC) call(method string, params ...interface{}) (json.RawMessage, StdError) {
req := rpc.jsonRPC(method, params...)
return rpc.callWithReq(req)
}
// call is a function to get response result commodiously
func (rpc *RPC) callWithTransaction(method string, transaction *Transaction, params ...interface{}) (json.RawMessage, StdError) {
req := rpc.jsonRPC(method, params...)
req.transaction = transaction
return rpc.callWithReq(req)
}
// callWithReq is a function to get response origin data
func (rpc *RPC) callWithReq(req *JSONRequest) (json.RawMessage, StdError) {
body, sysErr := json.Marshal(req)
if sysErr != nil {
return nil, NewSystemError(sysErr)
}
data, err := rpc.hrm.SyncRequest(body)
if err != nil {
return nil, err
}
var resp *JSONResponse
if sysErr = json.Unmarshal(data, &resp); sysErr != nil {
return nil, NewSystemError(sysErr)
}
if resp.Code != SuccessCode {
if req.transaction != nil && (resp.Code == InvalidSignature || (resp.Code == InvalidParams && strings.Contains(strings.ToLower(resp.Message), "version"))) {
preTxVersion := TxVersion
rpc.initGlobal()
if req.transaction.txVersion != TxVersion && preTxVersion != TxVersion {
req.transaction.setTxVersion(TxVersion)
req.transaction.SetSignature("")
req.transaction.Sign(req.transaction.account)
return rpc.call(req.Method, req.transaction.Serialize())
}
}
if resp.Code == ConsensusStatusAbnormal ||
resp.Code == QPSLimit ||
resp.Code == DispatcherFull ||
resp.Code == SimulateLimit {
return rpc.callWithReq(req)
}
return nil, NewServerError(resp.Code, resp.Message)
}
return resp.Result, nil
}
// callWithSpecificUrl is a function to get response form specific url
func (rpc *RPC) callWithSpecificURL(method string, url string, params ...interface{}) (json.RawMessage, StdError) {
req := rpc.jsonRPC(method, params...)
body, sysErr := json.Marshal(req)
if sysErr != nil {
return nil, NewSystemError(sysErr)
}
data, err := rpc.hrm.SyncRequestSpecificURL(body, url, GENERAL, nil, nil)
if err != nil {
return nil, err
}
var resp *JSONResponse
if sysErr = json.Unmarshal(data, &resp); sysErr != nil {
return nil, NewSystemError(sysErr)
}
if resp.Code != SuccessCode {
return nil, NewServerError(resp.Code, resp.Message)
}
return resp.Result, nil
}
func (rpc *RPC) callByPolling(method string, params ...interface{}) (json.RawMessage, StdError) {
req := rpc.jsonRPC(method, params...)
for i := int64(0); i < rpc.resTime; i++ {
resp, err := rpc.callWithReqByPolling(req, rpc.firstPollTime, rpc.firstPollInterval)
if err != nil {
return nil, err
}
if resp != nil {
return resp, nil
}
resp, err = rpc.callWithReqByPolling(req, rpc.secondPollTime, rpc.secondPollInterval)
if err != nil {
return nil, err
}
if resp != nil {
return resp, nil
}
}
return nil, NewRequestTimeoutError(errors.New("request time out"))
}
func (rpc *RPC) callWithReqByPolling(req *JSONRequest, pollingTime int64, pollingInterval int64) (json.RawMessage, StdError) {
for j := int64(0); j < pollingTime; j++ {
resp, err := rpc.callWithReq(req)
if err != nil {
if err.Code() == BalanceInsufficientCode {
return nil, err
} else if err.Code() != DataNotExistCode && err.Code() != SystemBusyCode {
return nil, err
}
time.Sleep(time.Millisecond * time.Duration(pollingInterval))
} else {
return resp, nil
}
}
return nil, nil
}
// Call call and get tx receipt directly without polling
func (rpc *RPC) Call(method string, param interface{}) (*TxReceipt, StdError) {
data, err := rpc.call(method, param)
if err != nil {
return nil, err
}
var receipt TxReceipt
if sysErr := json.Unmarshal(data, &receipt); sysErr != nil {
return nil, NewSystemError(sysErr)
}
return &receipt, nil
}
// callTransaction call and get tx receipt directly without polling
func (rpc *RPC) callTransaction(method string, transaction *Transaction, param interface{}) (*TxReceipt, StdError) {
data, err := rpc.callWithTransaction(method, transaction, param)
if err != nil {
return nil, err
}
var receipt TxReceipt
if sysErr := json.Unmarshal(data, &receipt); sysErr != nil {
return nil, NewSystemError(sysErr)
}
return &receipt, nil
}
// CallByPolling call and get tx receipt by polling
func (rpc *RPC) CallByPolling(method string, param interface{}, isPrivateTx bool) (*TxReceipt, StdError) {
var (
req *JSONRequest
data json.RawMessage
hash string
err StdError
sysErr error
)
// if simulate is false, transaction need to resend
req = rpc.jsonRPC(method, param)
for i := int64(0); i < rpc.resTime; i++ {
if data, err = rpc.callWithReq(req); err != nil {
return nil, err
} else {
if sysErr = json.Unmarshal(data, &hash); sysErr != nil {
return nil, NewSystemError(sysErr)
}
txReceipt, innErr, success := rpc.GetTxReceiptByPolling(hash, isPrivateTx)
err = innErr
if success {
return txReceipt, err
}
continue
}
//if code is -9999 -32001 and -32006, we should sleep then resend
//time.Sleep(time.Millisecond * time.Duration(rpc.firstPollInterval+rpc.secondPollInterval))
}
return nil, NewRequestTimeoutError(errors.New("request time out"))
}
// CallByPolling call and get tx receipt by polling
func (rpc *RPC) callTransactionByPolling(method string, transaction *Transaction, param interface{}) (*TxReceipt, StdError) {
var (
req *JSONRequest
data json.RawMessage
hash string
err StdError
sysErr error
)
// if simulate is false, transaction need to resend
req = rpc.jsonRPC(method, param)
req.transaction = transaction
for i := int64(0); i < rpc.resTime; i++ {
if data, err = rpc.callWithReq(req); err != nil {
return nil, err
} else {
if sysErr = json.Unmarshal(data, &hash); sysErr != nil {
return nil, NewSystemError(sysErr)
}
txReceipt, innErr, success := rpc.GetTxReceiptByPolling(hash, transaction.isPrivateTx)
err = innErr
if success {
return txReceipt, err
}
continue
}
}
return nil, NewRequestTimeoutError(errors.New("request time out"))
}
func (rpc *RPC) GetTxVersion() (string, StdError) {
method := TRANSACTION + "getTransactionsVersion"
data, err := rpc.call(method)
if err != nil {
return "", err
}
var txVersion string
if sysErr := json.Unmarshal(data, &txVersion); sysErr != nil {
return "", NewSystemError(sysErr)
}
return txVersion, nil
}
func (rpc *RPC) GetGasPrice() (int64, error) {
method := TRANSACTION + "getGasPrice"
data, err := rpc.call(method)
if err != nil {
return 0, err
}
var price int64
if sysErr := json.Unmarshal(data, &price); sysErr != nil {
return 0, NewSystemError(sysErr)
}
return price, nil
}
// GetTxReceiptByPolling get tx receipt by polling
func (rpc *RPC) GetTxReceiptByPolling(txHash string, isPrivateTx bool) (*TxReceipt, StdError, bool) {
var (
err StdError
receipt *TxReceipt
)
txHash = chPrefix(txHash)
for j := int64(0); j < rpc.firstPollTime; j++ {
receipt, err = rpc.GetTxReceipt(txHash, isPrivateTx)
if err != nil {
if err.Code() == BalanceInsufficientCode {
return nil, err, true
} else if err.Code() != DataNotExistCode && err.Code() != SystemBusyCode {
return nil, err, true
}
time.Sleep(time.Millisecond * time.Duration(rpc.firstPollInterval))
} else {
return receipt, nil, true
}
}
for j := int64(0); j < rpc.secondPollTime; j++ {
receipt, err = rpc.GetTxReceipt(txHash, isPrivateTx)
if err != nil {
if err.Code() == BalanceInsufficientCode {
return nil, err, true
} else if err.Code() != DataNotExistCode && err.Code() != SystemBusyCode {
return nil, err, true
}
time.Sleep(time.Millisecond * time.Duration(rpc.secondPollInterval))
} else {
return receipt, nil, true
}
}
return nil, NewGetResponseError(errors.New("polling failure")), false
}
/*---------------------------------- node ----------------------------------*/
// GetNodes 获取区块链节点信息
func (rpc *RPC) GetNodes() ([]NodeInfo, StdError) {
data, err := rpc.call(NODE + "getNodes")
if err != nil {
return nil, err
}
var nodeInfo []NodeInfo
if sysErr := json.Unmarshal(data, &nodeInfo); sysErr != nil {
return nil, NewSystemError(sysErr)
}
return nodeInfo, nil
}
// GetNodesNum 获取rpc连接的节点数
func (rpc *RPC) GetNodesNum() int {
return len(rpc.hrm.nodes)
}
// GetNodeHash 获取随机节点hash
func (rpc *RPC) GetNodeHash() (string, StdError) {
data, err := rpc.call(NODE + "getNodeHash")
if err != nil {
return "", err
}
hash := []byte(data)
return string(hash), nil
}
// GetNodeHashByID 从指定节点获取hash
func (rpc *RPC) GetNodeHashByID(id int) (string, StdError) {
url := rpc.hrm.nodes[id-1].url
data, err := rpc.callWithSpecificURL(NODE+"getNodeHash", url)
if err != nil {
return "", err
}
var hash string
if sysErr := json.Unmarshal(data, &hash); sysErr != nil {
return "", NewSystemError(sysErr)
}
return hash, nil
}
// DeleteNodeVP 删除VP节点
// Deprecated
func (rpc *RPC) DeleteNodeVP(hash string) (bool, StdError) {
method := NODE + "deleteVP"
param := newMapParam("nodehash", hash)
_, err := rpc.call(method, param.Serialize())
if err != nil {
return false, err
}
return true, nil
}
// DeleteNodeNVP 删除NVP节点
func (rpc *RPC) DeleteNodeNVP(hash string) (bool, StdError) {
method := NODE + "deleteNVP"
param := newMapParam("nodehash", hash)
_, err := rpc.call(method, param.Serialize())
if err != nil {
return false, err
}
return true, nil
}
// DisconnectNodeVP NVP断开与VP节点的链接
func (rpc *RPC) DisconnectNodeVP(hash string) (bool, StdError) {
method := NODE + "disconnectVP"
param := newMapParam("nodehash", hash)
_, err := rpc.call(method, param.Serialize())
if err != nil {
return false, err
}
return true, nil
}
// GetNodeStates 获取节点状态信息
func (rpc *RPC) GetNodeStates() ([]NodeStateInfo, StdError) {
method := NODE + "getNodeStates"
data, err := rpc.call(method)
if err != nil {
return nil, err
}
var list []NodeStateInfo
if sysErr := json.Unmarshal(data, &list); sysErr != nil {
return nil, NewSystemError(sysErr)
}
return list, nil
}
func (rpc *RPC) ReplaceNodeCerts(hostname string) (string, StdError) {
chash, cerr := rpc.GetNodeHash()
if cerr != nil {
return "", cerr
}
data, err := rpc.GetNodes()
if err != nil {
return "", err
}
for _, val := range data {
if val.HostName == hostname {
if !reflect.DeepEqual("\""+val.Hash+"\"", chash) {
return "", NewSystemError(fmt.Errorf("the binding node's hostname is %s", val.HostName))
}
break
}
}
method := NODE + "replaceCerts"
res, cerr := rpc.call(method)
if cerr != nil {
return "", cerr
}
var hash string
if sysErr := json.Unmarshal(res, &hash); sysErr != nil {
return "", NewSystemError(sysErr)
}
return hash, nil
}
/*---------------------------------- block ----------------------------------*/
// GetLatestBlock returns information about the latest block
func (rpc *RPC) GetLatestBlock() (*Block, StdError) {
method := BLOCK + "latestBlock"
data, stdErr := rpc.call(method)
if stdErr != nil {
return nil, stdErr
}
blockRaw := BlockRaw{}
sysErr := json.Unmarshal(data, &blockRaw)
if sysErr != nil {
return nil, NewSystemError(sysErr)
}
block, stdErr := blockRaw.ToBlock()
if stdErr != nil {
return nil, NewSystemError(sysErr)
}
return block, nil
}
// GetBlocks returns a list of blocks from start block number to end block number
// isPlain indicates if the result includes transaction information. if false, includes, otherwise not.
// Deprecated
func (rpc *RPC) GetBlocks(from, to uint64, isPlain bool) ([]*Block, StdError) {
if from == 0 || to == 0 || to < from {
return nil, NewSystemError(errors.New("to and from should be non-zero integer and to should no more than from"))
}
method := BLOCK + "getBlocks"
mp := newMapParam("from", from)
mp.addKV("to", to)
mp.addKV("isPlain", isPlain)
data, stdErr := rpc.call(method, mp.Serialize())
if stdErr != nil {
return nil, stdErr
}
var blockRaws []BlockRaw
sysErr := json.Unmarshal(data, &blockRaws)
if sysErr != nil {
return nil, NewSystemError(sysErr)
}
blocks := make([]*Block, 0, len(blockRaws))
for _, v := range blockRaws {
block, stdErr := v.ToBlock()
if stdErr != nil {
return nil, stdErr
}
blocks = append(blocks, block)
}
return blocks, nil
}
func (rpc *RPC) GetBlocksWithLimit(from, to uint64, isPlain bool, metadata *Metadata) (*PageResult, StdError) {
if from == 0 || to == 0 || to < from {
return nil, NewSystemError(errors.New("to and from should be non-zero integer and to should no more than from"))
}
method := BLOCK + "getBlocksWithLimit"
mp := newMapParam("from", from)
mp.addKV("to", to)
mp.addKV("isPlain", isPlain)
mp.addKV("matadata", metadata)
data, stdErr := rpc.call(method, mp.Serialize())
if stdErr != nil {
return nil, stdErr
}
var pageResult *PageResult
sysErr := json.Unmarshal(data, &pageResult)
if sysErr != nil {
return nil, NewSystemError(sysErr)
}
return pageResult, nil
}
// GetBlockByHash returns information about a block by hash.
// If the param isPlain value is true, it returns block excluding transactions. If false,
// it returns block including transactions.
func (rpc *RPC) GetBlockByHash(blockHash string, isPlain bool) (*Block, StdError) {
method := BLOCK + "getBlockByHash"
data, stdErr := rpc.call(method, blockHash, isPlain)
if stdErr != nil {
return nil, stdErr
}
blockRaw := BlockRaw{}
if sysErr := json.Unmarshal(data, &blockRaw); sysErr != nil {
return nil, NewSystemError(sysErr)
}
block, stdErr := blockRaw.ToBlock()
if stdErr != nil {
return nil, stdErr
}
return block, nil
}
// GetBatchBlocksByHash returns a list of blocks by a list of specific block hash.
// Deprecated
func (rpc *RPC) GetBatchBlocksByHash(blockHashes []string, isPlain bool) ([]*Block, StdError) {
method := BLOCK + "getBatchBlocksByHash"
mp := newMapParam("hashes", blockHashes)
mp.addKV("isPlain", isPlain)
data, stdErr := rpc.call(method, mp.Serialize())
if stdErr != nil {
return nil, stdErr
}
var blockRaws []BlockRaw
sysErr := json.Unmarshal(data, &blockRaws)
if sysErr != nil {
return nil, NewSystemError(sysErr)
}
blocks := make([]*Block, 0, len(blockRaws))
for _, v := range blockRaws {
block, stdErr := v.ToBlock()
if stdErr != nil {
return nil, stdErr
}
blocks = append(blocks, block)
}
return blocks, nil
}
// GetBlockByNumber returns information about a block by number. If the param isPlain
// value is true, it returns block excluding transactions. If false, it returns block
// including transactions.
// blockNum can use `latest`, means get latest block
func (rpc *RPC) GetBlockByNumber(blockNum interface{}, isPlain bool) (*Block, StdError) {
method := BLOCK + "getBlockByNumber"
data, stdErr := rpc.call(method, blockNum, isPlain)
if stdErr != nil {
return nil, stdErr
}
var blockRaw BlockRaw
sysErr := json.Unmarshal(data, &blockRaw)
if sysErr != nil {
return nil, NewSystemError(sysErr)
}
block, stdErr := blockRaw.ToBlock()
if stdErr != nil {
return nil, stdErr
}
return block, nil
}
// GetBatchBlocksByNumber returns a list of blocks by a list of specific block number.
// Deprecated
func (rpc *RPC) GetBatchBlocksByNumber(blockNums []uint64, isPlain bool) ([]*Block, StdError) {
method := BLOCK + "getBatchBlocksByNumber"
mp := newMapParam("numbers", blockNums)
mp.addKV("isPlain", isPlain)
data, stdErr := rpc.call(method, mp.Serialize())
if stdErr != nil {
return nil, stdErr
}
var blockRaws []BlockRaw
sysErr := json.Unmarshal(data, &blockRaws)
if sysErr != nil {
return nil, NewSystemError(sysErr)
}
blocks := make([]*Block, 0, len(blockRaws))
for _, v := range blockRaws {
block, stdErr := v.ToBlock()
if stdErr != nil {
return nil, stdErr
}
blocks = append(blocks, block)
}
return blocks, nil
}