/
service.go
372 lines (329 loc) · 9.09 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
/*
* Copyright (C) 2018 The ontology Authors
* This file is part of The ontology library.
*
* The ontology is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ontology 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The ontology. If not, see <http://www.gnu.org/licenses/>.
*/
package graphql
import (
"net"
"net/http"
"strconv"
"github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/relay"
"github.com/ontio/ontology/common"
"github.com/ontio/ontology/common/config"
"github.com/ontio/ontology/common/log"
"github.com/ontio/ontology/core/payload"
"github.com/ontio/ontology/core/types"
"github.com/ontio/ontology/http/base/actor"
comm "github.com/ontio/ontology/http/base/common"
"github.com/ontio/ontology/http/graphql/schema"
"github.com/ontio/ontology/smartcontract/service/native/utils"
"golang.org/x/net/netutil"
)
var ontSchema *graphql.Schema
func init() {
resolver := &resolver{}
s, err := schema.Asset("schema.graphql")
if err != nil {
panic(err)
}
ontSchema = graphql.MustParseSchema(string(s), resolver, graphql.UseFieldResolvers())
}
type resolver struct{}
type block struct {
Header *header
Transactions []*transaction
}
type header struct {
Version Uint32
Hash H256
PrevHash H256
Height Uint32
Timestamp Uint32
BlockRoot H256
TxsRoot H256
ConsensusData Uint64
NextBookkeeper Addr
Bookkeepers []PubKey
SigData []string
}
type invokeCodePayload struct {
Code string
}
type deployCodePayload struct {
Code string
VmType string
Name string
Version string
Author string
Email string
Desc string
}
type TxPayload struct {
pl interface{}
}
func (self *TxPayload) ToInvokeCode() (*invokeCodePayload, bool) {
pl, ok := self.pl.(*invokeCodePayload)
return pl, ok
}
func (self *TxPayload) ToDeployCode() (*deployCodePayload, bool) {
pl, ok := self.pl.(*deployCodePayload)
return pl, ok
}
func (self *TxPayload) Code() string {
switch pd := self.pl.(type) {
case *invokeCodePayload:
return pd.Code
case *deployCodePayload:
return pd.Code
default:
panic("unreachable")
}
}
func NewTxPayload(pl types.Payload) *TxPayload {
switch val := pl.(type) {
case *payload.InvokeCode:
return &TxPayload{pl: &invokeCodePayload{Code: common.ToHexString(val.Code)}}
case *payload.DeployCode:
vmty := "Neo"
if val.VmType() == payload.WASMVM_TYPE {
vmty = "Wasm"
}
dp := &deployCodePayload{
Code: common.ToHexString(val.GetRawCode()),
VmType: vmty,
Name: val.Name,
Version: val.Version,
Author: val.Author,
Email: val.Email,
Desc: val.Description,
}
return &TxPayload{pl: dp}
default:
panic("unreachable")
}
}
func NewTransaction(tx *types.Transaction, height uint32) *transaction {
ty := convTxType(tx)
var sigs []*Sig
for _, val := range tx.Sigs {
sig, err := val.GetSig()
if err == nil {
var sigdata []string
for _, data := range sig.SigData {
sigdata = append(sigdata, common.ToHexString(data))
}
var pubkey []PubKey
for _, val := range sig.PubKeys {
pubkey = append(pubkey, PubKey(common.PubKeyToHex(val)))
}
sigs = append(sigs, &Sig{
SigData: sigdata,
PubKeys: pubkey,
M: Uint32(sig.M),
})
}
}
t := &transaction{
Version: Uint32(tx.Version),
Hash: H256(tx.Hash()),
Nonce: Uint32(tx.Nonce),
TxType: ty,
GasPrice: Uint32(tx.GasPrice),
GasLimit: Uint32(tx.GasLimit),
Payer: Addr{tx.Payer},
Payload: NewTxPayload(tx.Payload),
Sigs: sigs,
Height: Uint32(height),
}
return t
}
func NewBlock(b *types.Block) *block {
var txs []*transaction
for _, tx := range b.Transactions {
txs = append(txs, NewTransaction(tx, b.Header.Height))
}
return &block{
Header: NewHeader(b.Header),
Transactions: txs,
}
}
func NewHeader(h *types.Header) *header {
var pubKeys []PubKey
for _, k := range h.Bookkeepers {
pubKeys = append(pubKeys, PubKey(common.PubKeyToHex(k)))
}
var sigData []string
for _, sig := range h.SigData {
sigData = append(sigData, common.ToHexString(sig))
}
hd := &header{
Version: Uint32(h.Version),
Hash: H256(h.Hash()),
PrevHash: H256(h.PrevBlockHash),
Height: Uint32(h.Height),
Timestamp: Uint32(h.Timestamp),
BlockRoot: H256(h.BlockRoot),
TxsRoot: H256(h.TransactionsRoot),
ConsensusData: Uint64(h.ConsensusData),
NextBookkeeper: Addr{h.NextBookkeeper},
Bookkeepers: pubKeys,
SigData: sigData,
}
return hd
}
func (self *resolver) GetBlockByHeight(args struct{ Height Uint32 }) (*block, error) {
b, err := actor.GetBlockByHeight(uint32(args.Height))
if err != nil {
return nil, err
}
return NewBlock(b), nil
}
func (self *resolver) GetBlockByHash(args struct{ Hash H256 }) (*block, error) {
b, err := actor.GetBlockFromStore(common.Uint256(args.Hash))
if err != nil {
return nil, err
}
return NewBlock(b), nil
}
func (self *resolver) GetBlockHash(args struct{ Height Uint32 }) H256 {
return H256(actor.GetBlockHashFromStore(uint32(args.Height)))
}
type balance struct {
Ont Uint64
Ong Uint64
Height Uint32
}
type TxType string
const INVOKE_NEO TxType = "INVOKE_NEO"
const INVOKE_WASM TxType = "INVOKE_WASM"
const DEPLOY_NEO TxType = "DEPLOY_NEO"
const DEPLOY_WASM TxType = "DEPLOY_WASM"
func convTxType(tx *types.Transaction) TxType {
switch pl := tx.Payload.(type) {
case *payload.InvokeCode:
if tx.TxType == types.InvokeNeo {
return INVOKE_NEO
} else {
return INVOKE_WASM
}
case *payload.DeployCode:
switch pl.VmType() {
case payload.NEOVM_TYPE:
return DEPLOY_NEO
case payload.WASMVM_TYPE:
return DEPLOY_WASM
default:
panic("unreachable")
}
default:
panic("unreachable")
}
}
type transaction struct {
Version Uint32
Hash H256
Nonce Uint32
TxType TxType
GasPrice Uint32
GasLimit Uint32
Payer Addr
Payload *TxPayload
Sigs []*Sig
Height Uint32
}
type Sig struct {
SigData []string
PubKeys []PubKey
M Uint32
}
func (self *resolver) GetTx(args struct{ Hash H256 }) (*transaction, error) {
height, tx, err := actor.GetTxnWithHeightByTxHash(common.Uint256(args.Hash))
if err != nil {
return nil, err
}
return NewTransaction(tx, height), nil
}
func (self *resolver) GetBalance(args struct{ Addr Addr }) (*balance, error) {
balances, height, err := comm.GetNativeTokenBalance(0,
[]common.Address{utils.OntContractAddress, utils.OngContractAddress}, args.Addr.Address, true)
if err != nil {
return nil, err
}
return &balance{
Height: Uint32(height),
Ont: Uint64(balances[0].MustToInteger64()),
Ong: Uint64(balances[1].MustToInteger64()),
}, nil
}
func StartServer(cfg *config.GraphQLConfig) {
if !cfg.EnableGraphQL || cfg.GraphQLPort == 0 {
return
}
serverMut := http.NewServeMux()
serverMut.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(page)
}))
serverMut.Handle("/query", &relay.Handler{Schema: ontSchema})
server := &http.Server{Handler: serverMut}
listener, err := net.Listen("tcp", ":"+strconv.Itoa(int(cfg.GraphQLPort)))
if err != nil {
log.Error("start graphql server error: %s", err)
return
}
if cfg.MaxConnections > 0 {
listener = netutil.LimitListener(listener, int(cfg.MaxConnections))
}
log.Infof("start GraphQL service on %d", cfg.GraphQLPort)
log.Error(server.Serve(listener))
}
var page = []byte(`
<!DOCTYPE html>
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-promise/4.1.1/es6-promise.auto.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.min.js"></script>
</head>
<body style="width: 100%; height: 100%; margin: 0; overflow: hidden;">
<div id="graphiql" style="height: 100vh;">Loading...</div>
<script>
function graphQLFetcher(graphQLParams) {
return fetch("/query", {
method: "post",
body: JSON.stringify(graphQLParams),
credentials: "include",
}).then(function (response) {
return response.text();
}).then(function (responseBody) {
try {
return JSON.parse(responseBody);
} catch (error) {
return responseBody;
}
});
}
ReactDOM.render(
React.createElement(GraphiQL, {fetcher: graphQLFetcher}),
document.getElementById("graphiql")
);
</script>
</body>
</html>
`)