forked from mintme-com/webchaind
/
apicmd.go
141 lines (120 loc) · 3.59 KB
/
apicmd.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
// Copyright 2017 The go-ethereum Authors
// Copyright 2018 Webchain project
// This file is part of Webchain.
//
// Webchain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Webchain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Webchain. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"strconv"
"strings"
"gopkg.in/urfave/cli.v1"
"os"
"github.com/webchain-network/webchaind/node"
"github.com/webchain-network/webchaind/rpc"
)
var (
apiCommand = cli.Command{
Action: execAPI,
Name: "api",
Usage: "Run any API command",
Description: `
The api command allows you to communicate (via IPC) with a running webchaind instance
and run any RPC API method.
Each parameter should be passed as JSON representation:
- no quotations for numbers or booleans,
- strings must be correctly quoted, like '"some value"' (quotes must be
included in string passed to application),
- complex objects could be passed as JSON string.
Examples:
$ webchaind api webchain getBlockByNumber 123 true
$ webchaind webchain getBlockByNumber '"latest"' true
$ webchaind --chain morden api webchain sendTransaction '{"from": "0x396599f365093186742c17aab158bf515e978bc7", "gas": "0x5208", "gasPrice": "0x02540be400", "to": "0xa02cee0fc1d3fb4dde86b79fe93e4140671fd949"}'
Output will be written to stderr in JSON format.
`,
}
)
func execAPI(ctx *cli.Context) error {
client, err := getClient(ctx)
if err != nil {
return err
}
if err := validateArguments(ctx, client); err != nil {
return err
}
result, err := callRPC(ctx, client)
if err != nil {
return err
}
return prettyPrint(result)
}
func getClient(ctx *cli.Context) (rpc.Client, error) {
chainDir := MustMakeChainDataDir(ctx)
var uri = "ipc:" + node.DefaultIPCEndpoint(chainDir)
return rpc.NewClient(uri)
}
func validateArguments(ctx *cli.Context, client rpc.Client) error {
if len(ctx.Args()) < 2 {
return fmt.Errorf("api command requires at least 2 arguments (module and method), %d provided",
len(ctx.Args()))
}
modules, err := client.SupportedModules()
if err != nil {
return err
}
module := ctx.Args()[0]
if _, ok := modules[module]; !ok {
return fmt.Errorf("unknown API module: %s", module)
}
return nil
}
func callRPC(ctx *cli.Context, client rpc.Client) (interface{}, error) {
var (
module = ctx.Args()[0]
method = ctx.Args()[1]
args = ctx.Args()[2:]
)
req := rpc.JSONRequest{
Id: json.RawMessage(strconv.Itoa(rand.Int())),
Method: module + "_" + method,
Version: "2.0",
Payload: json.RawMessage("[" + strings.Join(args, ",") + "]"),
}
if err := client.Send(req); err != nil {
return nil, err
}
var res rpc.JSONResponse
if err := client.Recv(&res); err != nil {
return nil, err
}
if res.Error != nil {
return nil, fmt.Errorf("error in %s_%s: %s (code: %d)",
module, method, res.Error.Message, res.Error.Code)
}
if res.Result != nil {
return res.Result, nil
}
return nil, errors.New("no API response")
}
func prettyPrint(result interface{}) error {
jsonBytes, err := json.MarshalIndent(result, "", " ")
if err != nil {
return err
}
os.Stderr.Write(jsonBytes)
return nil
}