forked from gagliardetto/solana-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nativetypes.go
407 lines (340 loc) · 8.85 KB
/
nativetypes.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
// Copyright 2021 github.com/gagliardetto
// This file has been modified by github.com/gagliardetto
//
// Copyright 2020 dfuse Platform Inc.
//
// 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 solana
import (
"crypto/ed25519"
"encoding/base64"
"fmt"
"io"
bin "github.com/gagliardetto/binary"
"github.com/mostynb/zstdpool-freelist"
"github.com/mr-tron/base58"
)
type Padding []byte
type Hash PublicKey
// MustHashFromBase58 decodes a base58 string into a Hash.
// Panics on error.
func MustHashFromBase58(in string) Hash {
return Hash(MustPublicKeyFromBase58(in))
}
// HashFromBase58 decodes a base58 string into a Hash.
func HashFromBase58(in string) (Hash, error) {
tmp, err := PublicKeyFromBase58(in)
if err != nil {
return Hash{}, err
}
return Hash(tmp), nil
}
// HashFromBytes decodes a byte slice into a Hash.
func HashFromBytes(in []byte) Hash {
return Hash(PublicKeyFromBytes(in))
}
// MarshalText implements encoding.TextMarshaler.
func (ha Hash) MarshalText() ([]byte, error) {
s := base58.Encode(ha[:])
return []byte(s), nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (ha *Hash) UnmarshalText(data []byte) (err error) {
tmp, err := HashFromBase58(string(data))
if err != nil {
return fmt.Errorf("invalid hash %q: %w", string(data), err)
}
*ha = tmp
return
}
func (ha Hash) MarshalJSON() ([]byte, error) {
return json.Marshal(base58.Encode(ha[:]))
}
func (ha *Hash) UnmarshalJSON(data []byte) (err error) {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
tmp, err := HashFromBase58(s)
if err != nil {
return fmt.Errorf("invalid hash %q: %w", s, err)
}
*ha = tmp
return
}
func (ha Hash) Equals(pb Hash) bool {
return ha == pb
}
var zeroHash = Hash{}
func (ha Hash) IsZero() bool {
return ha == zeroHash
}
func (ha Hash) String() string {
return base58.Encode(ha[:])
}
type Signature [64]byte
var zeroSignature = Signature{}
func (sig Signature) IsZero() bool {
return sig == zeroSignature
}
func (sig Signature) Equals(pb Signature) bool {
return sig == pb
}
// SignatureFromBase58 decodes a base58 string into a Signature.
func SignatureFromBase58(in string) (out Signature, err error) {
val, err := base58.Decode(in)
if err != nil {
return
}
if len(val) != SignatureLength {
err = fmt.Errorf("invalid length, expected 64, got %d", len(val))
return
}
copy(out[:], val)
return
}
// MustSignatureFromBase58 decodes a base58 string into a Signature.
// Panics on error.
func MustSignatureFromBase58(in string) Signature {
out, err := SignatureFromBase58(in)
if err != nil {
panic(err)
}
return out
}
// SignatureFromBytes decodes a byte slice into a Signature.
func SignatureFromBytes(in []byte) (out Signature) {
byteCount := len(in)
if byteCount == 0 {
return
}
max := SignatureLength
if byteCount < max {
max = byteCount
}
copy(out[:], in[0:max])
return
}
func (p Signature) MarshalText() ([]byte, error) {
s := base58.Encode(p[:])
return []byte(s), nil
}
func (p *Signature) UnmarshalText(data []byte) (err error) {
tmp, err := SignatureFromBase58(string(data))
if err != nil {
return fmt.Errorf("invalid signature %q: %w", string(data), err)
}
*p = tmp
return
}
func (p Signature) MarshalJSON() ([]byte, error) {
return json.Marshal(base58.Encode(p[:]))
}
func (p *Signature) UnmarshalJSON(data []byte) (err error) {
var s string
err = json.Unmarshal(data, &s)
if err != nil {
return
}
dat, err := base58.Decode(s)
if err != nil {
return err
}
if len(dat) != SignatureLength {
return fmt.Errorf("invalid length for Signature, expected 64, got %d", len(dat))
}
target := Signature{}
copy(target[:], dat)
*p = target
return
}
// Verify checks that the signature is valid for the given public key and message.
func (s Signature) Verify(pubkey PublicKey, msg []byte) bool {
return ed25519.Verify(pubkey[:], msg, s[:])
}
func (p Signature) String() string {
return base58.Encode(p[:])
}
type Base64 []byte
func (t Base64) MarshalJSON() ([]byte, error) {
return json.Marshal(base64.StdEncoding.EncodeToString(t))
}
func (t *Base64) UnmarshalJSON(data []byte) (err error) {
var s string
err = json.Unmarshal(data, &s)
if err != nil {
return
}
if s == "" {
*t = []byte{}
return nil
}
*t, err = base64.StdEncoding.DecodeString(s)
return
}
type Base58 []byte
func (t Base58) MarshalJSON() ([]byte, error) {
return json.Marshal(base58.Encode(t))
}
func (t *Base58) UnmarshalJSON(data []byte) (err error) {
var s string
err = json.Unmarshal(data, &s)
if err != nil {
return
}
if s == "" {
*t = []byte{}
return nil
}
*t, err = base58.Decode(s)
return
}
func (t Base58) String() string {
return base58.Encode(t)
}
type Data struct {
Content []byte
Encoding EncodingType
}
func (t Data) MarshalJSON() ([]byte, error) {
return json.Marshal(
[]interface{}{
t.String(),
t.Encoding,
})
}
var zstdDecoderPool = zstdpool.NewDecoderPool()
func (t *Data) UnmarshalJSON(data []byte) (err error) {
var in []string
if err := json.Unmarshal(data, &in); err != nil {
return err
}
if len(in) != 2 {
return fmt.Errorf("invalid length for solana.Data, expected 2, found %d", len(in))
}
contentString := in[0]
encodingString := in[1]
t.Encoding = EncodingType(encodingString)
if contentString == "" {
t.Content = []byte{}
return nil
}
switch t.Encoding {
case EncodingBase58:
var err error
t.Content, err = base58.Decode(contentString)
if err != nil {
return err
}
case EncodingBase64:
var err error
t.Content, err = base64.StdEncoding.DecodeString(contentString)
if err != nil {
return err
}
case EncodingBase64Zstd:
rawBytes, err := base64.StdEncoding.DecodeString(contentString)
if err != nil {
return err
}
dec, err := zstdDecoderPool.Get(nil)
if err != nil {
return err
}
defer zstdDecoderPool.Put(dec)
t.Content, err = dec.DecodeAll(rawBytes, nil)
if err != nil {
return err
}
default:
return fmt.Errorf("unsupported encoding %s", encodingString)
}
return
}
var zstdEncoderPool = zstdpool.NewEncoderPool()
func (t Data) String() string {
switch EncodingType(t.Encoding) {
case EncodingBase58:
return base58.Encode(t.Content)
case EncodingBase64:
return base64.StdEncoding.EncodeToString(t.Content)
case EncodingBase64Zstd:
enc, err := zstdEncoderPool.Get(nil)
if err != nil {
// TODO: remove panic?
panic(err)
}
defer zstdEncoderPool.Put(enc)
return base64.StdEncoding.EncodeToString(enc.EncodeAll(t.Content, nil))
default:
// TODO
return ""
}
}
func (obj Data) MarshalWithEncoder(encoder *bin.Encoder) (err error) {
err = encoder.WriteBytes(obj.Content, true)
if err != nil {
return err
}
err = encoder.WriteString(string(obj.Encoding))
if err != nil {
return err
}
return nil
}
func (obj *Data) UnmarshalWithDecoder(decoder *bin.Decoder) (err error) {
obj.Content, err = decoder.ReadByteSlice()
if err != nil {
return err
}
{
enc, err := decoder.ReadString()
if err != nil {
return err
}
obj.Encoding = EncodingType(enc)
}
return nil
}
type ByteWrapper struct {
io.Reader
}
func (w *ByteWrapper) ReadByte() (byte, error) {
var b [1]byte
// NOTE: w.Read() gives no guaranties about the number of bytes actually read.
// Using io.ReadFull reads exactly len(buf) bytes from r into buf.
_, err := io.ReadFull(w, b[:])
return b[0], err
}
type EncodingType string
const (
EncodingBase58 EncodingType = "base58" // limited to Account data of less than 129 bytes
EncodingBase64 EncodingType = "base64" // will return base64 encoded data for Account data of any size
EncodingBase64Zstd EncodingType = "base64+zstd" // compresses the Account data using Zstandard and base64-encodes the result
// attempts to use program-specific state parsers to
// return more human-readable and explicit account state data.
// If "jsonParsed" is requested but a parser cannot be found,
// the field falls back to "base64" encoding, detectable when the data field is type <string>.
// Cannot be used if specifying dataSlice parameters (offset, length).
EncodingJSONParsed EncodingType = "jsonParsed"
EncodingJSON EncodingType = "json" // NOTE: you're probably looking for EncodingJSONParsed
)
// IsAnyOfEncodingType checks whether the provided `candidate` is any of the `allowed`.
func IsAnyOfEncodingType(candidate EncodingType, allowed ...EncodingType) bool {
for _, v := range allowed {
if candidate == v {
return true
}
}
return false
}