OSDN Git Service

Merge pull request #41 from Bytom/dev
[bytom/vapor.git] / util / call_rpc.go
1 package util
2
3 import (
4         "context"
5         "encoding/json"
6         "errors"
7         "fmt"
8         "strconv"
9
10         jww "github.com/spf13/jwalterweatherman"
11         "github.com/vapor/blockchain/rpc"
12         "github.com/vapor/config"
13 )
14
15 var MainchainConfig *config.MainChainRpcConfig
16 var ValidatePegin bool
17
18 // Response describes the response standard.
19 type Response struct {
20         Status      string      `json:"status,omitempty"`
21         Code        string      `json:"code,omitempty"`
22         Msg         string      `json:"msg,omitempty"`
23         ErrorDetail string      `json:"error_detail,omitempty"`
24         Data        interface{} `json:"data,omitempty"`
25 }
26
27 // CallRPC call api.
28 func CallRPC(path string, req ...interface{}) (interface{}, error) {
29
30         host := MainchainConfig.MainchainRpcHost
31         port, _ := strconv.ParseUint(MainchainConfig.MainchainRpcPort, 10, 16)
32         token := MainchainConfig.MainchainToken
33
34         var resp = &Response{}
35         var request interface{}
36
37         if req != nil {
38                 request = req[0]
39         }
40
41         // TODO主链的ip port token
42         rpcURL := fmt.Sprintf("http://%s:%d", host, port)
43         client := &rpc.Client{BaseURL: rpcURL}
44         client.AccessToken = token
45         client.Call(context.Background(), path, request, resp)
46         switch resp.Status {
47         case "fail":
48                 jww.ERROR.Println(resp.Msg)
49                 return nil, errors.New("fail")
50         case "":
51                 jww.ERROR.Println("Unable to connect to the bytomd")
52                 return nil, errors.New("")
53         }
54         return resp.Data, nil
55 }
56
57 func IsConfirmedBytomBlock(txHeight uint64, nMinConfirmationDepth uint64) error {
58         data, exitCode := CallRPC("get-block-count")
59         if exitCode != nil {
60                 return exitCode
61         }
62         type blockHeight struct {
63                 BlockCount uint64 `json:"block_count"`
64         }
65         var mainchainHeight blockHeight
66         tmp, _ := json.Marshal(data)
67         json.Unmarshal(tmp, &mainchainHeight)
68         if mainchainHeight.BlockCount < txHeight || (mainchainHeight.BlockCount-txHeight) < nMinConfirmationDepth {
69                 return errors.New("Peg-in bytom transaction needs more confirmations to be sent")
70         }
71         return nil
72 }