-
Notifications
You must be signed in to change notification settings - Fork 36
/
extrinsic.go
325 lines (302 loc) · 12.3 KB
/
extrinsic.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
package scalecodec
import (
"encoding/json"
"errors"
"fmt"
scaleType "github.com/itering/scale.go/types"
"github.com/itering/scale.go/types/scaleBytes"
"github.com/itering/scale.go/utiles"
"github.com/shopspring/decimal"
"golang.org/x/crypto/blake2b"
)
type ExtrinsicParam struct {
Name string `json:"name"`
Type string `json:"type"`
TypeName string `json:"type_name"`
Value interface{} `json:"value"`
}
type ExtrinsicDecoder struct {
scaleType.ScaleDecoder
ExtrinsicLength int `json:"extrinsic_length"`
ExtrinsicHash string `json:"extrinsic_hash"`
VersionInfo string `json:"version_info"`
ContainsTransaction bool `json:"contains_transaction"`
Address interface{} `json:"address"`
Signature string `json:"signature"`
Nonce int `json:"nonce"`
Era string `json:"era"`
CallIndex string `json:"call_index"`
Params []ExtrinsicParam `json:"params"`
ParamsRaw string `json:"params_raw"`
Metadata *scaleType.MetadataStruct
SignedExtensions []scaleType.SignedExtension `json:"signed_extensions"`
AdditionalCheck []string
}
// https://github.com/polkadot-js/api/blob/master/packages/types/src/extrinsic/signedExtensions/index.ts#L24
var signedExts = map[string]bool{
"CheckSpecVersion": false,
"CheckTxVersion": false,
"CheckGenesis": false,
"CheckMortality": false,
"CheckNonce": false,
"CheckWeight": false,
"ChargeTransactionPayment": true,
"CheckBlockGasLimit": false,
"ChargeAssetTxPayment": true,
"CheckMetadataHash": true,
}
func (e *ExtrinsicDecoder) Init(data scaleBytes.ScaleBytes, option *scaleType.ScaleDecoderOption) {
if option == nil || option.Metadata == nil {
panic("ExtrinsicDecoder option metadata required")
}
e.Params = []ExtrinsicParam{}
e.Metadata = option.Metadata
e.SignedExtensions = option.SignedExtensions
e.AdditionalCheck = option.AdditionalCheck
e.ScaleDecoder.Init(data, option)
}
func (e *ExtrinsicDecoder) generateHash() string {
if !e.ContainsTransaction {
return ""
}
var extrinsicData []byte
if e.ExtrinsicLength > 0 {
extrinsicData = e.Data.Data
} else {
extrinsicLengthType := scaleType.CompactU32{}
extrinsicLengthType.Encode(len(e.Data.Data))
extrinsicData = append(extrinsicLengthType.Data.Data[:], e.Data.Data[:]...)
}
checksum, _ := blake2b.New(32, []byte{})
_, _ = checksum.Write(extrinsicData)
h := checksum.Sum(nil)
return utiles.BytesToHex(h)
}
type GenericExtrinsic struct {
VersionInfo string `json:"version_info"`
ExtrinsicLength int `json:"extrinsic_length"`
AddressType string `json:"address_type"`
Tip decimal.Decimal `json:"tip"`
SignedExtensions map[string]interface{} `json:"signed_extensions"`
AccountId interface{} `json:"account_id"`
Signer interface{} `json:"signer"` // map[string]interface or string
Signature string `json:"signature"`
SignatureRaw interface{} `json:"signature_raw"` // map[string]interface or string
Nonce int `json:"nonce"`
Era string `json:"era"`
ExtrinsicHash string `json:"extrinsic_hash"`
CallModuleFunction string `json:"call_module_function"`
CallCode string `json:"call_code"`
CallModule string `json:"call_module"`
Params []ExtrinsicParam `json:"params"`
ParamsRaw string `json:"params_raw"`
TransactionExtensionVersion int `json:"transaction_extension_version"`
}
func (e *ExtrinsicDecoder) Process() {
e.ExtrinsicLength = e.ProcessAndUpdateData("Compact<u32>").(int)
if e.ExtrinsicLength != e.Data.GetRemainingLength() {
e.ExtrinsicLength = 0
e.Data.Reset()
}
e.VersionInfo = utiles.BytesToHex(e.NextBytes(1))
e.ContainsTransaction = utiles.U256(e.VersionInfo).Int64() >= 80
result := GenericExtrinsic{
ExtrinsicLength: e.ExtrinsicLength,
VersionInfo: e.VersionInfo,
}
if e.VersionInfo == "04" || e.VersionInfo == "84" {
if e.ContainsTransaction {
// Address
result.Signer = e.ProcessAndUpdateData(utiles.TrueOrElse(e.Metadata.MetadataVersion >= 14 && scaleType.HasReg("ExtrinsicSigner"), "ExtrinsicSigner", "Address"))
switch v := result.Signer.(type) {
case string:
e.Address = v
result.AddressType = "AccountId"
case map[string]interface{}:
for name, value := range v {
result.AddressType = name
e.Address = value
}
}
// ExtrinsicSignature
result.SignatureRaw = e.ProcessAndUpdateData("ExtrinsicSignature")
switch v := result.SignatureRaw.(type) {
case string:
e.Signature = v
case map[string]interface{}:
for _, value := range v {
e.Signature = value.(string)
}
}
e.Era = e.ProcessAndUpdateData("EraExtrinsic").(string)
e.Nonce = int(e.ProcessAndUpdateData("Compact<U64>").(uint64))
if e.Metadata.Extrinsic != nil {
if e.Metadata.MetadataVersion < 14 && utiles.SliceIndex("ChargeTransactionPayment", e.Metadata.Extrinsic.SignedIdentifier) != -1 {
result.Tip = utiles.DecimalFromInterface(e.ProcessAndUpdateData("Compact<Balance>"))
}
} else {
result.Tip = utiles.DecimalFromInterface(e.ProcessAndUpdateData("Compact<Balance>"))
}
// spec SignedExtensions
result.SignedExtensions = make(map[string]interface{})
if len(e.SignedExtensions) > 0 {
for _, extension := range e.SignedExtensions {
if utiles.SliceIndex(extension.Name, e.Metadata.Extrinsic.SignedIdentifier) != -1 {
for _, v := range extension.AdditionalSigned {
result.SignedExtensions[v.Name] = e.ProcessAndUpdateData(v.Type)
}
}
}
} else {
if e.Metadata.MetadataVersion >= 14 {
for _, ext := range e.Metadata.Extrinsic.SignedExtensions {
if enable := signedExts[ext.Identifier]; enable || utiles.SliceIndex(ext.Identifier, e.AdditionalCheck) >= 0 {
if ext.Identifier == "ChargeTransactionPayment" {
result.Tip = utiles.DecimalFromInterface(e.ProcessAndUpdateData("Compact<Balance>"))
} else {
result.SignedExtensions[ext.Identifier] = e.ProcessAndUpdateData(ext.TypeString)
}
}
}
}
}
e.ExtrinsicHash = e.generateHash()
}
e.CallIndex = utiles.BytesToHex(e.NextBytes(2))
} else if e.VersionInfo == "05" || e.VersionInfo == "85" {
if e.ContainsTransaction {
// Address
result.Signer = e.ProcessAndUpdateData(utiles.TrueOrElse(e.Metadata.MetadataVersion >= 14 && scaleType.HasReg("ExtrinsicSigner"), "ExtrinsicSigner", "Address"))
switch v := result.Signer.(type) {
case string:
e.Address = v
result.AddressType = "AccountId"
case map[string]interface{}:
for name, value := range v {
result.AddressType = name
e.Address = value
}
}
// ExtrinsicSignature
result.SignatureRaw = e.ProcessAndUpdateData("ExtrinsicSignature")
result.TransactionExtensionVersion = e.ProcessAndUpdateData("U8").(int)
switch v := result.SignatureRaw.(type) {
case string:
e.Signature = v
case map[string]interface{}:
for _, value := range v {
e.Signature = value.(string)
}
}
e.Era = e.ProcessAndUpdateData("EraExtrinsic").(string)
e.Nonce = int(e.ProcessAndUpdateData("Compact<U64>").(uint64))
// spec SignedExtensions
result.SignedExtensions = make(map[string]interface{})
for _, ext := range e.Metadata.Extrinsic.SignedExtensions {
if enable := signedExts[ext.Identifier]; enable || utiles.SliceIndex(ext.Identifier, e.AdditionalCheck) >= 0 {
if ext.Identifier == "ChargeTransactionPayment" {
result.Tip = utiles.DecimalFromInterface(e.ProcessAndUpdateData("Compact<Balance>"))
} else {
result.SignedExtensions[ext.Identifier] = e.ProcessAndUpdateData(ext.TypeString)
}
}
}
e.ExtrinsicHash = e.generateHash()
}
e.CallIndex = utiles.BytesToHex(e.NextBytes(2))
} else {
panic(fmt.Sprintf("Extrinsics version %s is not support", e.VersionInfo))
}
if e.CallIndex == "" {
panic("Not find Extrinsic Lookup, please check type registry")
}
call, ok := e.Metadata.CallIndex[e.CallIndex]
if !ok {
panic(fmt.Sprintf("Not find Extrinsic Lookup %s, please check metadata info", e.CallIndex))
}
e.Module = call.Module.Name
offset := e.Data.Offset
for _, arg := range call.Call.Args {
e.Params = append(e.Params, ExtrinsicParam{Name: arg.Name, Type: arg.Type, Value: e.ProcessAndUpdateData(arg.Type), TypeName: arg.TypeName})
}
e.ParamsRaw = utiles.BytesToHex(e.Data.Data[offset:e.Data.Offset])
if e.ContainsTransaction {
result.AccountId = e.Address
result.Signature = e.Signature
result.Nonce = e.Nonce
result.Era = e.Era
result.ExtrinsicHash = e.ExtrinsicHash
}
result.CallCode = e.CallIndex
result.CallModuleFunction = call.Call.Name
result.CallModule = call.Module.Name
result.Params = e.Params
result.ParamsRaw = e.ParamsRaw
e.Value = &result
}
/*
Encode extrinsic with option
opt.Metadata is required
return hex string, if error, return empty string
Example:
m := scalecodec.MetadataDecoder{}
m.Init(utiles.HexToBytes(Kusama9370))
_ = m.Process()
option := types.ScaleDecoderOption{Metadata: &m.Metadata}
genericExtrinsic := scalecodec.GenericExtrinsic{
VersionInfo: "84",
CallCode: "0400",
Nonce: 0,
Era: "00",
Signer: map[string]interface{}{"Id": "0xe673cb35ffaaf7ab98c4e9268bfa9b4a74e49d41c8225121c346db7a7dd06d88"},
SignatureRaw: map[string]interface{}{"Ed25519": "0xfce9453b1442bba86c2781e755a29c8a215ccf4b65ce81eeaa5b5a04dcdb79a54525cc86969f910c71c05f84aeab9c205022ecd4aa2abb4a3c3667f09dd16e0b"},
Params: []scalecodec.ExtrinsicParam{
{Value: map[string]interface{}{"Id": "0x0770e0831a275b534f7507c8ebd9f5f982a55053c9dc672da886ef41a6b5c628"}}, {Value: "1094000000000"},
},
}
fmt.Println(genericExtrinsic.Encode(&option))
*/
func (g *GenericExtrinsic) Encode(opt *scaleType.ScaleDecoderOption) (string, error) {
if opt.Metadata == nil {
return "", errors.New("invalid metadata")
}
data := g.VersionInfo
if g.VersionInfo == "84" {
data = data + scaleType.Encode(utiles.TrueOrElse(opt.Metadata.MetadataVersion >= 14 && scaleType.HasReg("ExtrinsicSigner"), "ExtrinsicSigner", "AccountId"), g.Signer) // accountId
data = data + scaleType.Encode("ExtrinsicSignature", g.SignatureRaw) // signature
data = data + scaleType.Encode("EraExtrinsic", g.Era) // era
data = data + scaleType.Encode("Compact<U64>", g.Nonce) // nonce
if len(opt.Metadata.Extrinsic.SignedIdentifier) > 0 && utiles.SliceIndex("ChargeTransactionPayment", opt.Metadata.Extrinsic.SignedIdentifier) > -1 {
data = data + scaleType.Encode("Compact<Balance>", g.Tip) // tip
}
for identifier, extension := range g.SignedExtensions {
for _, ext := range opt.Metadata.Extrinsic.SignedExtensions {
if ext.Identifier == identifier {
data = data + scaleType.Encode(ext.TypeString, extension)
}
}
}
}
data = data + g.CallCode
call, ok := opt.Metadata.CallIndex[g.CallCode]
if !ok {
return "", fmt.Errorf("not find Extrinsic Lookup %s, please check metadata info", g.CallCode)
}
if len(g.Params) != len(call.Call.Args) {
return "", fmt.Errorf("extrinsic params length not match, expect %d, got %d", len(call.Call.Args), len(g.Params))
}
for index, arg := range call.Call.Args {
data = data + utiles.TrimHex(scaleType.EncodeWithOpt(arg.Type, g.Params[index].Value, opt))
}
return scaleType.Encode("Compact<u32>", len(utiles.HexToBytes(data))) + data, nil
}
// ToMap GenericExtrinsic convert to map[string]interface
func (g *GenericExtrinsic) ToMap() map[string]interface{} {
var r map[string]interface{}
b, err := json.Marshal(g)
if err != nil {
return nil
}
_ = json.Unmarshal(b, &r)
return r
}