-
Notifications
You must be signed in to change notification settings - Fork 27
/
address.go
435 lines (365 loc) · 9.93 KB
/
address.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
432
433
434
435
package address
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"strconv"
cbor "github.com/ipfs/go-ipld-cbor"
"github.com/minio/blake2b-simd"
"github.com/multiformats/go-varint"
"github.com/polydawn/refmt/obj/atlas"
"golang.org/x/xerrors"
cbg "github.com/whyrusleeping/cbor-gen"
)
func init() {
cbor.RegisterCborType(addressAtlasEntry)
}
var addressAtlasEntry = atlas.BuildEntry(Address{}).Transform().
TransformMarshal(atlas.MakeMarshalTransformFunc(
func(a Address) (string, error) {
return string(a.Bytes()), nil
})).
TransformUnmarshal(atlas.MakeUnmarshalTransformFunc(
func(x string) (Address, error) {
return NewFromBytes([]byte(x))
})).
Complete()
// CurrentNetwork specifies which network the address belongs to
var CurrentNetwork = Testnet
// Address is the go type that represents an address in the filecoin network.
type Address struct{ str string }
// Undef is the type that represents an undefined address.
var Undef = Address{}
// Network represents which network an address belongs to.
type Network = byte
const (
// Mainnet is the main network.
Mainnet Network = iota
// Testnet is the test network.
Testnet
)
// MainnetPrefix is the main network prefix.
const MainnetPrefix = "f"
// TestnetPrefix is the test network prefix.
const TestnetPrefix = "t"
// Protocol represents which protocol an address uses.
type Protocol = byte
const (
// ID represents the address ID protocol.
ID Protocol = iota
// SECP256K1 represents the address SECP256K1 protocol.
SECP256K1
// Actor represents the address Actor protocol.
Actor
// BLS represents the address BLS protocol.
BLS
Unknown = Protocol(255)
)
// Protocol returns the protocol used by the address.
func (a Address) Protocol() Protocol {
if len(a.str) == 0 {
return Unknown
}
return a.str[0]
}
// Payload returns the payload of the address.
func (a Address) Payload() []byte {
if len(a.str) == 0 {
return nil
}
return []byte(a.str[1:])
}
// Bytes returns the address as bytes.
func (a Address) Bytes() []byte {
return []byte(a.str)
}
// String returns an address encoded as a string.
func (a Address) String() string {
str, err := encode(CurrentNetwork, a)
if err != nil {
panic(err) // I don't know if this one is okay
}
return str
}
// Empty returns true if the address is empty, false otherwise.
func (a Address) Empty() bool {
return a == Undef
}
// Unmarshal unmarshals the cbor bytes into the address.
func (a Address) Unmarshal(b []byte) error {
return cbor.DecodeInto(b, &a)
}
// Marshal marshals the address to cbor.
func (a Address) Marshal() ([]byte, error) {
return cbor.DumpObject(a)
}
// UnmarshalJSON implements the json unmarshal interface.
func (a *Address) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
addr, err := decode(s)
if err != nil {
return err
}
*a = addr
return nil
}
// MarshalJSON implements the json marshal interface.
func (a Address) MarshalJSON() ([]byte, error) {
return []byte(`"` + a.String() + `"`), nil
}
func (a *Address) Scan(value interface{}) error {
switch value := value.(type) {
case string:
a1, err := decode(value)
if err != nil {
return err
}
*a = a1
return nil
default:
return xerrors.New("non-string types unsupported")
}
}
// NewIDAddress returns an address using the ID protocol.
func NewIDAddress(id uint64) (Address, error) {
if id > math.MaxInt64 {
return Undef, xerrors.New("IDs must be less than 2^63")
}
return newAddress(ID, varint.ToUvarint(id))
}
// NewSecp256k1Address returns an address using the SECP256K1 protocol.
func NewSecp256k1Address(pubkey []byte) (Address, error) {
return newAddress(SECP256K1, addressHash(pubkey))
}
// NewActorAddress returns an address using the Actor protocol.
func NewActorAddress(data []byte) (Address, error) {
return newAddress(Actor, addressHash(data))
}
// NewBLSAddress returns an address using the BLS protocol.
func NewBLSAddress(pubkey []byte) (Address, error) {
return newAddress(BLS, pubkey)
}
// NewFromString returns the address represented by the string `addr`.
func NewFromString(addr string) (Address, error) {
return decode(addr)
}
// NewFromBytes return the address represented by the bytes `addr`.
func NewFromBytes(addr []byte) (Address, error) {
if len(addr) == 0 {
return Undef, nil
}
if len(addr) == 1 {
return Undef, ErrInvalidLength
}
return newAddress(addr[0], addr[1:])
}
// Checksum returns the checksum of `ingest`.
func Checksum(ingest []byte) []byte {
return hash(ingest, checksumHashConfig)
}
// ValidateChecksum returns true if the checksum of `ingest` is equal to `expected`>
func ValidateChecksum(ingest, expect []byte) bool {
digest := Checksum(ingest)
return bytes.Equal(digest, expect)
}
func addressHash(ingest []byte) []byte {
return hash(ingest, payloadHashConfig)
}
func newAddress(protocol Protocol, payload []byte) (Address, error) {
switch protocol {
case ID:
v, n, err := varint.FromUvarint(payload)
if err != nil {
return Undef, xerrors.Errorf("could not decode: %v: %w", err, ErrInvalidPayload)
}
if n != len(payload) {
return Undef, xerrors.Errorf("different varint length (v:%d != p:%d): %w",
n, len(payload), ErrInvalidPayload)
}
if v > math.MaxInt64 {
return Undef, xerrors.Errorf("id addresses must be less than 2^63: %w", ErrInvalidPayload)
}
case SECP256K1, Actor:
if len(payload) != PayloadHashLength {
return Undef, ErrInvalidPayload
}
case BLS:
if len(payload) != BlsPublicKeyBytes {
return Undef, ErrInvalidPayload
}
default:
return Undef, ErrUnknownProtocol
}
explen := 1 + len(payload)
buf := make([]byte, explen)
buf[0] = protocol
copy(buf[1:], payload)
return Address{string(buf)}, nil
}
func encode(network Network, addr Address) (string, error) {
if addr == Undef {
return UndefAddressString, nil
}
var ntwk string
switch network {
case Mainnet:
ntwk = MainnetPrefix
case Testnet:
ntwk = TestnetPrefix
default:
return UndefAddressString, ErrUnknownNetwork
}
var strAddr string
switch addr.Protocol() {
case SECP256K1, Actor, BLS:
cksm := Checksum(append([]byte{addr.Protocol()}, addr.Payload()...))
strAddr = ntwk + fmt.Sprintf("%d", addr.Protocol()) + AddressEncoding.WithPadding(-1).EncodeToString(append(addr.Payload(), cksm[:]...))
case ID:
i, n, err := varint.FromUvarint(addr.Payload())
if err != nil {
return UndefAddressString, xerrors.Errorf("could not decode varint: %w", err)
}
if n != len(addr.Payload()) {
return UndefAddressString, xerrors.Errorf("payload contains additional bytes")
}
strAddr = fmt.Sprintf("%s%d%d", ntwk, addr.Protocol(), i)
default:
return UndefAddressString, ErrUnknownProtocol
}
return strAddr, nil
}
func decode(a string) (Address, error) {
if len(a) == 0 {
return Undef, nil
}
if a == UndefAddressString {
return Undef, nil
}
if len(a) > MaxAddressStringLength || len(a) < 3 {
return Undef, ErrInvalidLength
}
if string(a[0]) != MainnetPrefix && string(a[0]) != TestnetPrefix {
return Undef, ErrUnknownNetwork
}
var protocol Protocol
switch a[1] {
case '0':
protocol = ID
case '1':
protocol = SECP256K1
case '2':
protocol = Actor
case '3':
protocol = BLS
default:
return Undef, ErrUnknownProtocol
}
raw := a[2:]
if protocol == ID {
// 19 is length of math.MaxInt64 as a string
if len(raw) > 19 {
return Undef, ErrInvalidLength
}
id, err := strconv.ParseUint(raw, 10, 63)
if err != nil {
return Undef, ErrInvalidPayload
}
return newAddress(protocol, varint.ToUvarint(id))
}
payloadcksm, err := AddressEncoding.WithPadding(-1).DecodeString(raw)
if err != nil {
return Undef, err
}
if len(payloadcksm)-ChecksumHashLength < 0 {
return Undef, ErrInvalidChecksum
}
payload := payloadcksm[:len(payloadcksm)-ChecksumHashLength]
cksm := payloadcksm[len(payloadcksm)-ChecksumHashLength:]
if protocol == SECP256K1 || protocol == Actor {
if len(payload) != 20 {
return Undef, ErrInvalidPayload
}
}
if !ValidateChecksum(append([]byte{protocol}, payload...), cksm) {
return Undef, ErrInvalidChecksum
}
return newAddress(protocol, payload)
}
func hash(ingest []byte, cfg *blake2b.Config) []byte {
hasher, err := blake2b.New(cfg)
if err != nil {
// If this happens sth is very wrong.
panic(fmt.Sprintf("invalid address hash configuration: %v", err)) // ok
}
if _, err := hasher.Write(ingest); err != nil {
// blake2bs Write implementation never returns an error in its current
// setup. So if this happens sth went very wrong.
panic(fmt.Sprintf("blake2b is unable to process hashes: %v", err)) // ok
}
return hasher.Sum(nil)
}
func (a Address) MarshalBinary() ([]byte, error) {
return a.Bytes(), nil
}
func (a *Address) UnmarshalBinary(b []byte) error {
newAddr, err := NewFromBytes(b)
if err != nil {
return err
}
*a = newAddr
return nil
}
func (a *Address) MarshalCBOR(w io.Writer) error {
if a == nil {
_, err := w.Write(cbg.CborNull)
return err
}
if *a == Undef {
return fmt.Errorf("cannot marshal undefined address")
}
if err := cbg.WriteMajorTypeHeader(w, cbg.MajByteString, uint64(len(a.str))); err != nil {
return err
}
if _, err := io.WriteString(w, a.str); err != nil {
return err
}
return nil
}
func (a *Address) UnmarshalCBOR(r io.Reader) error {
br := cbg.GetPeeker(r)
maj, extra, err := cbg.CborReadHeader(br)
if err != nil {
return err
}
if maj != cbg.MajByteString {
return fmt.Errorf("cbor type for address unmarshal was not byte string")
}
if extra > 64 {
return fmt.Errorf("too many bytes to unmarshal for an address")
}
buf := make([]byte, int(extra))
if _, err := io.ReadFull(br, buf); err != nil {
return err
}
addr, err := NewFromBytes(buf)
if err != nil {
return err
}
if addr == Undef {
return fmt.Errorf("cbor input should not contain empty addresses")
}
*a = addr
return nil
}
func IDFromAddress(addr Address) (uint64, error) {
if addr.Protocol() != ID {
return 0, xerrors.Errorf("cannot get id from non id address")
}
i, _, err := varint.FromUvarint(addr.Payload())
return i, err
}