-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
431 lines (369 loc) · 10.4 KB
/
client.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
package client
import (
"errors"
"fmt"
"hash"
"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/types"
"github.com/centrifuge/go-substrate-rpc-client/v4/types/codec"
"github.com/centrifuge/go-substrate-rpc-client/v4/xxhash"
"golang.org/x/crypto/blake2b"
"github.com/wetee-dao/go-sdk/pallet/system"
gtypes "github.com/wetee-dao/go-sdk/pallet/types"
)
// 区块链链接
// Chain client
type ChainClient struct {
Api *gsrpc.SubstrateAPI
Meta *types.Metadata
Runtime *types.RuntimeVersion
Hash types.Hash
Debug bool
}
// 初始化区块连链接
// Init chain client
func ClientInit(url string, debug bool) (*ChainClient, error) {
if url == "" {
url = config.Default().RPCURL
}
api, err := gsrpc.NewSubstrateAPI(url)
if err != nil {
return nil, err
}
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
}
runtime, err := api.RPC.State.GetRuntimeVersionLatest()
if err != nil {
return nil, err
}
return &ChainClient{api, meta, runtime, genesisHash, debug}, 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
}
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 *Signer) (*types.AccountInfo, error) {
key, err := types.CreateStorageKey(c.Meta, "System", "Account", address.PublicKey)
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 *Signer, runtimeCall gtypes.RuntimeCall, untilFinalized bool) error {
accountInfo, err := c.GetAccount(signer)
if err != nil {
return errors.New("GetAccountInfo error: " + err.Error())
}
call, err := (runtimeCall).AsCall()
if err != nil {
return errors.New("(runtimeCall).AsCall() error: " + err.Error())
}
ext := NewExtrinsic(call)
o := types.SignatureOptions{
BlockHash: c.Hash,
Era: types.ExtrinsicEra{IsMortalEra: false},
GenesisHash: c.Hash,
Nonce: types.NewUCompactFromUInt(uint64(accountInfo.Nonce)),
SpecVersion: c.Runtime.SpecVersion,
Tip: types.NewUCompactFromUInt(0),
TransactionVersion: c.Runtime.TransactionVersion,
}
err = ext.Sign(signer, o)
if err != nil {
return err
}
sub, err := c.Api.RPC.Author.SubmitAndWatchExtrinsic(ext.Extrinsic)
if err != nil {
return errors.New("SubmitAndWatchExtrinsic error: " + err.Error())
}
defer sub.Unsubscribe()
timeout := time.After(30 * time.Second)
for {
select {
case status := <-sub.Chan():
if status.IsInBlock {
extBytes, err := codec.Encode(ext)
if err != nil {
return err
}
// 计算交易的hash
hash := blake2b.Sum256(extBytes)
events, err := c.checkExtrinsic(hash, status.AsInBlock)
if err != nil {
return err
}
// 如果不需要等待交易确认,直接返回
if events != nil && !untilFinalized {
return nil
}
}
if status.IsFinalized {
return nil
}
case err := <-sub.Err():
if c.Debug {
LogWithRed("SubmitAndWatchExtrinsic ERROR", err.Error())
}
return err
case <-timeout:
fmt.Println("Extrinsic: timeout")
return nil
}
}
}
// 检查交易是否成功
// Check whether the transaction is successful
func (c *ChainClient) checkExtrinsic(extHash types.Hash, blockHash types.Hash) ([]gtypes.EventRecord, error) {
block, err := c.Api.RPC.Chain.GetBlock(blockHash)
if err != nil {
return nil, err
}
events, err := system.GetEvents(c.Api.RPC.State, blockHash)
if err != nil {
return nil, err
}
cevents := make([]gtypes.EventRecord, 0, len(events))
for _, e := range events {
extrinsicIndex := e.Phase.AsApplyExtrinsicField0
ext := block.Block.Extrinsics[extrinsicIndex]
extBytes, err := codec.Encode(ext)
if err != nil {
return nil, err
}
// 添加相关的event
if blake2b.Sum256(extBytes) != extHash {
cevents = append(cevents, e)
}
// 判断是否是当前交易的消息
if blake2b.Sum256(extBytes) != extHash || !e.Event.IsSystem {
continue
}
if e.Event.AsSystemField0.IsExtrinsicSuccess {
if c.Debug {
LogWithRed("Extrinsic", "ExtrinsicSuccess")
}
return cevents, nil
}
if e.Event.AsSystemField0.IsExtrinsicFailed {
errData := e.Event.AsSystemField0.AsExtrinsicFailedDispatchError0
if c.Debug {
LogWithRed("Extrinsic", "ExtrinsicFailed")
}
b, err := errData.MarshalJSON()
if err != nil {
fmt.Println(err)
return nil, err
}
return nil, errors.New(string(b))
}
}
return nil, 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 []interface{}) ([]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 interface{}, 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 interface{}) ([]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 interface{}, skeys []interface{}, 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 interface{}, skeys []interface{}) ([]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
}
// 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)...)
}