forked from eoscanada/eos-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2ptypes.go
588 lines (482 loc) · 15.9 KB
/
p2ptypes.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
package eos
import (
"crypto/sha256"
"errors"
"fmt"
"encoding/binary"
"encoding/hex"
"encoding/json"
"github.com/eoscanada/eos-go/ecc"
"github.com/tidwall/gjson"
)
type P2PMessage interface {
fmt.Stringer
GetType() P2PMessageType
}
type HandshakeMessage struct {
// net_plugin/protocol.hpp handshake_message
NetworkVersion uint16 `json:"network_version"`
ChainID Checksum256 `json:"chain_id"`
NodeID Checksum256 `json:"node_id"` // sha256
Key ecc.PublicKey `json:"key"` // can be empty, producer key, or peer key
Time Tstamp `json:"time"` // time?!
Token Checksum256 `json:"token"` // digest of time to prove we own the private `key`
Signature ecc.Signature `json:"sig"` // can be empty if no key, signature of the digest above
P2PAddress string `json:"p2p_address"`
LastIrreversibleBlockNum uint32 `json:"last_irreversible_block_num"`
LastIrreversibleBlockID Checksum256 `json:"last_irreversible_block_id"`
HeadNum uint32 `json:"head_num"`
HeadID Checksum256 `json:"head_id"`
OS string `json:"os"`
Agent string `json:"agent"`
Generation int16 `json:"generation"`
}
func (m *HandshakeMessage) GetType() P2PMessageType {
return HandshakeMessageType
}
type ChainSizeMessage struct {
LastIrreversibleBlockNum uint32 `json:"last_irreversible_block_num"`
LastIrreversibleBlockID Checksum256 `json:"last_irreversible_block_id"`
HeadNum uint32 `json:"head_num"`
HeadID Checksum256 `json:"head_id"`
}
func (m *ChainSizeMessage) GetType() P2PMessageType {
return ChainSizeType
}
func (m *HandshakeMessage) String() string {
return fmt.Sprintf("handshake: Head [%d] Last Irreversible [%d] Time [%s]", m.HeadNum, m.LastIrreversibleBlockNum, m.Time)
}
type GoAwayReason uint8
// See plugins/net_plugin/include/eosio/net_plugin/protocol.hpp#L39
const (
GoAwayNoReason = GoAwayReason(iota)
GoAwaySelfConnect
GoAwayDuplicate
GoAwayWrongChain
GoAwayWrongVersion
GoAwayForked
GoAwayUnlinkable
GoAwayBadTransaction
GoAwayValidation
GoAwayBenignOther
GoAwayFatalOther
GoAwayAuthentication
)
var goAwayToStringMap = map[GoAwayReason]string{
GoAwayNoReason: "no reason",
GoAwaySelfConnect: "self connect",
GoAwayDuplicate: "duplicate",
GoAwayWrongChain: "wrong chain",
GoAwayWrongVersion: "wrong version",
GoAwayForked: "chain is forked",
GoAwayUnlinkable: "unlinkable block received",
GoAwayBadTransaction: "bad transaction",
GoAwayValidation: "invalid block",
GoAwayAuthentication: "authentication failure",
GoAwayFatalOther: "some other failure",
GoAwayBenignOther: "some other non-fatal condition, possibly unknown block",
}
func (r GoAwayReason) String() string {
if value, exists := goAwayToStringMap[r]; exists {
return value
}
return "some crazy reason"
}
type GoAwayMessage struct {
Reason GoAwayReason `json:"reason"`
NodeID Checksum256 `json:"node_id"`
}
func (m *GoAwayMessage) GetType() P2PMessageType {
return GoAwayMessageType
}
func (m *GoAwayMessage) String() string {
return fmt.Sprintf("go away: reason [%d]", m.Reason)
}
type TimeMessage struct {
Origin Tstamp `json:"org"`
Receive Tstamp `json:"rec"`
Transmit Tstamp `json:"xmt"`
Destination Tstamp `json:"dst"`
}
func (m *TimeMessage) GetType() P2PMessageType {
return TimeMessageType
}
func (t *TimeMessage) String() string {
return fmt.Sprintf("Origin [%s], Receive [%s], Transmit [%s], Destination [%s]", t.Origin, t.Receive, t.Transmit, t.Destination)
}
type TransactionStatus uint8
const (
TransactionStatusExecuted TransactionStatus = iota ///< succeed, no error handler executed
TransactionStatusSoftFail ///< objectively failed (not executed), error handler executed
TransactionStatusHardFail ///< objectively failed and error handler objectively failed thus no state change
TransactionStatusDelayed ///< transaction delayed
TransactionStatusExpired ///< transaction expired
TransactionStatusUnknown = TransactionStatus(255)
)
func (s *TransactionStatus) UnmarshalJSON(data []byte) error {
var decoded string
if err := json.Unmarshal(data, &decoded); err != nil {
return err
}
switch decoded {
case "executed":
*s = TransactionStatusExecuted
case "soft_fail":
*s = TransactionStatusSoftFail
case "hard_fail":
*s = TransactionStatusHardFail
case "delayed":
*s = TransactionStatusDelayed
case "expired":
*s = TransactionStatusExpired
default:
*s = TransactionStatusUnknown
}
return nil
}
func (s TransactionStatus) MarshalJSON() (data []byte, err error) {
out := "unknown"
switch s {
case TransactionStatusExecuted:
out = "executed"
case TransactionStatusSoftFail:
out = "soft_fail"
case TransactionStatusHardFail:
out = "hard_fail"
case TransactionStatusDelayed:
out = "delayed"
case TransactionStatusExpired:
out = "expired"
}
return json.Marshal(out)
}
func (s TransactionStatus) String() string {
switch s {
case TransactionStatusExecuted:
return "executed"
case TransactionStatusSoftFail:
return "soft_fail"
case TransactionStatusHardFail:
return "hard_fail"
case TransactionStatusDelayed:
return "delayed"
case TransactionStatusExpired:
return "expired"
default:
return "unknown"
}
}
//type TransactionID Checksum256
type ProducerKey struct {
AccountName AccountName `json:"producer_name"`
BlockSigningKey ecc.PublicKey `json:"block_signing_key"`
}
type ProducerSchedule struct {
Version uint32 `json:"version"`
Producers []ProducerKey `json:"producers"`
}
type ProducerAuthoritySchedule struct {
Version uint32 `json:"version"`
Producers []*ProducerAuthority `json:"producers"`
}
type ProducerAuthority struct {
AccountName AccountName `json:"producer_name"`
BlockSigningAuthority *BlockSigningAuthority `json:"authority"`
}
type MerkleRoot struct {
ActiveNodes []string `json:"_active_nodes"`
NodeCount uint32 `json:"_node_count"`
}
type EOSNameOrUint32 interface{}
type BlockState struct {
BlockNum uint32 `json:"block_num"`
DPoSProposedIrreversibleBlockNum uint32 `json:"dpos_proposed_irreversible_blocknum"`
DPoSIrreversibleBlockNum uint32 `json:"dpos_irreversible_blocknum"`
// Hybrid (dynamic types)
ActiveSchedule *ProducerScheduleOrAuthoritySchedule `json:"active_schedule"`
BlockrootMerkle *MerkleRoot `json:"blockroot_merkle,omitempty"`
ProducerToLastProduced [][2]EOSNameOrUint32 `json:"producer_to_last_produced,omitempty"`
ProducerToLastImpliedIRB [][2]EOSNameOrUint32 `json:"producer_to_last_implied_irb,omitempty"`
// EOSIO 1.x
BlockSigningKeyV1 *ecc.PublicKey `json:"block_signing_key,omitempty"`
// EOSIO 2.x
ValidBlockSigningAuthorityV2 *BlockSigningAuthority `json:"valid_block_signing_authority,omitempty"`
ConfirmCount []uint32 `json:"confirm_count,omitempty"`
BlockID string `json:"id"`
PendingSchedule *PendingSchedule `json:"pending_schedule"`
ActivatedProtocolFeatures map[string][]HexBytes `json:"activated_protocol_features,omitempty"`
SignedBlock *SignedBlock `json:"block,omitempty"`
Validated bool `json:"validated"`
}
type ProducerScheduleOrAuthoritySchedule struct {
// EOSIO 1.x
V1 *ProducerSchedule
// EOSIO 2.x
V2 *ProducerAuthoritySchedule
}
func (p *ProducerScheduleOrAuthoritySchedule) MarshalJSON() ([]byte, error) {
// In case of ambiguity, which arise only on empty `producers` array, the first one is picked since it does not matter (same JSON output)
if p.V1 != nil {
return json.Marshal(p.V1)
}
if p.V2 != nil {
return json.Marshal(p.V2)
}
return nil, fmt.Errorf("both V1 and V2 were null, this is an error")
}
func (p *ProducerScheduleOrAuthoritySchedule) UnmarshalJSON(data []byte) error {
versionResult := gjson.GetBytes(data, "version")
if !versionResult.Exists() || versionResult.Type != gjson.Number {
return fmt.Errorf("expected 'version' key of type 'number' to exist in %q", string(data))
}
producersResult := gjson.GetBytes(data, "producers")
if !producersResult.Exists() || !producersResult.IsArray() {
return fmt.Errorf("expected 'producers' key of type 'number' to exist in %q", string(data))
}
// We cannot infer anything, what should we do exactly? We could populate the two, but
// what happens on marshal? Both are defined, that's what we choose for now, `eos-go` user
// would then make the choice themselves.
if len(producersResult.Array()) == 0 || producersResult.Get("0.block_signing_key").Exists() {
p.V1 = new(ProducerSchedule)
err := json.Unmarshal(data, p.V1)
if err != nil {
return fmt.Errorf("unable to unmarshal ProducerSchedule type: %s", err)
}
}
if len(producersResult.Array()) == 0 || producersResult.Get("0.authority").Exists() {
p.V2 = new(ProducerAuthoritySchedule)
err := json.Unmarshal(data, p.V2)
if err != nil {
return fmt.Errorf("unable to unmarshal ProducerAuthoritySchedule type: %s", err)
}
}
if p.V1 == nil && p.V2 == nil {
return errors.New("unable to unmarshal producer authority or schedule, no type could be inferred from JSON")
}
return nil
}
const (
BlockSigningAuthorityV0Type = 0
)
// See libraries/chain/include/eosio/chain/producer_schedule.hpp#L161
type BlockSigningAuthority struct {
BaseVariant
}
var blockSigningVariantFactoryImplMap = map[uint32]VariantImplFactory{
BlockSigningAuthorityV0Type: func() interface{} { return new(BlockSigningAuthorityV0) },
}
func (a *BlockSigningAuthority) UnmarshalJSON(data []byte) error {
return a.BaseVariant.UnmarshalJSON(data, blockSigningVariantFactoryImplMap)
}
func (a *BlockSigningAuthority) UnmarshalBinary(decoder *Decoder) error {
return a.BaseVariant.UnmarshalBinaryVariant(decoder, blockSigningVariantFactoryImplMap)
}
// See libraries/chain/include/eosio/chain/producer_schedule.hpp#L100
type BlockSigningAuthorityV0 struct {
Threshold uint32 `json:"threshold"`
Keys []*KeyWeight `json:"keys"`
}
type PendingSchedule struct {
ScheduleLIBNum uint32 `json:"schedule_lib_num"`
ScheduleHash HexBytes `json:"schedule_hash"`
Schedule *ProducerScheduleOrAuthoritySchedule `json:"schedule"`
}
type BlockHeader struct {
Timestamp BlockTimestamp `json:"timestamp"`
Producer AccountName `json:"producer"`
Confirmed uint16 `json:"confirmed"`
Previous Checksum256 `json:"previous"`
TransactionMRoot Checksum256 `json:"transaction_mroot"`
ActionMRoot Checksum256 `json:"action_mroot"`
ScheduleVersion uint32 `json:"schedule_version"`
// EOSIO 1.x
NewProducersV1 *ProducerSchedule `json:"new_producers,omitempty" eos:"optional"`
HeaderExtensions []*Extension `json:"header_extensions"`
}
func (b *BlockHeader) BlockNumber() uint32 {
return binary.BigEndian.Uint32(b.Previous[:4]) + 1
}
func (b *BlockHeader) BlockID() (Checksum256, error) {
cereal, err := MarshalBinary(b)
if err != nil {
return nil, err
}
h := sha256.New()
_, _ = h.Write(cereal)
hashed := h.Sum(nil)
binary.BigEndian.PutUint32(hashed, b.BlockNumber())
return Checksum256(hashed), nil
}
type SignedBlockHeader struct {
BlockHeader
ProducerSignature ecc.Signature `json:"producer_signature"`
}
type SignedBlock struct {
SignedBlockHeader
Transactions []TransactionReceipt `json:"transactions"`
BlockExtensions []*Extension `json:"block_extensions"`
}
func (m *SignedBlock) String() string {
return fmt.Sprintf("SignedBlock [%d] with %d txs", m.BlockNumber(), len(m.Transactions))
}
func (m *SignedBlock) GetType() P2PMessageType {
return SignedBlockType
}
type TransactionReceiptHeader struct {
Status TransactionStatus `json:"status"`
CPUUsageMicroSeconds uint32 `json:"cpu_usage_us"`
NetUsageWords Varuint32 `json:"net_usage_words"`
}
type TransactionReceipt struct {
TransactionReceiptHeader
Transaction TransactionWithID `json:"trx"`
}
type TransactionWithID struct {
ID Checksum256
Packed *PackedTransaction
}
func (t TransactionWithID) MarshalJSON() ([]byte, error) {
return json.Marshal([]interface{}{
t.ID,
t.Packed,
})
}
func (t *TransactionWithID) UnmarshalJSON(data []byte) error {
var packed PackedTransaction
if data[0] == '{' {
if err := json.Unmarshal(data, &packed); err != nil {
return err
}
id, err := packed.ID()
if err != nil {
return fmt.Errorf("get id: %s", err)
}
*t = TransactionWithID{
ID: id,
Packed: &packed,
}
return nil
} else if data[0] == '"' {
var id string
err := json.Unmarshal(data, &id)
if err != nil {
return err
}
shaID, err := hex.DecodeString(id)
if err != nil {
return fmt.Errorf("decoding id in trx: %s", err)
}
*t = TransactionWithID{
ID: Checksum256(shaID),
}
return nil
}
var in []json.RawMessage
err := json.Unmarshal(data, &in)
if err != nil {
return err
}
if len(in) != 2 {
return fmt.Errorf("expected two params for TransactionWithID, got %d", len(in))
}
typ := string(in[0])
switch typ {
case "0":
var s string
if err := json.Unmarshal(in[1], &s); err != nil {
return err
}
*t = TransactionWithID{}
if err := json.Unmarshal(in[1], &t.ID); err != nil {
return err
}
case "1":
// ignore the ID field right now..
err = json.Unmarshal(in[1], &packed)
if err != nil {
return err
}
id, err := packed.ID()
if err != nil {
return fmt.Errorf("get id: %s", err)
}
*t = TransactionWithID{
ID: id,
Packed: &packed,
}
default:
return fmt.Errorf("unsupported multi-variant trx serialization type from C++ code into Go: %q", typ)
}
return nil
}
type IDListMode byte
const (
none IDListMode = iota
catch_up
last_irr_catch_up
normal
)
type OrderedTransactionIDs struct {
Mode [4]byte `json:"mode"`
Pending uint32 `json:"pending"`
IDs []Checksum256 `json:"ids"`
}
type OrderedBlockIDs struct {
Mode [4]byte `json:"mode"`
Pending uint32 `json:"pending"`
IDs []Checksum256 `json:"ids"`
}
func (o *OrderedBlockIDs) String() string {
ids := ""
for _, id := range o.IDs {
ids += fmt.Sprintf("%s,", id)
}
return fmt.Sprintf("Mode %d, Pending %d, ids [%s]", o.Mode, o.Pending, ids)
}
type NoticeMessage struct {
KnownTrx OrderedBlockIDs `json:"known_trx"`
KnownBlocks OrderedBlockIDs `json:"known_blocks"`
}
func (n *NoticeMessage) String() string {
return fmt.Sprintf("KnownTrx %s :: KnownBlocks %s", n.KnownTrx.String(), n.KnownBlocks.String())
}
func (m *NoticeMessage) GetType() P2PMessageType {
return NoticeMessageType
}
type SyncRequestMessage struct {
StartBlock uint32 `json:"start_block"`
EndBlock uint32 `json:"end_block"`
}
func (m *SyncRequestMessage) GetType() P2PMessageType {
return SyncRequestMessageType
}
func (m *SyncRequestMessage) String() string {
return fmt.Sprintf("SyncRequest: Start Block [%d] End Block [%d]", m.StartBlock, m.EndBlock)
}
type RequestMessage struct {
ReqTrx OrderedBlockIDs `json:"req_trx"`
ReqBlocks OrderedBlockIDs `json:"req_blocks"`
}
func (r *RequestMessage) String() string {
return fmt.Sprintf("ReqTrx %s :: ReqBlocks %s", r.ReqTrx.String(), r.ReqBlocks.String())
}
func (m *RequestMessage) GetType() P2PMessageType {
return RequestMessageType
}
type SignedTransactionMessage struct {
Signatures []ecc.Signature `json:"signatures"`
ContextFreeData []byte `json:"context_free_data"`
}
type PackedTransactionMessage struct {
PackedTransaction
}
func (m *PackedTransactionMessage) GetType() P2PMessageType {
return PackedTransactionMessageType
}
func (m PackedTransactionMessage) String() string {
signTrx, err := m.Unpack()
if err != nil {
return fmt.Sprintf("err trx msg unpack by %s", err.Error())
}
return signTrx.String()
}