forked from eoscanada/eos-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2ptypes.go
460 lines (387 loc) · 11.3 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
package eos
import (
"crypto/sha256"
"fmt"
"encoding/binary"
"encoding/hex"
"encoding/json"
"github.com/eoscanada/eos-go/ecc"
)
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
const (
GoAwayNoReason = GoAwayReason(iota)
GoAwaySelfConnect
GoAwayDuplicate
GoAwayWrongChain
GoAwayWrongVersion
GoAwayForked
GoAwayUnlinkable
GoAwayBadTransaction
GoAwayValidation
GoAwayAuthentication
GoAwayFatalOther
GoAwayBenignOther
GoAwayCrazy
)
func (r GoAwayReason) String() string {
switch r {
case GoAwayNoReason:
return "no reason"
case GoAwaySelfConnect:
return "self connect"
case GoAwayDuplicate:
return "duplicate"
case GoAwayWrongChain:
return "wrong chain"
case GoAwayWrongVersion:
return "wrong version"
case GoAwayForked:
return "forked"
case GoAwayUnlinkable:
return "unlinkable"
case GoAwayBadTransaction:
return "bad transaction"
case GoAwayValidation:
return "validation"
case GoAwayAuthentication:
return "authentication"
case GoAwayFatalOther:
return "fatal other"
case GoAwayBenignOther:
return "benign other"
case GoAwayCrazy:
return "crazy"
}
return "invalid go away code"
}
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 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"`
NewProducers *OptionalProducerSchedule `json:"new_producers" 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 OptionalProducerSchedule struct {
ProducerSchedule
}
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()
}