forked from centrifuge/go-substrate-rpc-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
extrinsic.go
355 lines (300 loc) · 8.26 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
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
// Go Substrate RPC Client (GSRPC) provides APIs and types around Polkadot and any Substrate-based chain RPC calls
//
// Copyright 2019 Centrifuge GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math/big"
"strings"
"github.com/Cerebellum-Network/go-substrate-rpc-client/v8/scale"
"github.com/Cerebellum-Network/go-substrate-rpc-client/v8/signature"
"github.com/Cerebellum-Network/go-substrate-rpc-client/v8/types/codec"
)
const (
ExtrinsicBitSigned = 0x80
ExtrinsicBitUnsigned = 0
ExtrinsicUnmaskVersion = 0x7f
ExtrinsicDefaultVersion = 1
ExtrinsicVersionUnknown = 0 // v0 is unknown
ExtrinsicVersion1 = 1
ExtrinsicVersion2 = 2
ExtrinsicVersion3 = 3
ExtrinsicVersion4 = 4
)
// Extrinsic is a piece of Args bundled into a block that expresses something from the "external" (i.e. off-chain)
// world. There are, broadly speaking, two types of extrinsic: transactions (which tend to be signed) and
// inherents (which don't).
type Extrinsic struct {
// Version is the encoded version flag (which encodes the raw transaction version and signing information in one byte)
Version byte
// Signature is the ExtrinsicSignatureV4, it's presence depends on the Version flag
Signature ExtrinsicSignatureV4
// Method is the call this extrinsic wraps
Method Call
}
// NewExtrinsic creates a new Extrinsic from the provided Call
func NewExtrinsic(c Call) Extrinsic {
return Extrinsic{
Version: ExtrinsicVersion4,
Method: c,
}
}
// UnmarshalJSON fills Extrinsic with the JSON encoded byte array given by bz
func (e *Extrinsic) UnmarshalJSON(bz []byte) error {
var tmp string
if err := json.Unmarshal(bz, &tmp); err != nil {
return err
}
// HACK 11 Jan 2019 - before https://github.com/paritytech/substrate/pull/1388
// extrinsics didn't have the length, cater for both approaches. This is very
// inconsistent with any other `Vec<u8>` implementation
var l UCompact
err := codec.DecodeFromHex(tmp, &l)
if err != nil {
return err
}
prefix, err := codec.EncodeToHex(l)
if err != nil {
return err
}
// determine whether length prefix is there
if strings.HasPrefix(tmp, prefix) {
return codec.DecodeFromHex(tmp, e)
}
// not there, prepend with compact encoded length prefix
dec, err := codec.HexDecodeString(tmp)
if err != nil {
return err
}
length := NewUCompactFromUInt(uint64(len(dec)))
bprefix, err := codec.Encode(length)
if err != nil {
return err
}
bprefix = append(bprefix, dec...)
return codec.Decode(bprefix, e)
}
// MarshalJSON returns a JSON encoded byte array of Extrinsic
func (e Extrinsic) MarshalJSON() ([]byte, error) {
s, err := codec.EncodeToHex(e)
if err != nil {
return nil, err
}
return json.Marshal(s)
}
// IsSigned returns true if the extrinsic is signed
func (e Extrinsic) IsSigned() bool {
return e.Version&ExtrinsicBitSigned == ExtrinsicBitSigned
}
// Type returns the raw transaction version (not flagged with signing information)
func (e Extrinsic) Type() uint8 {
return e.Version & ExtrinsicUnmaskVersion
}
// Sign adds a signature to the extrinsic
func (e *Extrinsic) Sign(signer signature.KeyringPair, o SignatureOptions) error {
if e.Type() != ExtrinsicVersion4 {
return fmt.Errorf("unsupported extrinsic version: %v (isSigned: %v, type: %v)", e.Version, e.IsSigned(), e.Type())
}
mb, err := codec.Encode(e.Method)
if err != nil {
return err
}
era := o.Era
if !o.Era.IsMortalEra {
era = ExtrinsicEra{IsImmortalEra: true}
}
payload := ExtrinsicPayloadV4{
ExtrinsicPayloadV3: ExtrinsicPayloadV3{
Method: mb,
Era: era,
Nonce: o.Nonce,
Tip: o.Tip,
SpecVersion: o.SpecVersion,
GenesisHash: o.GenesisHash,
BlockHash: o.BlockHash,
},
TransactionVersion: o.TransactionVersion,
}
signerPubKey, err := NewMultiAddressFromAccountID(signer.PublicKey)
if err != nil {
return err
}
sig, err := payload.Sign(signer)
if err != nil {
return err
}
extSig := ExtrinsicSignatureV4{
Signer: signerPubKey,
Signature: MultiSignature{IsSr25519: true, AsSr25519: sig},
Era: era,
Nonce: o.Nonce,
Tip: o.Tip,
}
e.Signature = extSig
// mark the extrinsic as signed
e.Version |= ExtrinsicBitSigned
return nil
}
func (e *Extrinsic) Decode(decoder scale.Decoder) error {
// compact length encoding (1, 2, or 4 bytes) (may not be there for Extrinsics older than Jan 11 2019)
_, err := decoder.DecodeUintCompact()
if err != nil {
return err
}
// version, signature bitmask (1 byte)
err = decoder.Decode(&e.Version)
if err != nil {
return err
}
// signature
if e.IsSigned() {
if e.Type() != ExtrinsicVersion4 {
return fmt.Errorf("unsupported extrinsic version: %v (isSigned: %v, type: %v)", e.Version, e.IsSigned(),
e.Type())
}
err = decoder.Decode(&e.Signature)
if err != nil {
return err
}
}
// call
err = decoder.Decode(&e.Method)
if err != nil {
return err
}
return nil
}
func (e Extrinsic) Encode(encoder scale.Encoder) error {
if e.Type() != ExtrinsicVersion4 {
return fmt.Errorf("unsupported extrinsic version: %v (isSigned: %v, type: %v)", e.Version, e.IsSigned(),
e.Type())
}
// create a temporary buffer that will receive the plain encoded transaction (version, signature (optional),
// method/call)
var bb = bytes.Buffer{}
tempEnc := scale.NewEncoder(&bb)
// encode the version of the extrinsic
err := tempEnc.Encode(e.Version)
if err != nil {
return err
}
// encode the signature if signed
if e.IsSigned() {
err = tempEnc.Encode(e.Signature)
if err != nil {
return err
}
}
// encode the method
err = tempEnc.Encode(e.Method)
if err != nil {
return err
}
// take the temporary buffer to determine length, write that as prefix
eb := bb.Bytes()
err = encoder.EncodeUintCompact(*big.NewInt(0).SetUint64(uint64(len(eb))))
if err != nil {
return err
}
// write the actual encoded transaction
err = encoder.Write(eb)
if err != nil {
return err
}
return nil
}
// Call is the extrinsic function descriptor
type Call struct {
CallIndex CallIndex
Args Args
}
func NewCall(m *Metadata, call string, args ...interface{}) (Call, error) {
c, err := m.FindCallIndex(call)
if err != nil {
return Call{}, err
}
var a []byte
for _, arg := range args {
e, err := codec.Encode(arg)
if err != nil {
return Call{}, err
}
a = append(a, e...)
}
return Call{c, a}, nil
}
// Callindex is a 16 bit wrapper around the `[sectionIndex, methodIndex]` value that uniquely identifies a method
type CallIndex struct {
SectionIndex uint8
MethodIndex uint8
}
func (m *CallIndex) Decode(decoder scale.Decoder) error {
err := decoder.Decode(&m.SectionIndex)
if err != nil {
return err
}
err = decoder.Decode(&m.MethodIndex)
if err != nil {
return err
}
return nil
}
func (m CallIndex) Encode(encoder scale.Encoder) error {
err := encoder.Encode(m.SectionIndex)
if err != nil {
return err
}
err = encoder.Encode(m.MethodIndex)
if err != nil {
return err
}
return nil
}
// Args are the encoded arguments for a Call
type Args []byte
// Encode implements encoding for Args, which just unwraps the bytes of Args
func (a Args) Encode(encoder scale.Encoder) error {
return encoder.Write(a)
}
// Decode implements decoding for Args, which just reads all the remaining bytes into Args
func (a *Args) Decode(decoder scale.Decoder) error {
for i := 0; true; i++ {
b, err := decoder.ReadOneByte()
if err == io.EOF {
break
}
if err != nil {
return err
}
*a = append((*a)[:i], b)
}
return nil
}
type Justification Bytes
type SignaturePayload struct {
Address Address
BlockHash Hash
BlockNumber BlockNumber
Era ExtrinsicEra
GenesisHash Hash
Method Call
Nonce UCompact
RuntimeVersion RuntimeVersion
Tip UCompact
Version uint8
}