/
api_handler.go
618 lines (561 loc) · 19.5 KB
/
api_handler.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
// Copyright FISCO-BCOS go-sdk
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package client provides a client for the FISCO BCOS RPC API.
package client
import (
"context"
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"time"
"github.com/ningxin18/go-bcos-sdk/conn"
"github.com/ningxin18/go-bcos-sdk/core/types"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/rlp"
)
// APIHandler defines typed wrappers for the FISCO BCOS RPC API.
type APIHandler struct {
*conn.Connection
}
const (
indent = " "
BlockLimit int64 = 600
)
// NewAPIHandler create a new API handler
func NewAPIHandler(c *conn.Connection) *APIHandler {
apiHandler := APIHandler{c}
return &apiHandler
}
func toCallArg(msg ethereum.CallMsg) interface{} {
arg := map[string]interface{}{
"from": msg.From.String(),
"to": msg.To.String(),
}
if len(msg.Data) > 0 {
arg["data"] = hexutil.Bytes(msg.Data).String()
}
if msg.Value != nil {
arg["value"] = (*hexutil.Big)(msg.Value).String()
}
if msg.Gas != 0 {
arg["gas"] = hexutil.Uint64(msg.Gas)
}
if msg.GasPrice != nil {
arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
}
return arg
}
type callResult struct {
CurrentBlockNumber string `json:"currentBlockNumber"`
Output string `json:"output"`
Status string `json:"status"`
}
// Call invoke the call method of rpc api
func (api *APIHandler) Call(ctx context.Context, groupID int, msg ethereum.CallMsg) ([]byte, error) {
var hexBytes hexutil.Bytes
var cr *callResult
err := api.CallContext(ctx, &cr, "call", groupID, toCallArg(msg))
if err != nil {
return nil, err
}
if cr.Status != "0x0" {
var errorMessage string
if len(cr.Output) >= 138 {
outputBytes, err := hex.DecodeString(cr.Output[2:])
if err != nil {
return nil, fmt.Errorf("call error of status %s, hex.DecodeString failed", cr.Status)
}
errorMessage = string(outputBytes[68:])
}
return nil, fmt.Errorf("call error of status %s, %v", cr.Status, errorMessage)
}
hexBytes = common.FromHex(cr.Output)
return hexBytes, nil
}
// SendRawTransaction injects a signed transaction into the pending pool for execution.
//
// If the transaction was a contract creation use the TransactionReceipt method to get the
// contract address after the transaction has been mined.
func (api *APIHandler) SendRawTransaction(ctx context.Context, groupID int, tx *types.Transaction) (*types.Receipt, error) {
data, err := rlp.EncodeToBytes(tx)
if err != nil {
fmt.Printf("rlp encode tx error!")
return nil, err
}
var receipt *types.Receipt
if api.IsHTTP() {
err = api.CallContext(ctx, nil, "sendRawTransaction", groupID, hexutil.Encode(data))
if err != nil {
return nil, err
}
// timer to wait transaction on-chain
queryTicker := time.NewTicker(time.Second)
defer queryTicker.Stop()
for {
receipt, err := api.GetTransactionReceipt(ctx, groupID, tx.Hash().Hex())
if receipt != nil {
return receipt, nil
}
if err != nil {
errorStr := fmt.Sprintf("%s", err)
if strings.Contains(errorStr, "connection refused") {
return nil, err
}
//fmt.Printf("Receipt retrieval failed, err: %v\n", err)
} else {
fmt.Println("Transaction not yet mined")
}
// Wait for the next round.
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-queryTicker.C:
}
}
} else {
var anonymityReceipt = &struct {
types.Receipt
Status string `json:"status"`
}{}
err = api.CallContext(ctx, anonymityReceipt, "sendRawTransaction", groupID, hexutil.Encode(data))
if err != nil {
return nil, err
}
status, err := strconv.ParseInt(anonymityReceipt.Status[2:], 16, 32)
if err != nil {
return nil, fmt.Errorf("SendRawTransaction failed, strconv.ParseInt err: " + fmt.Sprint(err))
}
receipt = &anonymityReceipt.Receipt
receipt.Status = int(status)
return receipt, nil
}
}
func (api *APIHandler) SendRawTransaction_bcos(ctx context.Context, groupID int, data string) (string, error) {
var r string
err := api.CallContext(ctx, &r, "sendRawTransaction", groupID, data)
if err != nil {
return r, err
}
return r, nil
}
func (api *APIHandler) AsyncSendRawTransaction(ctx context.Context, groupID int, tx *types.Transaction, handler func(*types.Receipt, error)) error {
data, err := rlp.EncodeToBytes(tx)
if err != nil {
fmt.Printf("rlp encode tx error!")
return err
}
if api.IsHTTP() {
err = api.CallContext(ctx, nil, "sendRawTransaction", groupID, hexutil.Encode(data))
if err != nil {
return nil
}
var receipt *types.Receipt
go func() {
for {
receipt, err = api.GetTransactionReceipt(ctx, groupID, tx.Hash().Hex())
if receipt != nil {
handler(receipt, nil)
return
}
if err != nil {
errorStr := fmt.Sprintf("%s", err)
if strings.Contains(errorStr, "connection refused") {
handler(nil, errors.New("connection refused"))
return
}
}
}
}()
} else {
err = api.AsyncSendTransaction(ctx, handler, "sendRawTransaction", groupID, hexutil.Encode(data))
if err != nil {
return err
}
}
return nil
}
// TransactionReceipt returns the receipt of a transaction by transaction hash.
// Note that the receipt is not available for pending transactions.
func (api *APIHandler) TransactionReceipt(ctx context.Context, groupID int, txHash common.Hash) (*types.Receipt, error) {
var r *types.Receipt
err := api.CallContext(ctx, &r, "getTransactionReceipt", groupID, txHash.Hex())
if err == nil && r == nil {
return nil, fmt.Errorf("TransactionReceipt failed, transaction not found, txHash is: %v, receipt is: %+v", txHash.Hex(), r)
}
return r, err
}
func (api *APIHandler) SubscribeTopic(topic string, handler func([]byte)) error {
return api.Connection.SubscribeTopic(topic, handler)
}
func (api *APIHandler) SubscribePrivateTopic(topic string, privateKey *ecdsa.PrivateKey, handler func([]byte)) error {
return api.Connection.SubscribePrivateTopic(topic, privateKey, handler)
}
func (api *APIHandler) PublishPrivateTopic(topic string, publicKey []*ecdsa.PublicKey) error {
return api.Connection.PublishPrivateTopic(topic, publicKey)
}
func (api *APIHandler) UnsubscribeTopic(topic string) error {
return api.Connection.UnsubscribeTopic(topic)
}
func (api *APIHandler) UnsubscribePrivateTopic(topic string) error {
return api.Connection.UnsubscribePrivateTopic(topic)
}
func (api *APIHandler) SendAMOPMsg(topic string, data []byte) error {
return api.Connection.SendAMOPMsg(topic, data)
}
func (api *APIHandler) BroadcastAMOPMsg(topic string, data []byte) error {
return api.Connection.BroadcastAMOPMsg(topic, data)
}
func (api *APIHandler) SendAMOPPrivateMsg(topic string, data []byte) error {
return api.Connection.SendAMOPPrivateMsg(topic, data)
}
func (api *APIHandler) BroadcastAMOPPrivateMsg(topic string, data []byte) error {
return api.Connection.BroadcastAMOPPrivateMsg(topic, data)
}
func (api *APIHandler) SubscribeBlockNumberNotify(groupID uint64, handler func(int64)) error {
return api.Connection.SubscribeBlockNumberNotify(groupID, handler)
}
func (api *APIHandler) UnsubscribeBlockNumberNotify(groupID uint64) error {
return api.Connection.UnsubscribeBlockNumberNotify(groupID)
}
// GetClientVersion returns the version of FISCO BCOS running on the nodes.
func (api *APIHandler) GetClientVersion(ctx context.Context) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getClientVersion")
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetChainID returns the Chain ID of the FISCO BCOS running on the nodes.
func (api *APIHandler) GetChainID(ctx context.Context) (*big.Int, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getClientVersion")
if err != nil {
return nil, err
}
m, ok := raw.(map[string]interface{})
if !ok {
return nil, errors.New("GetChainID Json respond does not satisfy the type assertion: map[string]interface{}")
}
var temp interface{}
temp, ok = m["Chain Id"]
if !ok {
return nil, errors.New("JSON respond does not contains the key : Chain Id")
}
var strChainid string
strChainid, ok = temp.(string)
if !ok {
return nil, errors.New("type assertion for Chain Id is wrong: not a string")
}
convertor := new(big.Int)
var chainid *big.Int
chainid, ok = convertor.SetString(strChainid, 10)
if !ok {
return nil, errors.New("big.Int.SetString(): error for Chain Id")
}
return chainid, nil
}
// GetBlockNumber returns the latest block height(hex format) on a given groupID.
func (api *APIHandler) GetBlockNumber(ctx context.Context, groupID int) ([]byte, error) {
var raw string
err := api.CallContext(ctx, &raw, "getBlockNumber", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
func (api *APIHandler) GetBlockNumberInt(ctx context.Context, groupID int) (*big.Int, error) {
var raw hexutil.Big
err := api.CallContext(ctx, &raw, "getBlockNumber", groupID)
if err != nil {
return nil, err
}
return (*big.Int)(&raw), nil
}
// GetBlockLimit returns the blocklimit for current blocknumber
func (api *APIHandler) GetBlockLimit(ctx context.Context, groupID int) (*big.Int, error) {
var blockLimit *big.Int
if !api.IsHTTP() {
blockNumber := api.Connection.GetBlockNumber()
if blockNumber != 0 {
blockLimit = big.NewInt(blockNumber + BlockLimit)
return blockLimit, nil
}
}
defaultNumber := big.NewInt(BlockLimit)
var raw hexutil.Big
err := api.CallContext(ctx, &raw, "getBlockNumber", groupID)
if err != nil {
return nil, err
}
blockLimit = defaultNumber.Add(defaultNumber, (*big.Int)(&raw))
return blockLimit, nil
}
// GetPBFTView returns the latest PBFT view(hex format) of the specific group and it will returns a wrong sentence
// if the consensus algorithm is not the PBFT.
func (api *APIHandler) GetPBFTView(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getPbftView", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
// TODO
// Raft consensus
}
// GetSealerList returns the list of consensus nodes' ID according to the groupID
func (api *APIHandler) GetSealerList(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getSealerList", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetObserverList returns the list of observer nodes' ID according to the groupID
func (api *APIHandler) GetObserverList(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getObserverList", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetConsensusStatus returns the status information about the consensus algorithm on a specific groupID
func (api *APIHandler) GetConsensusStatus(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getConsensusStatus", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetSyncStatus returns the synchronization status of the group
func (api *APIHandler) GetSyncStatus(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getSyncStatus", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetPeers returns the information of the connected peers
func (api *APIHandler) GetPeers(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getPeers", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetGroupPeers returns the nodes and the overser nodes list on a specific group
func (api *APIHandler) GetGroupPeers(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getGroupPeers", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetNodeIDList returns the ID information of the connected peers and itself
func (api *APIHandler) GetNodeIDList(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getNodeIDList", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetGroupList returns the groupID list that the node belongs to
func (api *APIHandler) GetGroupList(ctx context.Context) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getGroupList")
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetBlockByHash returns the block information according to the given block hash
func (api *APIHandler) GetBlockByHash(ctx context.Context, groupID int, bhash string, includetx bool) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getBlockByHash", groupID, bhash, includetx)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetBlockByNumber returns the block information according to the given block number(hex format)
func (api *APIHandler) GetBlockByNumber(ctx context.Context, groupID int, bnum string, includetx bool) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getBlockByNumber", groupID, bnum, includetx)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetBlockHashByNumber returns the block hash according to the given block number
func (api *APIHandler) GetBlockHashByNumber(ctx context.Context, groupID int, bnum string) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getBlockHashByNumber", groupID, bnum)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetTransactionByHash returns the transaction information according to the given transaction hash
func (api *APIHandler) GetTransactionByHash(ctx context.Context, groupID int, txhash string) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getTransactionByHash", groupID, txhash)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetTransactionByBlockHashAndIndex returns the transaction information according to
// the given block hash and transaction index
func (api *APIHandler) GetTransactionByBlockHashAndIndex(ctx context.Context, groupID int, bhash string, txindex string) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getTransactionByBlockHashAndIndex", groupID, bhash, txindex)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetTransactionByBlockNumberAndIndex returns the transaction information according to
// the given block number and transaction index
func (api *APIHandler) GetTransactionByBlockNumberAndIndex(ctx context.Context, groupID int, bnum string, txindex string) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getTransactionByBlockNumberAndIndex", groupID, bnum, txindex)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetTransactionReceipt returns the transaction receipt according to the given transaction hash
func (api *APIHandler) GetTransactionReceipt(ctx context.Context, groupID int, txhash string) (*types.Receipt, error) {
var raw *types.Receipt
var anonymityReceipt = &struct {
types.Receipt
Status string `json:"status"`
}{}
err := api.CallContext(ctx, anonymityReceipt, "getTransactionReceipt", groupID, txhash)
if err != nil {
return nil, err
}
if len(anonymityReceipt.Status) < 2 {
return nil, fmt.Errorf("transaction %v is not on-chain", txhash)
}
status, err := strconv.ParseInt(anonymityReceipt.Status[2:], 16, 32)
if err != nil {
return nil, fmt.Errorf("GetTransactionReceipt failed, strconv.ParseInt err: " + fmt.Sprint(err))
}
raw = &anonymityReceipt.Receipt
raw.Status = int(status)
return raw, err
}
// GetContractAddress returns a contract address according to the transaction hash
func (api *APIHandler) GetContractAddress(ctx context.Context, groupID int, txhash string) (common.Address, error) {
var raw interface{}
var contractAddress common.Address
err := api.CallContext(ctx, &raw, "getTransactionReceipt", groupID, txhash)
if err != nil {
return contractAddress, err
}
m, ok := raw.(map[string]interface{})
if !ok {
return contractAddress, fmt.Errorf("GetContractAddress Json respond does not satisfy the type assertion: map[string]interface{}, %+v", raw)
}
var temp interface{}
temp, ok = m["contractAddress"]
if !ok {
return contractAddress, errors.New("Json respond does not contains the key : contractAddress")
}
var strContractAddress string
strContractAddress, ok = temp.(string)
if !ok {
return contractAddress, errors.New("type assertion for Chain Id is wrong: not a string")
}
return common.HexToAddress(strContractAddress), nil
}
// GetPendingTransactions returns information of the pending transactions
func (api *APIHandler) GetPendingTransactions(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getPendingTransactions", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetPendingTxSize returns amount of the pending transactions
func (api *APIHandler) GetPendingTxSize(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getPendingTxSize", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetCode returns the contract code according to the contract address
func (api *APIHandler) GetCode(ctx context.Context, groupID int, addr string) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getCode", groupID, addr)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetTotalTransactionCount returns the totoal amount of transactions and the block height at present
func (api *APIHandler) GetTotalTransactionCount(ctx context.Context, groupID int) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getTotalTransactionCount", groupID)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}
// GetSystemConfigByKey returns value according to the key(only tx_count_limit, tx_gas_limit could work)
func (api *APIHandler) GetSystemConfigByKey(ctx context.Context, groupID int, configKey string) ([]byte, error) {
var raw interface{}
err := api.CallContext(ctx, &raw, "getSystemConfigByKey", groupID, configKey)
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(raw, "", indent)
return js, err
}