-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_base.go
More file actions
621 lines (530 loc) · 15.3 KB
/
client_base.go
File metadata and controls
621 lines (530 loc) · 15.3 KB
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
619
620
621
package ink
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"hash"
"log"
"math/big"
"sync"
"time"
gsrpc "github.com/centrifuge/go-substrate-rpc-client/v4"
"github.com/centrifuge/go-substrate-rpc-client/v4/config"
"github.com/centrifuge/go-substrate-rpc-client/v4/registry"
"github.com/centrifuge/go-substrate-rpc-client/v4/scale"
"github.com/centrifuge/go-substrate-rpc-client/v4/types"
"github.com/centrifuge/go-substrate-rpc-client/v4/types/codec"
"github.com/centrifuge/go-substrate-rpc-client/v4/types/extrinsic"
"github.com/centrifuge/go-substrate-rpc-client/v4/xxhash"
"golang.org/x/crypto/blake2b"
"github.com/wetee-dao/ink.go/pallet/revive"
"github.com/wetee-dao/ink.go/pallet/system"
gtypes "github.com/wetee-dao/ink.go/pallet/types"
"github.com/wetee-dao/ink.go/util"
)
// 区块链链接
// Chain client
type ChainClient struct {
Meta *types.Metadata
Runtime *types.RuntimeVersion
ErrorMap registry.ErrorRegistry
Hash types.Hash
Debug bool
currIndex int
mu sync.Mutex
conns []*gsrpc.SubstrateAPI
}
// 初始化区块连链接
// Init chain client
func InitClient(urls []string, debug bool) (*ChainClient, error) {
if len(urls) == 0 {
urls = []string{config.Default().RPCURL}
}
var meta *types.Metadata
var runtime *types.RuntimeVersion
var errMap registry.ErrorRegistry
var genesisHash types.Hash
conns := make([]*gsrpc.SubstrateAPI, 0, len(urls))
for _, url := range urls {
api, err := gsrpc.NewSubstrateAPI(url)
if err != nil {
return nil, err
}
if len(conns) > 0 {
hash, err := api.RPC.Chain.GetBlockHash(0)
if err != nil {
return nil, err
}
if hash != genesisHash {
return nil, errors.New("url " + url + " genesis hash is not match")
}
conns = append(conns, api)
continue
}
meta, err = api.RPC.State.GetMetadataLatest()
if err != nil {
return nil, err
}
gtypes.Meta = *meta
genesisHash, err = api.RPC.Chain.GetBlockHash(0)
if err != nil {
return nil, err
}
errMap, err = InitErrors(meta)
if err != nil {
return nil, err
}
runtime, err = api.RPC.State.GetRuntimeVersionLatest()
if err != nil {
return nil, err
}
conns = append(conns, api)
}
return &ChainClient{
Meta: meta,
Runtime: runtime,
ErrorMap: errMap,
Hash: genesisHash,
Debug: debug,
conns: conns,
}, nil
}
// 检查 metadata 是否匹配
// 不匹配就更新
func (c *ChainClient) CheckMetadata() error {
runtime, err := c.Api().RPC.State.GetRuntimeVersionLatest()
if err != nil {
return err
}
if c.Runtime.SpecVersion == runtime.SpecVersion {
return nil
}
meta, err := c.Api().RPC.State.GetMetadataLatest()
if err != nil {
return err
}
errMap, err := InitErrors(meta)
if err != nil {
return err
}
c.ErrorMap = errMap
c.Runtime = runtime
c.Meta = meta
gtypes.Meta = *meta
return nil
}
// 获取区块高度
// Get block number
func (c *ChainClient) GetBlockNumber() (types.BlockNumber, error) {
hash, err := c.Api().RPC.Chain.GetHeaderLatest()
if err != nil {
return 0, err
}
return hash.Number, nil
}
// 获取账户信息
// Get account info
func (c *ChainClient) GetAccount(address SignerType) (*types.AccountInfo, error) {
key, err := types.CreateStorageKey(c.Meta, "System", "Account", address.Public())
if err != nil {
panic(err)
}
var accountInfo types.AccountInfo
_, err = c.Api().RPC.State.GetStorageLatest(key, &accountInfo)
return &accountInfo, err
}
// 签名并提交交易
// Sign and submit transaction
func (c *ChainClient) SignAndSubmit(signer SignerType, call types.Call, untilFinalized bool, nonce uint64) error {
if nonce == 0 {
accountInfo, err := c.GetAccount(signer)
if err != nil {
return errors.New("GetAccountInfo error: " + err.Error())
}
nonce = uint64(accountInfo.Nonce)
}
ext := NewExtrinsic(call)
err := ext.Sign(signer, c.Meta, extrinsic.WithEra(types.ExtrinsicEra{IsImmortalEra: true}, c.Hash),
extrinsic.WithNonce(types.NewUCompactFromUInt(nonce)),
extrinsic.WithTip(types.NewUCompactFromUInt(0)),
extrinsic.WithSpecVersion(c.Runtime.SpecVersion),
extrinsic.WithTransactionVersion(c.Runtime.TransactionVersion),
extrinsic.WithGenesisHash(c.Hash),
)
if err != nil {
return err
}
sub, err := c.Api().RPC.Author.SubmitAndWatchExtrinsic(ext.Extrinsic)
if err != nil {
return errors.New("Author.SubmitAndWatchExtrinsic error: " + err.Error())
}
defer sub.Unsubscribe()
timeout := time.After(30 * time.Second)
extBytes, err := codec.Encode(ext.Extrinsic)
if err != nil {
return errors.New("Codec.Encode error: " + err.Error())
}
hash := blake2b.Sum256(extBytes)
for {
select {
case status := <-sub.Chan():
if status.IsInBlock {
_, success, err := c.checkExtrinsic(hash, status.AsInBlock)
if err != nil {
return err
}
if success && c.Debug {
util.LogWithGreen("[Extrinsic]", "InBlock")
}
if success && !untilFinalized {
return nil
}
} else if status.IsFinalized {
_, success, err := c.checkExtrinsic(hash, status.AsFinalized)
if err != nil {
return err
}
if success {
if c.Debug {
util.LogWithGreen("[Extrinsic]", "Finalized")
fmt.Println()
}
return nil
}
} else if status.IsDropped {
util.LogWithRed("SubmitAndWatchExtrinsic Dropped")
} else if status.IsUsurped {
util.LogWithRed("SubmitAndWatchExtrinsic Usurped")
}
case err := <-sub.Err():
if c.Debug {
util.LogWithRed("SubmitAndWatchExtrinsic ERROR", err.Error())
}
return err
case <-timeout:
util.LogWithRed("SubmitAndWatchExtrinsic ERROR: timeout")
return nil
}
}
}
// 检查交易是否成功
// Check whether the transaction is successful
func (c *ChainClient) checkExtrinsic(extHash types.Hash, blockHash types.Hash) ([]gtypes.EventRecord, bool, error) {
block, err := c.Api().RPC.Chain.GetBlock(blockHash)
if err != nil {
return nil, false, err
}
events, err := system.GetEvents(c.Api().RPC.State, blockHash)
if err != nil {
return nil, false, err
}
cevents := make([]gtypes.EventRecord, 0, len(events))
for _, e := range events {
extrinsicIndex := e.Phase.AsApplyExtrinsicField0
ext := block.Block.Extrinsics[extrinsicIndex]
extBytes, err := hex.DecodeString(ext[2:])
if err != nil {
return nil, false, err
}
eventExtHash := blake2b.Sum256(extBytes)
// 添加相关的event
if eventExtHash != extHash {
cevents = append(cevents, e)
}
// 判断是否是当前交易的消息
if eventExtHash != extHash || !e.Event.IsSystem {
continue
}
// 判断是否是交易成功的消息
if e.Event.AsSystemField0.IsExtrinsicSuccess {
// if c.Debug {
// util.LogWithPurple("Extrinsic", "ExtrinsicSuccess")
// }
return cevents, true, nil
}
// 获取交易失败的消息
if e.Event.AsSystemField0.IsExtrinsicFailed {
errData := e.Event.AsSystemField0.AsExtrinsicFailedDispatchError0
if c.Debug {
util.LogWithPurple("Extrinsic", "ExtrinsicFailed")
}
var errInfo error
// 判断是否是区块链模块错误
if errData.IsModule {
merr := errData.AsModuleField0
info, ierr := c.GetErrorInfo(merr.Index, merr.Error)
if ierr == nil {
errInfo = errors.New("tx: module error " + info.Name)
} else {
errInfo = errors.New("tx: unknown module error ")
}
} else {
b, err := errData.MarshalJSON()
if err != nil {
fmt.Println(err)
return nil, false, err
}
errInfo = errors.New(string(b))
}
return nil, false, errInfo
}
}
return nil, false, nil
}
// 查询 map 所有数据
// query map data list of map
func (c *ChainClient) QueryMapAll(pallet string, method string) ([]types.StorageChangeSet, error) {
key := CreatePrefixedKey(pallet, method)
keys, err := c.Api().RPC.State.GetKeysLatest(key)
if err != nil {
return []types.StorageChangeSet{}, err
}
set, err := c.Api().RPC.State.QueryStorageAtLatest(keys)
if err != nil {
return []types.StorageChangeSet{}, err
}
return set, nil
}
// 查询 map 所有数据
// query map data list of map4
func (c *ChainClient) QueryMapKeys(pallet string, method string, fkeys []any) ([]types.StorageChangeSet, error) {
key := CreatePrefixedKey(pallet, method)
hashers, err := c.GetHashers(pallet, method)
if err != nil {
return nil, err
}
keys := make([]types.StorageKey, 0, len(fkeys))
for i, sk := range fkeys {
arg2, err := codec.Encode(sk)
if err != nil {
return nil, err
}
_, err = hashers[0].Write(arg2)
if err != nil {
return nil, fmt.Errorf("unable to hash args[%d]: %s Error: %v", 1, arg2, err)
}
keys[i] = types.StorageKey(append(key, hashers[1].Sum(nil)...))
}
set, err := c.Api().RPC.State.QueryStorageAtLatest(keys)
if err != nil {
return []types.StorageChangeSet{}, err
}
return set, nil
}
// 查询 double map 第一个 key 的所有数据
// query double map data list of double map
func (c *ChainClient) QueryDoubleMapAll(pallet string, method string, keyarg any, at *types.Hash) ([]types.StorageChangeSet, error) {
key, err := c.GetDoubleMapPrefixKey(pallet, method, keyarg)
if err != nil {
return nil, err
}
// query key
var keys []types.StorageKey
if at == nil {
keys, err = c.Api().RPC.State.GetKeysLatest(key)
} else {
keys, err = c.Api().RPC.State.GetKeys(key, *at)
}
if err != nil {
return nil, err
}
// get all data
var set []types.StorageChangeSet
if at == nil {
set, err = c.Api().RPC.State.QueryStorageAtLatest(keys)
} else {
set, err = c.Api().RPC.State.QueryStorageAt(keys, *at)
}
if err != nil {
return nil, err
}
return set, nil
}
// 查询 double map 第一个 key 前缀
// get double map prefix key of double map {{pallet}}.{{method}}.{{frist key}}
func (c *ChainClient) GetDoubleMapPrefixKey(pallet string, method string, keyarg any) ([]byte, error) {
arg, err := codec.Encode(keyarg)
if err != nil {
return nil, err
}
// create key prefix
key := CreatePrefixedKey(pallet, method)
hashers, err := c.GetHashers(pallet, method)
if err != nil {
return nil, err
}
// write key
_, err = hashers[0].Write(arg)
if err != nil {
return nil, fmt.Errorf("unable to hash args[%d]: %s Error: %v", 0, arg, err)
}
// append hash to key
key = append(key, hashers[0].Sum(nil)...)
return key, nil
}
// 查询 double map 第一个 key 的所有数据
// query double map data list of double map
func (c *ChainClient) QueryDoubleMapKeys(pallet string, method string, keyarg any, skeys []any, at *types.Hash) ([]types.StorageChangeSet, error) {
keys, err := c.GetDoubleMapPrefixKeys(pallet, method, keyarg, skeys)
if err != nil {
return nil, err
}
// get all data
var set []types.StorageChangeSet
if at == nil {
set, err = c.Api().RPC.State.QueryStorageAtLatest(keys)
} else {
set, err = c.Api().RPC.State.QueryStorageAt(keys, *at)
}
if err != nil {
return nil, err
}
return set, nil
}
// 查询 double map 第一个 key 前缀 和 多个 第二个 key
// get double map prefix key of double map {{pallet}}.{{method}}.{{frist key}}
func (c *ChainClient) GetDoubleMapPrefixKeys(pallet string, method string, keyarg any, skeys []any) ([]types.StorageKey, error) {
arg, err := codec.Encode(keyarg)
if err != nil {
return nil, err
}
// create key prefix
key := CreatePrefixedKey(pallet, method)
hashers, err := c.GetHashers(pallet, method)
if err != nil {
return nil, err
}
// write key
_, err = hashers[0].Write(arg)
if err != nil {
return nil, fmt.Errorf("unable to hash args[%d]: %s Error: %v", 0, arg, err)
}
// append hash to key
key = append(key, hashers[0].Sum(nil)...)
keys := make([]types.StorageKey, 0, len(skeys))
for _, sk := range skeys {
arg2, err := codec.Encode(sk)
if err != nil {
return nil, err
}
_, err = hashers[1].Write(arg2)
if err != nil {
return nil, fmt.Errorf("unable to hash args[%d]: %s Error: %v", 1, arg2, err)
}
keys = append(keys, types.StorageKey(append(key, hashers[1].Sum(nil)...)))
}
return keys, nil
}
// Get hashers of map {{pallet}}.{{method}}
func (c *ChainClient) GetHashers(pallet, method string) ([]hash.Hash, error) {
// get entry metadata
// 获取储存元数据
entryMeta, err := c.Meta.FindStorageEntryMetadata(pallet, method)
if err != nil {
return nil, err
}
// check if it's a map
// 判断是否为map
if !entryMeta.IsMap() {
return nil, errors.New(pallet + "." + method + "is not map")
}
// get map hashers
// 获取储存的 hasher 函数
hashers, err := entryMeta.Hashers()
if err != nil {
return nil, err
}
return hashers, nil
}
// Call runtime api
func (c *ChainClient) CallRuntimeApi(pallet, method string, args []any, result any) error {
var buffer bytes.Buffer
var err error
encoder := scale.NewEncoder(&buffer)
// Encode the arguments
for _, arg := range args {
err = encoder.Encode(arg)
if err != nil {
log.Fatal(err)
return err
}
}
// Call runtime api
var rawResult string
err = c.Api().Client.Call(&rawResult, "state_call", pallet+"_"+method, "0x"+hex.EncodeToString(buffer.Bytes()))
if err != nil {
return err
}
if c.Debug {
util.LogWithPurple("[RuntimeApi]", pallet+"_"+method)
util.LogWithPurple("[RawResult]", rawResult)
}
// Decode the raw result from hex to bytes
rawResult = rawResult[2:]
resultBytes, err := hex.DecodeString(rawResult)
if err != nil {
log.Fatalf("CallRuntimeApi Failed to decode result: %v", err)
}
// Decode the result using scale.Decoder
return scale.NewDecoder(bytes.NewReader(resultBytes)).Decode(result)
}
// Get balance of h160
func (c *ChainClient) BalanceOfH160(address string) (types.U128, error) {
balance := types.NewU128(*big.NewInt(0))
bt, err := util.HexToH160(address)
if err != nil {
return types.U128{}, err
}
err = c.CallRuntimeApi("ReviveApi", "balance", []any{bt}, &balance)
if err != nil {
return types.U128{}, err
}
return balance, nil
}
func (c *ChainClient) MapReviveAccount(signer SignerType) error {
runtimeCall := revive.MakeMapAccountCall()
call, err := (runtimeCall).AsCall()
if err != nil {
return errors.New("(runtimeCall).AsCall() error: " + err.Error())
}
return c.SignAndSubmit(signer, call, true, 0)
}
// Get block gas limit
func (c *ChainClient) InkBlockGasLimit(address [32]byte) error {
balance := types.NewU128(*big.NewInt(0))
err := c.CallRuntimeApi("ReviveApi", "block_gas_limit", []any{}, &balance)
return err
}
// Close chain client
func (c *ChainClient) Close() {
c.Api().Client.Close()
}
// Utility.batch 如果批量中的某个调用失败(返回错误),整个批量调用立即停止,后续调用永远不会执行
// Utility.batch_all 无论中间某个调用是否失败,都会继续执行整个批量中的所有调用(不中断)
// Utility.force_batch 强制执行,忽略调用失败
var batchMethods = []string{"batch", "batch_all", "force_batch"}
// get batch call
func (c *ChainClient) BatchCall(
callMethod string, // Utility.batch_all or Utility.batch or Utility.force_batch
calls []types.Call,
) (*types.Call, error) {
isIn := false
for _, m := range batchMethods {
if m == callMethod {
isIn = true
}
}
if !isIn {
return nil, fmt.Errorf("callMethod %s is not in batchMethods %v", callMethod, batchMethods)
}
batchCall, err := types.NewCall(c.Meta, "Utility."+callMethod, calls)
if err != nil {
return nil, fmt.Errorf("new BatchCall error: %w", err)
}
return &batchCall, nil
}
// Create prefixed key of {{pallet}}.{{method}}
func CreatePrefixedKey(pallet, method string) []byte {
return append(xxhash.New128([]byte(pallet)).Sum(nil), xxhash.New128([]byte(method)).Sum(nil)...)
}