forked from eoscanada/eos-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
493 lines (413 loc) · 12.9 KB
/
api.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
package eos
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"sync"
"time"
"github.com/eoscanada/eos-go/ecc"
)
type API struct {
HttpClient *http.Client
BaseURL string
WalletURL string
Signer Signer
Debug bool
Compress CompressionType
DefaultMaxCPUUsageMS uint8
DefaultMaxNetUsageWords uint32 // in 8-bytes words
lastGetInfo *InfoResp
lastGetInfoStamp time.Time
lastGetInfoLock sync.Mutex
customGetRequiredKeys func(tx *Transaction) ([]ecc.PublicKey, error)
}
func New(baseURL string) *API {
api := &API{
HttpClient: &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DisableKeepAlives: true, // default behavior, because of `nodeos`'s lack of support for Keep alives.
},
},
BaseURL: baseURL,
Compress: CompressionZlib,
}
return api
}
// FixKeepAlives tests the remote server for keepalive support (the
// main `nodeos` software doesn't in the version from March 22nd
// 2018). Some endpoints front their node with a keep-alive
// supporting web server. Adjust the `KeepAlive` support of the
// client accordingly.
func (api *API) FixKeepAlives() bool {
// Yeah, to provoke a keep alive, you need to query twice.
for i := 0; i < 5; i++ {
_, err := api.GetInfo()
if api.Debug {
log.Println("err", err)
}
if err == io.EOF {
if tr, ok := api.HttpClient.Transport.(*http.Transport); ok {
tr.DisableKeepAlives = true
return true
}
}
_, err = api.GetNetConnections()
if api.Debug {
log.Println("err", err)
}
if err == io.EOF {
if tr, ok := api.HttpClient.Transport.(*http.Transport); ok {
tr.DisableKeepAlives = true
return true
}
}
}
return false
}
func (api *API) EnableKeepAlives() bool {
if tr, ok := api.HttpClient.Transport.(*http.Transport); ok {
tr.DisableKeepAlives = false
return true
}
return false
}
func (api *API) SetCustomGetRequiredKeys(f func(tx *Transaction) ([]ecc.PublicKey, error)) {
api.customGetRequiredKeys = f
}
func (api *API) SetSigner(s Signer) {
api.Signer = s
}
func (api *API) SetWalletUrl(walletUrl string) {
api.WalletURL = walletUrl
}
// ProducerPause will pause block production on a nodeos with
// `producer_api` plugin loaded.
func (api *API) ProducerPause() error {
return api.call("producer", "pause", nil, nil)
}
// ProducerResume will resume block production on a nodeos with
// `producer_api` plugin loaded. Obviously, this needs to be a
// producing node on the producers schedule for it to do anything.
func (api *API) ProducerResume() error {
return api.call("producer", "resume", nil, nil)
}
// IsProducerPaused queries the blockchain for the pause statement of
// block production.
func (api *API) IsProducerPaused() (out bool, err error) {
err = api.call("producer", "paused", nil, &out)
return
}
func (api *API) GetAccount(name AccountName) (out *AccountResp, err error) {
err = api.call("chain", "get_account", M{"account_name": name}, &out)
return
}
func (api *API) GetCode(account AccountName) (out *GetCodeResp, err error) {
err = api.call("chain", "get_code", M{"account_name": account, "code_as_wasm": true}, &out)
return
}
func (api *API) GetABI(account AccountName) (out *GetABIResp, err error) {
err = api.call("chain", "get_abi", M{"account_name": account}, &out)
return
}
// WalletImportKey loads a new WIF-encoded key into the wallet.
func (api *API) WalletImportKey(walletName, wifPrivKey string) (err error) {
return api.call("wallet", "import_key", []string{walletName, wifPrivKey}, nil)
}
func (api *API) WalletPublicKeys() (out []ecc.PublicKey, err error) {
var textKeys []string
err = api.call("wallet", "get_public_keys", nil, &textKeys)
if err != nil {
return nil, err
}
for _, k := range textKeys {
newKey, err := ecc.NewPublicKey(k)
if err != nil {
return nil, err
}
out = append(out, newKey)
}
return
}
func (api *API) ListKeys() (out []*ecc.PrivateKey, err error) {
var textKeys []string
err = api.call("wallet", "list_keys", nil, &textKeys)
if err != nil {
return nil, err
}
for _, k := range textKeys {
newKey, err := ecc.NewPrivateKey(k)
if err != nil {
return nil, err
}
out = append(out, newKey)
}
return
}
func (api *API) WalletSignTransaction(tx *SignedTransaction, chainID []byte, pubKeys ...ecc.PublicKey) (out *WalletSignTransactionResp, err error) {
var textKeys []string
for _, key := range pubKeys {
textKeys = append(textKeys, key.String())
}
err = api.call("wallet", "sign_transaction", []interface{}{
tx,
textKeys,
hex.EncodeToString(chainID),
}, &out)
return
}
// SignPushActions will create a transaction, fill it with default
// values, sign it and submit it to the chain. It is the highest
// level function on top of the `/v1/chain/push_transaction` endpoint.
func (api *API) SignPushActions(a ...*Action) (out *PushTransactionFullResp, err error) {
return api.SignPushActionsWithOpts(a, nil)
}
func (api *API) SignPushActionsWithOpts(actions []*Action, opts *TxOptions) (out *PushTransactionFullResp, err error) {
if opts == nil {
opts = &TxOptions{}
}
if err := opts.FillFromChain(api); err != nil {
return nil, err
}
tx := NewTransaction(actions, opts)
return api.SignPushTransaction(tx, opts.ChainID, opts.Compress)
}
// SignPushTransaction will sign a transaction and submit it to the
// chain.
func (api *API) SignPushTransaction(tx *Transaction, chainID SHA256Bytes, compression CompressionType) (out *PushTransactionFullResp, err error) {
_, packed, err := api.SignTransaction(tx, chainID, compression)
if err != nil {
return nil, err
}
return api.PushTransaction(packed)
}
// SignTransaction will sign and pack a transaction, but not submit to
// the chain. It lives on the `api` object because it might query the
// blockchain to learn which keys are required to sign this particular
// transaction.
//
// You can override the way we request keys (which defaults to
// `api.GetRequiredKeys()`) with SetCustomGetRequiredKeys().
//
// To sign a transaction, you need a Signer defined on the `API`
// object. See SetSigner.
func (api *API) SignTransaction(tx *Transaction, chainID SHA256Bytes, compression CompressionType) (*SignedTransaction, *PackedTransaction, error) {
if api.Signer == nil {
return nil, nil, fmt.Errorf("no Signer configured")
}
stx := NewSignedTransaction(tx)
var requiredKeys []ecc.PublicKey
if api.customGetRequiredKeys != nil {
var err error
requiredKeys, err = api.customGetRequiredKeys(tx)
if err != nil {
return nil, nil, fmt.Errorf("custom_get_required_keys: %s", err)
}
} else {
resp, err := api.GetRequiredKeys(tx)
if err != nil {
return nil, nil, fmt.Errorf("get_required_keys: %s", err)
}
requiredKeys = resp.RequiredKeys
}
signedTx, err := api.Signer.Sign(stx, chainID, requiredKeys...)
if err != nil {
return nil, nil, fmt.Errorf("signing through wallet: %s", err)
}
packed, err := signedTx.Pack(compression)
if err != nil {
return nil, nil, err
}
return signedTx, packed, nil
}
// PushTransaction submits a properly filled (tapos), packed and
// signed transaction to the blockchain.
func (api *API) PushTransaction(tx *PackedTransaction) (out *PushTransactionFullResp, err error) {
err = api.call("chain", "push_transaction", tx, &out)
return
}
func (api *API) GetInfo() (out *InfoResp, err error) {
err = api.call("chain", "get_info", nil, &out)
return
}
func (api *API) cachedGetInfo() (*InfoResp, error) {
api.lastGetInfoLock.Lock()
defer api.lastGetInfoLock.Unlock()
var info *InfoResp
var err error
if !api.lastGetInfoStamp.IsZero() && time.Now().Add(-1*time.Second).Before(api.lastGetInfoStamp) {
info = api.lastGetInfo
} else {
info, err = api.GetInfo()
if err != nil {
return nil, err
}
api.lastGetInfoStamp = time.Now()
api.lastGetInfo = info
}
if err != nil {
return nil, err
}
return api.lastGetInfo, nil
}
func (api *API) GetNetConnections() (out []*NetConnectionsResp, err error) {
err = api.call("net", "connections", nil, &out)
return
}
func (api *API) NetConnect(host string) (out NetConnectResp, err error) {
err = api.call("net", "connect", host, &out)
return
}
func (api *API) NetDisconnect(host string) (out NetDisconnectResp, err error) {
err = api.call("net", "disconnect", host, &out)
return
}
func (api *API) GetNetStatus(host string) (out *NetStatusResp, err error) {
err = api.call("net", "status", M{"host": host}, &out)
return
}
func (api *API) GetBlockByID(id string) (out *BlockResp, err error) {
err = api.call("chain", "get_block", M{"block_num_or_id": id}, &out)
return
}
func (api *API) GetProducers() (out *ProducersResp, err error) {
/*
+FC_REFLECT( eosio::chain_apis::read_only::get_producers_params, (json)(lower_bound)(limit) )
+FC_REFLECT( eosio::chain_apis::read_only::get_producers_result, (rows)(total_producer_vote_weight)(more) ); */
err = api.call("chain", "get_producers", nil, &out)
return
}
func (api *API) GetBlockByNum(num uint32) (out *BlockResp, err error) {
err = api.call("chain", "get_block", M{"block_num_or_id": fmt.Sprintf("%d", num)}, &out)
//err = api.call("chain", "get_block", M{"block_num_or_id": num}, &out)
return
}
func (api *API) GetBlockByNumOrID(query string) (out *SignedBlock, err error) {
err = api.call("chain", "get_block", M{"block_num_or_id": query}, &out)
return
}
func (api *API) GetBlockByNumOrIDRaw(query string) (out interface{}, err error) {
err = api.call("chain", "get_block", M{"block_num_or_id": query}, &out)
return
}
func (api *API) GetDBSize() (out *DBSizeResp, err error) {
err = api.call("db_size", "get", nil, &out)
return
}
func (api *API) GetTransaction(id string) (out *TransactionResp, err error) {
err = api.call("history", "get_transaction", M{"id": id}, &out)
return
}
func (api *API) GetTransactionRaw(id string) (out json.RawMessage, err error) {
err = api.call("history", "get_transaction", M{"id": id}, &out)
return
}
func (api *API) GetTransactions(name AccountName) (out *TransactionsResp, err error) {
err = api.call("account_history", "get_transactions", M{"account_name": name}, &out)
return
}
func (api *API) GetTableRows(params GetTableRowsRequest) (out *GetTableRowsResp, err error) {
err = api.call("chain", "get_table_rows", params, &out)
return
}
func (api *API) GetRequiredKeys(tx *Transaction) (out *GetRequiredKeysResp, err error) {
keys, err := api.Signer.AvailableKeys()
if err != nil {
return nil, err
}
err = api.call("chain", "get_required_keys", M{"transaction": tx, "available_keys": keys}, &out)
return
}
func (api *API) GetCurrencyBalance(account AccountName, symbol string, code AccountName) (out []Asset, err error) {
params := M{"account": account, "code": code}
if symbol != "" {
params["symbol"] = symbol
}
err = api.call("chain", "get_currency_balance", params, &out)
return
}
// See more here: libraries/chain/contracts/abi_serializer.cpp:58...
func (api *API) call(baseAPI string, endpoint string, body interface{}, out interface{}) error {
jsonBody, err := enc(body)
if err != nil {
return err
}
var targetURL string
if baseAPI == "wallet" {
if api.WalletURL == "" {
return fmt.Errorf("WalletURL: %s while calling wallet API", ErrNotSet)
}
targetURL = fmt.Sprintf("%s/v1/%s/%s", api.WalletURL, baseAPI, endpoint)
} else {
targetURL = fmt.Sprintf("%s/v1/%s/%s", api.BaseURL, baseAPI, endpoint)
}
req, err := http.NewRequest("POST", targetURL, jsonBody)
if err != nil {
return fmt.Errorf("NewRequest: %s", err)
}
if api.Debug {
// Useful when debugging API calls
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Println(err)
}
fmt.Println("-------------------------------")
fmt.Println(string(requestDump))
fmt.Println("")
}
resp, err := api.HttpClient.Do(req)
if err != nil {
return fmt.Errorf("%s: %s", req.URL.String(), err)
}
defer resp.Body.Close()
var cnt bytes.Buffer
_, err = io.Copy(&cnt, resp.Body)
if err != nil {
return fmt.Errorf("Copy: %s", err)
}
if resp.StatusCode == 404 {
return ErrNotFound
}
if resp.StatusCode > 299 {
return fmt.Errorf("%s: status code=%d, body=%s", req.URL.String(), resp.StatusCode, cnt.String())
}
if api.Debug {
fmt.Println("RESPONSE:")
fmt.Println(cnt.String())
fmt.Println("")
}
if err := json.Unmarshal(cnt.Bytes(), &out); err != nil {
return fmt.Errorf("Unmarshal: %s", err)
}
return nil
}
var ErrNotFound = errors.New("resource not found")
var ErrNotSet = errors.New("config is not set")
type M map[string]interface{}
func enc(v interface{}) (io.Reader, error) {
if v == nil {
return nil, nil
}
cnt, err := json.Marshal(v)
if err != nil {
return nil, err
}
//fmt.Println("BODY", string(cnt))
return bytes.NewReader(cnt), nil
}