forked from FactomProject/factomd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
receipts.go
424 lines (374 loc) · 10.3 KB
/
receipts.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
// Copyright 2017 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package receipts
import (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/FactomProject/factomd/common/interfaces"
"github.com/FactomProject/factomd/common/primitives"
)
type Receipt struct {
Entry *EntryJSON `json:"entry,omitempty"`
MerkleBranch []*primitives.MerkleNode `json:"merklebranch,omitempty"`
EntryBlockKeyMR *primitives.Hash `json:"entryblockkeymr,omitempty"`
DirectoryBlockKeyMR *primitives.Hash `json:"directoryblockkeymr,omitempty"`
DirectoryBlockHeight uint32 `json:"directoryblockheight,omitempty"`
}
func (e *Receipt) TrimReceipt() {
if e == nil {
return
}
entry, _ := primitives.NewShaHashFromStr(e.Entry.EntryHash)
for i := range e.MerkleBranch {
if entry.IsSameAs(e.MerkleBranch[i].Left) {
e.MerkleBranch[i].Left = nil
} else {
if entry.IsSameAs(e.MerkleBranch[i].Right) {
e.MerkleBranch[i].Right = nil
}
}
entry = e.MerkleBranch[i].Top
e.MerkleBranch[i].Top = nil
}
}
func (e *Receipt) Validate() error {
if e == nil {
return fmt.Errorf("No receipt provided")
}
if e.Entry == nil {
return fmt.Errorf("Receipt has no entry")
}
if e.MerkleBranch == nil {
return fmt.Errorf("Receipt has no MerkleBranch")
}
if e.EntryBlockKeyMR == nil {
return fmt.Errorf("Receipt has no EntryBlockKeyMR")
}
if e.DirectoryBlockKeyMR == nil {
return fmt.Errorf("Receipt has no DirectoryBlockKeyMR")
}
entryHash, err := primitives.NewShaHashFromStr(e.Entry.EntryHash)
//TODO: validate entry hashes into EntryHash
if err != nil {
return err
}
var left interfaces.IHash
var right interfaces.IHash
var currentEntry interfaces.IHash
currentEntry = entryHash
eBlockFound := false
dBlockFound := false
for i, node := range e.MerkleBranch {
if node.Left == nil {
if node.Right == nil {
return fmt.Errorf("Node %v/%v has two nil sides", i, len(e.MerkleBranch))
}
left = currentEntry
right = node.Right
} else {
left = node.Left
if node.Right == nil {
right = currentEntry
} else {
right = node.Right
}
}
if left.IsSameAs(currentEntry) == false && left.IsSameAs(currentEntry) {
return fmt.Errorf("Entry %v not found in node %v/%v", currentEntry, i, len(e.MerkleBranch))
}
top := primitives.HashMerkleBranches(left, right)
if node.Top != nil {
if top.IsSameAs(node.Top) == false {
return fmt.Errorf("Derived top %v is not the same as saved top in node %v/%v", top, i, len(e.MerkleBranch))
}
}
if top.IsSameAs(e.EntryBlockKeyMR) == true {
eBlockFound = true
}
if top.IsSameAs(e.DirectoryBlockKeyMR) == true {
dBlockFound = true
}
currentEntry = top
}
if eBlockFound == false {
return fmt.Errorf("EntryBlockKeyMR not found in branch")
}
if dBlockFound == false {
return fmt.Errorf("DirectoryBlockKeyMR not found in branch")
}
return nil
}
func (e *Receipt) IsSameAs(r *Receipt) bool {
if e.Entry == nil {
if r.Entry != nil {
return false
}
} else {
if e.Entry.IsSameAs(r.Entry) == false {
return false
}
}
if e.MerkleBranch == nil {
if r.MerkleBranch != nil {
return false
}
} else {
if len(e.MerkleBranch) != len(r.MerkleBranch) {
return false
}
for i := range e.MerkleBranch {
if e.MerkleBranch[i].Left == nil {
if r.MerkleBranch[i].Left != nil {
return false
}
} else {
if e.MerkleBranch[i].Left.IsSameAs(r.MerkleBranch[i].Left) == false {
return false
}
}
if e.MerkleBranch[i].Right == nil {
if r.MerkleBranch[i].Right != nil {
return false
}
} else {
if e.MerkleBranch[i].Right.IsSameAs(r.MerkleBranch[i].Right) == false {
return false
}
}
if e.MerkleBranch[i].Top == nil {
if r.MerkleBranch[i].Top != nil {
return false
}
} else {
if e.MerkleBranch[i].Top.IsSameAs(r.MerkleBranch[i].Top) == false {
return false
}
}
}
}
if e.EntryBlockKeyMR == nil {
if r.EntryBlockKeyMR != nil {
return false
}
} else {
if e.EntryBlockKeyMR.IsSameAs(r.EntryBlockKeyMR) == false {
return false
}
}
if e.DirectoryBlockKeyMR == nil {
if r.DirectoryBlockKeyMR != nil {
return false
}
} else {
if e.DirectoryBlockKeyMR.IsSameAs(r.DirectoryBlockKeyMR) == false {
return false
}
}
return true
}
func (e *Receipt) JSONByte() ([]byte, error) {
return primitives.EncodeJSON(e)
}
func (e *Receipt) JSONString() (string, error) {
return primitives.EncodeJSONString(e)
}
func (e *Receipt) CustomMarshalString() string {
str, _ := e.JSONString()
return str
}
func (e *Receipt) DecodeString(str string) error {
jsonByte := []byte(str)
err := json.Unmarshal(jsonByte, e)
if err != nil {
return err
}
return nil
}
func DecodeReceiptString(str string) (*Receipt, error) {
receipt := new(Receipt)
err := json.Unmarshal([]byte(str), &receipt)
if err != nil {
return nil, err
}
return receipt, nil
}
type EntryJSON struct {
Raw string `json:"raw,omitempty"`
EntryHash string `json:"entryhash,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
}
func (e *EntryJSON) JSONByte() ([]byte, error) {
return primitives.EncodeJSON(e)
}
func (e *EntryJSON) JSONString() (string, error) {
return primitives.EncodeJSONString(e)
}
func (e *EntryJSON) String() string {
str, _ := e.JSONString()
return str
}
func (e *EntryJSON) IsSameAs(r *EntryJSON) bool {
if r == nil {
return false
}
if e.Raw != r.Raw {
return false
}
if e.EntryHash != r.EntryHash {
return false
}
if e.Timestamp != r.Timestamp {
return false
}
return true
}
func CreateFullReceipt(dbo interfaces.DBOverlaySimple, entryHash interfaces.IHash, includeRawEntry bool) (*Receipt, error) {
return CreateReceipt(dbo, entryHash, includeRawEntry)
}
func CreateMinimalReceipt(dbo interfaces.DBOverlaySimple, entryID interfaces.IHash) (*Receipt, error) {
receipt, err := CreateReceipt(dbo, entryID, false)
if err != nil {
return nil, err
}
receipt.TrimReceipt()
return receipt, nil
}
func CreateReceipt(dbo interfaces.DBOverlaySimple, entryHash interfaces.IHash, includeRawEntry bool) (*Receipt, error) {
receipt := new(Receipt)
receipt.Entry = new(EntryJSON)
receipt.Entry.EntryHash = entryHash.String()
// Optionally include the full marshalled entry in the receipt
if includeRawEntry {
entry, err := dbo.FetchEntry(entryHash)
if err != nil {
return nil, err
} else if entry == nil {
return nil, fmt.Errorf("entry not found")
}
raw, err := entry.MarshalBinary()
if err != nil {
return nil, err
}
receipt.Entry.Raw = hex.EncodeToString(raw)
}
// Entry Block
hash, err := dbo.FetchIncludedIn(entryHash)
if err != nil {
return nil, err
} else if hash == nil {
return nil, fmt.Errorf("Block containing entry not found")
}
eBlock, err := dbo.FetchEBlock(hash)
if err != nil {
return nil, err
} else if eBlock == nil {
return nil, fmt.Errorf("EBlock not found")
}
hash = eBlock.DatabasePrimaryIndex()
receipt.EntryBlockKeyMR = hash.(*primitives.Hash)
eBlockEntries := eBlock.GetEntryHashes()
branch := primitives.BuildMerkleBranchForHash(eBlockEntries, entryHash, true)
blockNode := new(primitives.MerkleNode)
left, err := eBlock.HeaderHash()
if err != nil {
return nil, err
}
blockNode.Left = left.(*primitives.Hash)
blockNode.Right = eBlock.BodyKeyMR().(*primitives.Hash)
blockNode.Top = hash.(*primitives.Hash)
branch = append(branch, blockNode)
receipt.MerkleBranch = append(receipt.MerkleBranch, branch...)
// Directory Block
hash, err = dbo.FetchIncludedIn(hash)
if err != nil {
return nil, err
} else if hash == nil {
return nil, fmt.Errorf("Block containing EBlock not found")
}
dBlock, err := dbo.FetchDBlock(hash)
if err != nil {
return nil, err
} else if dBlock == nil {
return nil, fmt.Errorf("DBlock not found")
}
dBlockEntries := dBlock.GetEntryHashesForBranch()
branch = primitives.BuildMerkleBranchForHash(dBlockEntries, receipt.EntryBlockKeyMR, true)
blockNode = new(primitives.MerkleNode)
left, err = dBlock.GetHeaderHash()
if err != nil {
return nil, err
}
blockNode.Left = left.(*primitives.Hash)
blockNode.Right = dBlock.BodyKeyMR().(*primitives.Hash)
blockNode.Top = hash.(*primitives.Hash)
branch = append(branch, blockNode)
receipt.MerkleBranch = append(receipt.MerkleBranch, branch...)
// Directory Block Info
hash = dBlock.DatabasePrimaryIndex()
receipt.DirectoryBlockKeyMR = hash.(*primitives.Hash)
receipt.DirectoryBlockHeight = dBlock.GetDatabaseHeight()
// Now that we have enough info available, find entry timestamp
mins := make(map[string]uint8) // create a map of possible minute markers
for i := byte(1); i <= 10; i++ {
h := make([]byte, 32)
h[len(h)-1] = i
mins[hex.EncodeToString(h)] = i
}
entryFound := false
for _, v := range eBlockEntries {
if v.IsSameAs(entryHash) {
entryFound = true
}
if n, exist := mins[v.String()]; exist && entryFound {
// Found a minute marker and found the entry already, set the timestamp and break
receipt.Entry.Timestamp = int64(dBlock.GetHeader().GetTimestamp().GetTimeSeconds() + 60*int64(n))
break
}
}
return receipt, nil
}
func VerifyFullReceipt(dbo interfaces.DBOverlaySimple, receiptStr string) error {
receipt, err := DecodeReceiptString(receiptStr)
if err != nil {
return err
}
//fmt.Printf("receipt - %v\n", receipt.CustomMarshalString())
err = receipt.Validate()
if err != nil {
return err
}
for i, node := range receipt.MerkleBranch {
if node.Left == nil || node.Right == nil {
return fmt.Errorf("Node %v/%v has a nil side", i, len(receipt.MerkleBranch))
}
if node.Top == nil {
return fmt.Errorf("Node %v/%v has no top", i, len(receipt.MerkleBranch))
}
}
return nil
}
func VerifyMinimalReceipt(dbo interfaces.DBOverlaySimple, receiptStr string) error {
receipt, err := DecodeReceiptString(receiptStr)
if err != nil {
return err
}
err = receipt.Validate()
if err != nil {
return err
}
for i, node := range receipt.MerkleBranch {
if node.Left == nil && node.Right == nil {
return fmt.Errorf("Node %v/%v has two nil sides", i, len(receipt.MerkleBranch))
}
if node.Left != nil && node.Right != nil {
return fmt.Errorf("Node %v/%v has two non-nil sides", i, len(receipt.MerkleBranch))
}
if node.Top != nil {
return fmt.Errorf("Node %v/%v has unnecessary top", i, len(receipt.MerkleBranch))
}
}
//...
return nil
}