-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbstate.go
813 lines (685 loc) · 22.5 KB
/
dbstate.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
// Copyright 2017 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package messages
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"os"
"reflect"
"github.com/DCNT-Hammer/dcnt/common/adminBlock"
"github.com/DCNT-Hammer/dcnt/common/constants"
"github.com/DCNT-Hammer/dcnt/common/directoryBlock"
"github.com/DCNT-Hammer/dcnt/common/entryBlock"
"github.com/DCNT-Hammer/dcnt/common/entryCreditBlock"
"github.com/DCNT-Hammer/dcnt/common/factoid"
"github.com/DCNT-Hammer/dcnt/common/interfaces"
"github.com/DCNT-Hammer/dcnt/common/primitives"
"github.com/DCNT-Hammer/dcnt/common/messages/msgbase"
log "github.com/sirupsen/logrus"
)
// Communicate a Directory Block State
type DBStateMsg struct {
msgbase.MessageBase
Timestamp interfaces.Timestamp
//TODO: handle malformed DBStates!
DirectoryBlock interfaces.IDirectoryBlock
AdminBlock interfaces.IAdminBlock
FactoidBlock interfaces.IFBlock
EntryCreditBlock interfaces.IEntryCreditBlock
EBlocks []interfaces.IEntryBlock
Entries []interfaces.IEBEntry
SignatureList SigList
//Not marshalled
IgnoreSigs bool
Sent interfaces.Timestamp
IsInDB bool
IsLast bool // Flag from state.LoadDatabase() that this is the last saved block loaded at boot.
}
var _ interfaces.IMsg = (*DBStateMsg)(nil)
func (a *DBStateMsg) IsSameAs(b *DBStateMsg) bool {
defer func() {
if r := recover(); r != nil {
return
}
}()
if b == nil {
return false
}
if a.Timestamp.GetTimeMilli() != b.Timestamp.GetTimeMilli() {
return false
}
ok, err := primitives.AreBinaryMarshallablesEqual(a.DirectoryBlock, b.DirectoryBlock)
if err != nil || ok == false {
return false
}
ok, err = primitives.AreBinaryMarshallablesEqual(a.AdminBlock, b.AdminBlock)
if err != nil || ok == false {
return false
}
ok, err = primitives.AreBinaryMarshallablesEqual(a.FactoidBlock, b.FactoidBlock)
if err != nil || ok == false {
return false
}
ok, err = primitives.AreBinaryMarshallablesEqual(a.EntryCreditBlock, b.EntryCreditBlock)
if err != nil || ok == false {
return false
}
if len(a.EBlocks) != len(b.EBlocks) || (len(a.Entries) != len(b.Entries)) {
return false
}
for i := range a.EBlocks {
ok, err = primitives.AreBinaryMarshallablesEqual(a.EBlocks[i], b.EBlocks[i])
if err != nil || ok == false {
return false
}
}
for i := range a.Entries {
ok, err = primitives.AreBinaryMarshallablesEqual(a.Entries[i], b.Entries[i])
if err != nil || ok == false {
return false
}
}
return true
}
func (m *DBStateMsg) GetRepeatHash() (rval interfaces.IHash) {
defer func() {
if rval != nil && reflect.ValueOf(rval).IsNil() {
rval = nil // convert an interface that is nil to a nil interface
primitives.LogNilHashBug("DBStateMsg.GetRepeatHash() saw an interface that was nil")
}
}()
return m.DirectoryBlock.GetHash()
}
func (m *DBStateMsg) GetHash() (rval interfaces.IHash) {
defer func() {
if rval != nil && reflect.ValueOf(rval).IsNil() {
rval = nil // convert an interface that is nil to a nil interface
primitives.LogNilHashBug("DBStateMsg.GetHash() saw an interface that was nil")
}
}()
// data, _ := m.MarshalBinary()
// return primitives.Sha(data)
// These two calls do the same thing. It should be standardized.
return m.GetMsgHash()
}
func (m *DBStateMsg) GetMsgHash() (rval interfaces.IHash) {
defer func() {
if rval != nil && reflect.ValueOf(rval).IsNil() {
rval = nil // convert an interface that is nil to a nil interface
primitives.LogNilHashBug("DBStateMsg.GetMsgHash() saw an interface that was nil")
}
}()
if m.MsgHash == nil {
data, err := m.MarshalBinary()
if err != nil {
return nil
}
m.MsgHash = primitives.Sha(data)
}
return m.MsgHash
}
func (m *DBStateMsg) Type() byte {
return constants.DBSTATE_MSG
}
func (m *DBStateMsg) GetTimestamp() interfaces.Timestamp {
return m.Timestamp
}
// Validate the message, given the state. Three possible results:
// < 0 -- Message is invalid. Discard
// 1 -- Message is valid
// NOTE! Do no return 0, that sticks this message in the holding map, vs the DBStateList
// ValidateSignatures is called when actually applying the DBState.
func (m *DBStateMsg) Validate(state interfaces.IState) int {
// No matter what, a block has to have what a block has to have.
if m.DirectoryBlock == nil || m.AdminBlock == nil || m.FactoidBlock == nil || m.EntryCreditBlock == nil {
state.AddStatus(fmt.Sprintf("DBStateMsg.Validate() Fail Doesn't have all the blocks"))
//We need the basic block types
return -1
}
if m.IsInDB {
return 1 // accept any DBState from our database
}
dbheight := m.DirectoryBlock.GetHeader().GetDBHeight()
// Just accept the genesis block
if dbheight == 0 {
return 1
}
if dbheight < state.GetDBHeightAtBoot() {
state.LogMessage("dbstatesloaded", "drop, below dbheight at boot", m)
return -1 // already have this one
}
if dbheight < state.GetHighestSavedBlk() {
state.LogMessage("dbstatesloaded", "drop, already in database", m)
return -1 // already have this one
}
if state.GetNetworkID() != m.DirectoryBlock.GetHeader().GetNetworkID() {
state.AddStatus(fmt.Sprintf("DBStateMsg.Validate() Fail ht: %d Expecting NetworkID %x and found %x",
dbheight, state.GetNetworkID(), m.DirectoryBlock.GetHeader().GetNetworkID()))
//Wrong network ID
return -1
}
if m.DirectoryBlock.GetHeader().GetNetworkID() == constants.MAIN_NETWORK_ID {
key := constants.CheckPoints[dbheight]
if key != "" {
if key != m.DirectoryBlock.DatabasePrimaryIndex().String() {
state.AddStatus(fmt.Sprintf("DBStateMsg.Validate() Fail ht: %d checkpoint failure. Had %s Expected %s",
dbheight, m.DirectoryBlock.DatabasePrimaryIndex().String(), key))
//Key does not match checkpoint
return -1
}
}
}
return 1
}
func (m *DBStateMsg) ValidateSignatures(state interfaces.IState) int {
// Validate Signatures
if m.IsInDB {
return 1
}
// If this is the next block that we need, we can validate it by signatures. If it is a past block
// we can validate by prevKeyMr of the block that follows this one
if m.DirectoryBlock.GetDatabaseHeight() == state.GetHighestSavedBlk()+1 {
// Fed count of this height -1, as we may not have the height itself
feds := state.GetFedServers(m.DirectoryBlock.GetDatabaseHeight())
fedCount := len(feds)
tally := m.SigTally(state)
if tally >= (fedCount/2 + 1) {
// This has all the signatures it needs
goto ValidSignatures
} else {
// If we remove servers, there will not be as many signatures. We need to accommodate for this
// by reducing our needed. This will only get called if we fall short on signatures.
aes := m.AdminBlock.GetABEntries()
for _, adminEntry := range aes {
switch adminEntry.Type() {
case constants.TYPE_REMOVE_FED_SERVER:
// Double check the entry is a real remove fed server message
_, ok := adminEntry.(*adminBlock.RemoveFederatedServer)
if !ok {
continue
}
// Reduce our total fed servers
fedCount--
case constants.TYPE_ADD_AUDIT_SERVER:
// This could be a demotion, so we need to reduce the fedcount
ad, ok := adminEntry.(*adminBlock.AddAuditServer)
if !ok {
continue
}
// See if this was one of our leaders
for _, f := range feds {
if f.GetChainID().IsSameAs(ad.IdentityChainID) {
fedCount--
break
}
}
}
}
if tally >= (fedCount/2 + 1) {
// This has all the signatures it needs
goto ValidSignatures
}
}
// It does not pass have enough signatures. It will not obtain more signatures.
return -1
} else { // Alternative to signatures passing by checking our DB
// This is a future block. We cannot determine at this time
if m.DirectoryBlock.GetDatabaseHeight() > state.GetHighestSavedBlk()+1 {
return 0
}
// This block is not the next block we need. Check this block +1 and check it's prevKeyMr
next := state.GetDirectoryBlockByHeight(m.DirectoryBlock.GetDatabaseHeight() + 1)
if next == nil {
// Do not have the next directory block, so we cannot tell by this method.
// We should have this dblock though, so maybe we should return -1?
return 0
}
// If the prevKeyMr of the next matches this one, we know it is valid.
if next.GetHeader().GetPrevKeyMR().IsSameAs(m.DirectoryBlock.GetKeyMR()) {
goto ValidSignatures
} else {
// The KeyMR does not match, this block is invalid
return -1
}
}
ValidSignatures: // Goto here if signatures pass
// ValidateData will ensure all the data given matches the DBlock
return m.ValidateData(state)
}
// ValidateData will check the data attached to the DBState against the directory block it contains.
// This is ensure no additional junk is attached to a valid DBState
func (m *DBStateMsg) ValidateData(state interfaces.IState) int {
// Checking the content of the DBState against the directoryblock contained
// Map of Entries and Eblocks in this DBState dblock
// A value of true indicates a repeat. Repeats are not enforce though
eblocks := make(map[[32]byte]bool) //, len(m.EBlocks))
ents := make(map[[32]byte]bool) //, len(m.Entries))
// Ensure blocks in the DBlock matches blocks in DBState
for _, b := range m.DirectoryBlock.GetEBlockDBEntries() {
switch {
case bytes.Compare(b.GetChainID().Bytes(), constants.ADMIN_CHAINID) == 0:
// Validate ABlock
goodKeyMr, err := m.AdminBlock.GetKeyMR()
if err != nil {
return -1
}
if !b.GetKeyMR().IsSameAs(goodKeyMr) {
return -1
}
case bytes.Compare(b.GetChainID().Bytes(), constants.FACTOID_CHAINID) == 0:
// Validate FBlock
if !b.GetKeyMR().IsSameAs(m.FactoidBlock.GetKeyMR()) {
return -1
}
case bytes.Compare(b.GetChainID().Bytes(), constants.EC_CHAINID) == 0:
// Validate ECBlock
if !b.GetKeyMR().IsSameAs(m.EntryCreditBlock.GetHash()) {
return -1
}
default: // EBLOCK
// Eblocks in the DBlock. Not only check if the Eblocks in DBState list are good, but also entries
eblocks[b.GetKeyMR().Fixed()] = false
}
}
// Loop over eblocks and see if they fall in the map
for _, eb := range m.EBlocks {
keymr, err := eb.KeyMR()
if err != nil {
return -1
}
// If the eblock does not exist in our map, it doesn't exist in the directory block
if _, ok := eblocks[keymr.Fixed()]; !ok {
return -1
}
eblocks[keymr.Fixed()] = true
for _, e := range eb.GetEntryHashes() {
ents[e.Fixed()] = false
}
}
for _, e := range m.Entries {
// Although we can check for repeated entries, a directory block is allowed to contain duplicate entries
// So just check if the entry is in the DBlock
if _, ok := ents[e.GetHash().Fixed()]; !ok {
return -1
}
ents[e.GetHash().Fixed()] = true
}
return 1
}
func (m *DBStateMsg) SigTally(state interfaces.IState) int {
dbheight := m.DirectoryBlock.GetHeader().GetDBHeight()
validSigCount := 0
validSigCount += m.checkpointFix()
data, err := m.DirectoryBlock.GetHeader().MarshalBinary()
if err != nil {
state.AddStatus(fmt.Sprint("Debug: DBState Signature Error, Marshal binary errored"))
return validSigCount
}
// Signatures that are not valid by current fed list
var remainingSig []interfaces.IFullSignature
// If there is a repeat signature, we do not count it twice
sigmap := make(map[string]bool)
for _, sig := range m.SignatureList.List {
// check expected signature
if sigmap[fmt.Sprintf("%x", sig.GetSignature()[:])] {
continue // Toss duplicate signatures
}
sigmap[fmt.Sprintf("%x", sig.GetSignature()[:])] = true
check, err := state.FastVerifyAuthoritySignature(data, sig, dbheight)
if err == nil && check >= 0 {
validSigCount++
continue
}
// it was not the expected signature check the boot strap
//Check signature against the Skeleton key
authoritativeKey := state.GetNetworkBootStrapKey()
if authoritativeKey != nil {
if bytes.Compare(sig.GetKey(), authoritativeKey.Bytes()) == 0 {
if sig.Verify(data) {
validSigCount++
continue
}
}
}
// save the unverified sig so we can check for leadership changes later on
if sig.Verify(data) {
remainingSig = append(remainingSig, sig)
}
}
// If promotions have occurred this block, we need to account for their signatures to be
// valid. We will only pay for this overhead if there are signatures left, meaning most blocks will
// not enter this loop
if len(remainingSig) > 0 {
type tempAuthority struct {
Key []byte
Promoted bool
}
// Map of new federated servers, and their keys
newSigners := make(map[string]*tempAuthority)
// Search for promotions and their keys and populate the map:
aes := m.AdminBlock.GetABEntries()
for _, adminEntry := range aes {
switch adminEntry.Type() {
case constants.TYPE_ADD_FED_SERVER:
// New federated server that can sign blocks
r, ok := adminEntry.(*adminBlock.AddFederatedServer)
if !ok {
// This shouldn't fail, as we checked the type
continue
}
if _, ok := newSigners[r.IdentityChainID.String()]; !ok {
newSigners[r.IdentityChainID.String()] = new(tempAuthority)
}
newSigners[r.IdentityChainID.String()].Promoted = true
case constants.TYPE_REMOVE_FED_SERVER:
// A remove will remove this server from our list of servers that can sign,
// but we need them to still be valid, so we will allow them to still sign
r, ok := adminEntry.(*adminBlock.RemoveFederatedServer)
if !ok {
// This shouldn't fail, as we checked the type
continue
}
if _, ok := newSigners[r.IdentityChainID.String()]; !ok {
newSigners[r.IdentityChainID.String()] = new(tempAuthority)
}
newSigners[r.IdentityChainID.String()].Promoted = true
case constants.TYPE_ADD_FED_SERVER_KEY:
r, ok := adminEntry.(*adminBlock.AddFederatedServerSigningKey)
if !ok {
// This shouldn't fail, as we checked the type
continue
}
// We need to grab the signing key from the admin block if provided
if _, ok := newSigners[r.IdentityChainID.String()]; !ok {
newSigners[r.IdentityChainID.String()] = new(tempAuthority)
}
keybytes, err := r.PublicKey.MarshalBinary()
if err != nil {
continue
}
newSigners[r.IdentityChainID.String()].Key = keybytes
}
}
// There is a chance their signing keys won't be located in the admin block. If they came from being an audit server,
// their key might be in the authority list, or identity list.
for i, v := range newSigners {
if v.Key != nil {
continue
}
idHash, err := primitives.HexToHash(i)
if err != nil {
continue
}
signingkey, status := state.GetSigningKey(idHash)
if status >= 0 {
v.Key = signingkey.Bytes()
}
}
// These signatures that did not validate with current set of authorities
for _, sig := range remainingSig {
InnerSingerLoop:
for _, signer := range newSigners {
if bytes.Compare(sig.GetKey(), signer.Key) == 0 {
validSigCount++
break InnerSingerLoop
}
}
}
}
return validSigCount
}
func (m *DBStateMsg) checkpointFix() int {
returnAmt := 0
dbheight := m.DirectoryBlock.GetDatabaseHeight()
allow := func(str string, siglist SigList) int {
amt := 0
goodSig, _ := hex.DecodeString(str)
for _, s := range siglist.List {
if bytes.Compare(s.Bytes(), goodSig) == 0 {
amt++
break
}
}
return amt
}
switch dbheight {
case 75893:
returnAmt += allow("8066fc4222eff67470ffaca15bdb5d6d15b65daf3cc86c121b872d7485b388b3cb4b7bbbd0248076065262d54699bab68e7d5be96e137aa3428b903916e4180a", m.SignatureList)
case 76720:
returnAmt += allow("ab429576ee93485cfffe0c778d429073f24ce76d3014f2ddecd6e90e87a5e912b849842597cae23a66beee203ee455bd44fe4073747ce6c099a21f4525c3d901", m.SignatureList)
case 76792:
returnAmt += allow("9f86122d624400b3036e60105f3db4e99199ae9217cbeb1462811426319983dc0e4f5e5cd16996cc3cf2940ead765ce00fc699e23b459395569c10e1df4c650b", m.SignatureList)
case 87624:
returnAmt += allow("cb67b7f8ed2b2845b9941264f3631a639685e2b7a47b8c353461ee9b197c2307aaab27419b72f5478f0e2a0d610ef4f16cbfaa5e9889c114415a63b8cb54f000", m.SignatureList)
default:
return 0
}
return returnAmt
}
func (m *DBStateMsg) ComputeVMIndex(state interfaces.IState) {}
// Execute the leader functions of the given message
func (m *DBStateMsg) LeaderExecute(state interfaces.IState) {
m.FollowerExecute(state)
}
func (m *DBStateMsg) FollowerExecute(state interfaces.IState) {
state.FollowerExecuteDBState(m)
}
// DBState messages do not go into the process list.
func (e *DBStateMsg) Process(dbheight uint32, state interfaces.IState) bool {
panic("DBStatemsg should never have its Process() method called")
}
func (e *DBStateMsg) JSONByte() ([]byte, error) {
return primitives.EncodeJSON(e)
}
func (e *DBStateMsg) JSONString() (string, error) {
return primitives.EncodeJSONString(e)
}
func (m *DBStateMsg) UnmarshalBinaryData(data []byte) (newData []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Error unmarshalling Directory Block State Message: %v", r)
}
}()
newData = data
if newData[0] != m.Type() {
return nil, fmt.Errorf("Invalid Message type")
}
newData = newData[1:]
m.Peer2Peer = true
m.Timestamp = new(primitives.Timestamp)
newData, err = m.Timestamp.UnmarshalBinaryData(newData)
if err != nil {
return nil, err
}
m.DirectoryBlock = new(directoryBlock.DirectoryBlock)
newData, err = m.DirectoryBlock.UnmarshalBinaryData(newData)
if err != nil {
return nil, err
}
m.AdminBlock = new(adminBlock.AdminBlock)
newData, err = m.AdminBlock.UnmarshalBinaryData(newData)
if err != nil {
return nil, err
}
m.FactoidBlock = new(factoid.FBlock)
newData, err = m.FactoidBlock.UnmarshalBinaryData(newData)
if err != nil {
return nil, err
}
m.EntryCreditBlock = entryCreditBlock.NewECBlock()
newData, err = m.EntryCreditBlock.UnmarshalBinaryData(newData)
if err != nil {
return nil, err
}
eBlockCount, newData := binary.BigEndian.Uint32(newData[0:4]), newData[4:]
for i := uint32(0); i < eBlockCount; i++ {
eBlock := entryBlock.NewEBlock()
newData, err = eBlock.UnmarshalBinaryData(newData)
if err != nil {
panic(err.Error())
}
m.EBlocks = append(m.EBlocks, eBlock)
}
entryCount, newData := binary.BigEndian.Uint32(newData[0:4]), newData[4:]
for i := uint32(0); i < entryCount; i++ {
var entrySize uint32
entrySize, newData = binary.BigEndian.Uint32(newData[0:4]), newData[4:]
entry := entryBlock.NewEntry()
newData, err = newData[int(entrySize):], entry.UnmarshalBinary(newData[:int(entrySize)])
if err != nil {
panic(err.Error())
}
m.Entries = append(m.Entries, entry)
}
newData, err = m.SignatureList.UnmarshalBinaryData(newData)
if err != nil {
return nil, err
}
return
}
func (m *DBStateMsg) UnmarshalBinary(data []byte) error {
_, err := m.UnmarshalBinaryData(data)
return err
}
func (m *DBStateMsg) MarshalBinary() (rval []byte, err error) {
defer func(pe *error) {
if *pe != nil {
fmt.Fprintf(os.Stderr, "DBStateMsg.MarshalBinary err:%v", *pe)
}
}(&err)
var buf primitives.Buffer
binary.Write(&buf, binary.BigEndian, m.Type())
t := m.GetTimestamp()
data, err := t.MarshalBinary()
if err != nil {
return nil, err
}
buf.Write(data)
data, err = m.DirectoryBlock.MarshalBinary()
if err != nil {
return nil, err
}
buf.Write(data)
data, err = m.AdminBlock.MarshalBinary()
if err != nil {
return nil, err
}
buf.Write(data)
data, err = m.FactoidBlock.MarshalBinary()
if err != nil {
return nil, err
}
buf.Write(data)
data, err = m.EntryCreditBlock.MarshalBinary()
if err != nil {
return nil, err
}
buf.Write(data)
eBlockCount := uint32(len(m.EBlocks))
binary.Write(&buf, binary.BigEndian, eBlockCount)
for _, eb := range m.EBlocks {
bin, err := eb.MarshalBinary()
if err != nil {
return nil, err
}
buf.Write(bin)
}
entryCount := uint32(len(m.Entries))
binary.Write(&buf, binary.BigEndian, entryCount)
for _, e := range m.Entries {
bin, err := e.MarshalBinary()
if err != nil || bin == nil || len(bin) == 0 {
return nil, err
}
entrySize := uint32(len(bin))
binary.Write(&buf, binary.BigEndian, entrySize)
buf.Write(bin)
}
if d, err := m.SignatureList.MarshalBinary(); err != nil {
return nil, err
} else {
buf.Write(d)
}
return buf.DeepCopyBytes(), nil
}
func (m *DBStateMsg) String() string {
data, _ := m.MarshalBinary()
return fmt.Sprintf("DBState: dbht:%3d [size: %11s] dblock %6x admin %6x fb %6x ec %6x hash %6x ts:%s InDB %v IsLast %v Sigs %d",
m.DirectoryBlock.GetHeader().GetDBHeight(),
primitives.AddCommas(int64(len(data))),
m.DirectoryBlock.GetKeyMR().Bytes()[:3],
m.AdminBlock.GetHash().Bytes()[:3],
m.FactoidBlock.GetHash().Bytes()[:3],
m.EntryCreditBlock.GetHash().Bytes()[:3],
m.GetHash().Bytes()[:3], m.DirectoryBlock.GetTimestamp().String(), m.IsInDB, m.IsLast, m.SignatureList.Length)
}
func (m *DBStateMsg) LogFields() log.Fields {
return log.Fields{"category": "message", "messagetype": "dbstate",
"dbheight": m.DirectoryBlock.GetHeader().GetDBHeight(),
"dblockhash": m.DirectoryBlock.GetKeyMR().String(),
"ablockhash": m.AdminBlock.GetHash().String(),
"fblockhash": m.FactoidBlock.GetHash().String(),
"ecblockhash": m.EntryCreditBlock.GetHash().String(),
"hash": m.GetHash().String()}
}
func NewDBStateMsg(timestamp interfaces.Timestamp,
d interfaces.IDirectoryBlock,
a interfaces.IAdminBlock,
f interfaces.IFBlock,
e interfaces.IEntryCreditBlock,
eBlocks []interfaces.IEntryBlock,
entries []interfaces.IEBEntry,
sigList []interfaces.IFullSignature) interfaces.IMsg {
msg := new(DBStateMsg)
msg.NoResend = true
msg.Peer2Peer = true
msg.Timestamp = timestamp
msg.DirectoryBlock = d
msg.AdminBlock = a
msg.FactoidBlock = f
msg.EntryCreditBlock = e
msg.EBlocks = eBlocks
msg.Entries = entries
sl := new(SigList)
sl.Length = uint32(len(sigList))
sl.List = sigList
msg.SignatureList = *sl
return msg
}
type SigList struct {
Length uint32
List []interfaces.IFullSignature
}
func (sl *SigList) MarshalBinary() (data []byte, err error) {
var buf primitives.Buffer
binary.Write(&buf, binary.BigEndian, uint32(sl.Length))
for _, individualSig := range sl.List {
if d, err := individualSig.MarshalBinary(); err != nil {
return nil, err
} else {
buf.Write(d)
}
}
return buf.DeepCopyBytes(), nil
}
func (sl *SigList) UnmarshalBinaryData(data []byte) (newData []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Error unmarshalling SigList in Full Server Fault: %v", r)
}
}()
newData = data
sl.Length, newData = binary.BigEndian.Uint32(newData[0:4]), newData[4:]
for i := sl.Length; i > 0; i-- {
tempSig := new(primitives.Signature)
newData, err = tempSig.UnmarshalBinaryData(newData)
if err != nil {
return nil, err
}
sl.List = append(sl.List, tempSig)
}
return newData, nil
}