-
Notifications
You must be signed in to change notification settings - Fork 0
/
entry.go
470 lines (401 loc) · 10.5 KB
/
entry.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
// Copyright 2017 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package entryBlock
import (
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"fmt"
"os"
"reflect"
"github.com/DCNT-Hammer/dcnt/common/interfaces"
"github.com/DCNT-Hammer/dcnt/common/primitives"
"github.com/DCNT-Hammer/dcnt/common/primitives/random"
)
// An Entry is the element which carries user data
// https://github.com/DCNT-Hammer/dcntocs/blob/master/dcntataStructureDetails.md#entry
type Entry struct {
Version uint8 `json:"version"`
ChainID interfaces.IHash `json:"chainid"`
ExtIDs []primitives.ByteSlice `json:"extids"`
Content primitives.ByteSlice `json:"content"`
// cache
hash interfaces.IHash
}
var _ interfaces.IEBEntry = (*Entry)(nil)
var _ interfaces.DatabaseBatchable = (*Entry)(nil)
var _ interfaces.BinaryMarshallable = (*Entry)(nil)
func RandomEntry() interfaces.IEBEntry {
e := NewEntry()
e.Version = random.RandUInt8()
e.ChainID = primitives.RandomHash()
l := random.RandIntBetween(0, 20)
for i := 0; i < l; i++ {
e.ExtIDs = append(e.ExtIDs, *primitives.RandomByteSlice())
}
e.Content = *primitives.RandomByteSlice()
return e
}
func DeterministicEntry(i int) interfaces.IEBEntry {
e := NewEntry()
e.Version = 0
bs := fmt.Sprintf("%x", i)
if len(bs)%2 == 1 {
bs = "0" + bs
}
e.ExtIDs = []primitives.ByteSlice{*primitives.StringToByteSlice(bs)}
//e.ExtIDs = append(e.ExtIDs, *primitives.StringToByteSlice(fmt.Sprintf("%d", i)))
e.ChainID = ExternalIDsToChainID([][]byte{e.ExtIDs[0].Bytes})
return e
}
func (c *Entry) IsSameAs(b interfaces.IEBEntry) bool {
if b == nil {
if c != nil {
return false
} else {
return true
}
}
a := b.(*Entry)
if c.Version != a.Version {
return false
}
if len(c.ExtIDs) != len(a.ExtIDs) {
return false
}
for i := range c.ExtIDs {
if c.ExtIDs[i].IsSameAs(&a.ExtIDs[i]) == false {
return false
}
}
if c.ChainID.IsSameAs(a.ChainID) == false {
return false
}
if c.Content.IsSameAs(&a.Content) == false {
return false
}
return true
}
// Returns the size of the entry subject to payment in K. So anything up
// to 1K returns 1, everything up to and including 2K returns 2, etc.
// An error returns 100 (an invalid size)
func (c *Entry) KSize() int {
data, err := c.MarshalBinary()
if err != nil {
return 100
}
return (len(data) - 35 + 1023) / 1024
}
func (c *Entry) New() interfaces.BinaryMarshallableAndCopyable {
return NewEntry()
}
func (c *Entry) GetDatabaseHeight() uint32 {
return 0
}
func (e *Entry) GetWeld() []byte {
return primitives.DoubleSha(append(e.GetHash().Bytes(), e.GetChainID().Bytes()...))
}
func (e *Entry) GetWeldHash() (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("Entry.GetWeldHash() saw an interface that was nil")
}
}()
hash := primitives.NewZeroHash()
hash.SetBytes(e.GetWeld())
return hash
}
func (c *Entry) GetChainID() (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("Entry.GetChainID() saw an interface that was nil")
}
}()
return c.ChainID
}
func (c *Entry) DatabasePrimaryIndex() (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("Entry.DatabasePrimaryIndex() saw an interface that was nil")
}
}()
return c.GetHash()
}
func (c *Entry) DatabaseSecondaryIndex() (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("Entry.DatabaseSecondaryIndex() saw an interface that was nil")
}
}()
return nil
}
// NewChainID generates a ChainID from an entry. ChainID = primitives.Sha(Sha(ExtIDs[0]) +
// Sha(ExtIDs[1] + ... + Sha(ExtIDs[n]))
func NewChainID(e interfaces.IEBEntry) interfaces.IHash {
return ExternalIDsToChainID(e.ExternalIDs())
}
func ExternalIDsToChainID(extIDs [][]byte) interfaces.IHash {
id := new(primitives.Hash)
sum := sha256.New()
for _, v := range extIDs {
x := sha256.Sum256(v)
sum.Write(x[:])
}
id.SetBytes(sum.Sum(nil))
return id
}
func (e *Entry) GetContent() []byte {
return e.Content.Bytes
}
func (e *Entry) GetChainIDHash() (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("Entry.GetChainIDHash() saw an interface that was nil")
}
}()
return e.ChainID
}
func (e *Entry) ExternalIDs() [][]byte {
answer := [][]byte{}
for _, v := range e.ExtIDs {
answer = append(answer, v.Bytes)
}
return answer
}
func (e *Entry) IsValid() bool {
//double check the version
if e.Version != 0 {
return false
}
if e.KSize() > 10 {
return false
}
return true
}
func (e *Entry) 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("Entry.GetHash() saw an interface that was nil")
}
}()
if e.hash == nil || e.hash.PFixed() == nil {
h := primitives.NewZeroHash()
entry, err := e.MarshalBinary()
if err != nil {
fmt.Println("Failed to Marshal Entry", e.String())
return nil
}
h1 := sha512.Sum512(entry)
h2 := sha256.Sum256(append(h1[:], entry[:]...))
h.SetBytes(h2[:])
e.hash = h
}
return e.hash
}
func (e *Entry) MarshalBinary() (rval []byte, err error) {
defer func(pe *error) {
if *pe != nil {
fmt.Fprintf(os.Stderr, "Entry.MarshalBinary err:%v", *pe)
}
}(&err)
buf := primitives.NewBuffer(nil)
// 1 byte Version
err = buf.PushByte(byte(e.Version))
if err != nil {
return nil, err
}
if e.ChainID == nil {
e.ChainID = primitives.NewZeroHash()
}
// 32 byte ChainID
err = buf.PushBinaryMarshallable(e.ChainID)
if err != nil {
return nil, err
}
// ExtIDs
if ext, err := e.MarshalExtIDsBinary(); err != nil {
return nil, err
} else {
// 2 byte size of ExtIDs
if err := binary.Write(buf, binary.BigEndian, int16(len(ext))); err != nil {
return nil, err
}
// binary ExtIDs
buf.Write(ext)
}
// Content
buf.Write(e.Content.Bytes)
return buf.Bytes(), nil
}
// MarshalExtIDsBinary marshals the ExtIDs into a []byte containing a series of
// 2 byte size of each ExtID followed by the ExtID.
func (e *Entry) MarshalExtIDsBinary() (rval []byte, err error) {
defer func(pe *error) {
if *pe != nil {
fmt.Fprintf(os.Stderr, "Entry.MarshalExtIDsBinary err:%v", *pe)
}
}(&err)
buf := new(primitives.Buffer)
for _, x := range e.ExtIDs {
// 2 byte size of the ExtID
if err := binary.Write(buf, binary.BigEndian, uint16(len(x.Bytes))); err != nil {
return nil, err
}
// ExtID bytes
buf.Write(x.Bytes)
}
return buf.DeepCopyBytes(), nil
}
func UnmarshalEntry(data []byte) (interfaces.IEBEntry, error) {
entry := NewEntry()
err := entry.UnmarshalBinary(data)
if err != nil {
return nil, err
}
return entry, nil
}
func (e *Entry) UnmarshalBinaryData(data []byte) (_ []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Error unmarshalling: %v", r)
}
}()
buf := primitives.NewBuffer(data)
// 1 byte Version
e.Version, err = buf.PopByte()
if err != nil {
return nil, err
}
// 32 byte ChainID
e.ChainID = primitives.NewZeroHash()
err = buf.PopBinaryMarshallable(e.ChainID)
if err != nil {
return nil, err
}
// 2 byte size of ExtIDs
var extSize uint16
if err = binary.Read(buf, binary.BigEndian, &extSize); err != nil {
return nil, err
}
// ExtIDs
for i := int(extSize); i > 0; {
var xsize int16
binary.Read(buf, binary.BigEndian, &xsize)
i -= 2
if i < 0 {
err = fmt.Errorf("Error parsing external IDs")
return nil, err
}
// check that the payload size is not too big before we allocate the
// buffer. Max payload size is 10KB
if xsize > 10240 {
return nil, fmt.Errorf(
"Error: entry.UnmarshalBinary: ExtIDs size %d too high (uint "+
" underflow?)",
xsize,
)
}
x := make([]byte, xsize)
if n, err := buf.Read(x); err != nil {
return nil, err
} else {
if c := cap(x); n != c {
err = fmt.Errorf("Could not read ExtID: Read %d bytes of %d\n", n, c)
return nil, err
}
ex := primitives.ByteSlice{}
err = ex.UnmarshalBinary(x)
if err != nil {
return nil, err
}
e.ExtIDs = append(e.ExtIDs, ex)
i -= n
if i < 0 {
err = fmt.Errorf("Error parsing external IDs")
return nil, err
}
}
}
// Content
err = e.Content.UnmarshalBinary(buf.Bytes())
if err != nil {
return nil, err
}
return nil, nil
}
func (e *Entry) UnmarshalBinary(data []byte) (err error) {
_, err = e.UnmarshalBinaryData(data)
return
}
func (e *Entry) JSONByte() ([]byte, error) {
return primitives.EncodeJSON(e)
}
func (e *Entry) JSONString() (string, error) {
return primitives.EncodeJSONString(e)
}
func (e *Entry) String() string {
str, _ := e.JSONString()
return str
}
/***************************************************************
* Helper Functions
***************************************************************/
func NewEntry() *Entry {
e := new(Entry)
e.ChainID = primitives.NewZeroHash()
e.ExtIDs = make([]primitives.ByteSlice, 0)
e.Content = primitives.ByteSlice{}
return e
}
func MarshalEntryList(list []interfaces.IEBEntry) ([]byte, error) {
buf := primitives.NewBuffer(nil)
l := len(list)
buf.PushVarInt(uint64(l))
for _, v := range list {
bin, err := v.MarshalBinary()
if err != nil {
return nil, err
}
err = buf.PushBytes(bin)
if err != nil {
return nil, err
}
}
return buf.DeepCopyBytes(), nil
}
func UnmarshalEntryList(data []byte) ([]interfaces.IEBEntry, []byte, error) {
buf := primitives.NewBuffer(data)
entryLimit := uint64(buf.Len())
entryCount, err := buf.PopVarInt()
if err != nil {
return nil, nil, err
}
if entryCount > entryLimit {
return nil, nil, fmt.Errorf(
"Error: UnmarshalEntryList: entry count %d higher than space in "+
"body %d (uint underflow?)",
entryCount, entryLimit,
)
}
list := make([]interfaces.IEBEntry, int(entryCount))
for i := range list {
e := NewEntry()
x, err := buf.PopBytes()
if err != nil {
return nil, nil, err
}
err = e.UnmarshalBinary(x)
if err != nil {
return nil, nil, err
}
list[i] = e
}
return list, buf.DeepCopyBytes(), nil
}