-
Notifications
You must be signed in to change notification settings - Fork 1
/
gitbe.go
2593 lines (2277 loc) · 67.8 KB
/
gitbe.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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2017-2018 The Decred developers
// Copyright (c) 2018-2019 The Hc developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package gitbe
import (
"bytes"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/HcashOrg/hcd/chaincfg"
"github.com/HcashOrg/hctime/api/v1"
"github.com/HcashOrg/hctime/merkle"
"github.com/HcashOrg/hcAutonomy/HcashOrgplugin"
pd "github.com/HcashOrg/hcAutonomy/hcAutonomyd/api/v1"
"github.com/HcashOrg/hcAutonomy/hcAutonomyd/api/v1/identity"
"github.com/HcashOrg/hcAutonomy/hcAutonomyd/api/v1/mime"
"github.com/HcashOrg/hcAutonomy/hcAutonomyd/backend"
"github.com/HcashOrg/hcAutonomy/util"
filesystem "github.com/otiai10/copy"
"github.com/robfig/cron"
"github.com/subosito/norma"
)
const (
// LockDuration is the maximum lock time duration allowed. 15 seconds
// is ~3x of anchoring without internet delay.
LockDuration = 15 * time.Second
// defaultUnvettedPath is the landing zone for unvetted content.
defaultUnvettedPath = "unvetted"
// defaultVettedPath is the publicly visible git vetted record repo.
defaultVettedPath = "vetted"
// defaultJournalsPath is the path where data is journaled and/or
// cached.
defaultJournalsPath = "journals" // XXX it looks like this belongs in plugins
// defaultRecordMetadataFilename is the filename of record record.
defaultRecordMetadataFilename = "recordmetadata.json"
// defaultMDFilenameSuffix is the filename suffic for the user provided
// metadata record. The metadata record shall be string encoded.
defaultMDFilenameSuffix = ".metadata.txt"
// defaultAuditTrailFile is the filename where a human readable audit
// trail is kept.
defaultAuditTrailFile = "anchor_audit_trail.txt"
// defaultAnchorsDirectory is the directory where anchors are stored.
// They are indexed by TX.
defaultAnchorsDirectory = "anchors"
// defaultPayloadDir is the default path to store a record payload.
defaultPayloadDir = "payload"
// anchorSchedule determines how often we anchor the vetted repo.
// Seconds Minutes Hours Days Months DayOfWeek
anchorSchedule = "20 * * * * *" // At 58 minutes every hour
// expectedTestTX is a fake TX used by unit tests.
expectedTestTX = "TESTTX"
// markerAnchor is used in commit messages to determine
// where an anchor has been committed. This value is
// parsed and therefore must be a const.
markerAnchor = "Anchor"
// markerAnchorConfirmation is used in commit messages to determine
// where an anchor confirmation has been committed. This value is
// parsed and therefore must be a const.
markerAnchorConfirmation = "Anchor confirmation"
)
var (
_ backend.Backend = (*gitBackEnd)(nil)
defaultRepoConfig = map[string]string{
// This prevents git from converting CRLF when committing and checking
// out files, which helps when running on Windows.
"core.autocrlf": "false",
"user.name": "HcAutonomy",
"user.email": "pool@h.cash",
}
errNothingToDo = errors.New("nothing to do")
)
// file is an internal representation of a file that resides in memory.
type file struct {
name string // Basename of the file
digest []byte // SHA256 of payload
payload []byte // Actual file payload
}
// gitBackEnd is a git based backend context that satisfies the backend
// interface.
type gitBackEnd struct {
sync.Mutex // Global lock
cron *cron.Cron // Scheduler for periodic tasks
activeNetParams *chaincfg.Params // indicator if we are running on testnet
journal *Journal // Journal context
shutdown bool // Backend is shutdown
root string // Root directory
unvetted string // Unvettend content
vetted string // Vetted, public, visible content
journals string // Journals/cache
hctimeHost string // hctimed directory
gitPath string // Path to git
gitTrace bool // Enable git tracing
test bool // Set during UT
exit chan struct{} // Close channel
checkAnchor chan struct{} // Work notification
plugins []backend.Plugin // Plugins
// The following items are used for testing only
testAnchors map[string]bool // [digest]anchored
}
func pijoin(elements ...string) string {
return filepath.Join(elements...)
}
func join(elements ...string) string {
panic(filepath.Join(elements...))
}
// getLatest returns the latest version as a string.
// This function must be called with the lock held.
func getLatest(dir string) (string, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return "", backend.ErrRecordNotFound
}
if len(files) == 0 {
return "", backend.ErrRecordNotFound
}
// We expect only numeric filenames
versions := make([]int, 0, len(files))
for _, v := range files {
u, err := strconv.ParseInt(v.Name(), 10, 64)
if err != nil {
return "", err
}
versions = append(versions, int(u))
}
sort.Ints(versions)
return strconv.FormatInt(int64(versions[len(versions)-1]), 10), nil
}
// getNext looks at the current latest version and increments the count by one.
// This function must be called with the lock held.
func getNext(dir string) (string, string, error) {
v, err := getLatest(dir)
if err != nil {
return "", "", backend.ErrRecordNotFound
}
vv, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return "", "", err
}
vv++
// Sanity
if vv <= 0 {
return "", "", fmt.Errorf("invalid version")
}
return v, strconv.FormatInt(vv, 10), nil
}
// _joinLatest joins the provided path elements and adds the latest version of
// the provided directory.
func _joinLatest(elements ...string) (string, error) {
dir := pijoin(elements...)
v, err := getLatest(dir)
if err != nil {
return "", err
}
return pijoin(dir, v), nil
}
// getPathToVersion returns the directory path to the specified record version
// if the version isn't provided, the latest version is returned by default
func getPathToVersion(path, id, version string) string {
if version == "" {
return joinLatest(path, id)
} else {
return pijoin(path, id, version)
}
}
// joinLatest joins the provided path elements and adds the latest version of
// the provided directory. This function panic when it errors out, this is by
// design in order to find all incorrect invocations.
func joinLatest(elements ...string) string {
path, err := _joinLatest(elements...)
if err != nil {
panic(err)
}
return path
}
// extendSHA1 appends 0 to make a SHA1 the size of a SHA256 digest.
func extendSHA1(d []byte) []byte {
if len(d) != sha1.Size {
panic("invalid sha1 length")
}
digest := make([]byte, sha256.Size)
copy(digest, d)
return digest
}
// unextendSHA1ToSha256 removes 0 to make a SHA256 the size of a SHA1 digest.
func unextendSHA256(d []byte) []byte {
if len(d) != sha256.Size {
panic("invalid sha256 length")
}
// make sure this was an extended digest
for _, x := range d[sha1.Size:] {
if x != 0 {
panic("invalid extended sha256")
}
}
digest := make([]byte, sha1.Size)
copy(digest, d)
return digest
}
// extendSHA1FromString takes a string and ensures it is a digest and then
// extends it using extendSHA1. It returns a string representation of the
// digest.
func extendSHA1FromString(s string) (string, error) {
ds, err := hex.DecodeString(s)
if err != nil {
return "", fmt.Errorf("not hex: %v", s)
}
d := extendSHA1(ds)
return hex.EncodeToString(d), nil
}
// verifyContent verifies that all provided backend.MetadataStream and
// backend.File are sane and returns a cooked array of the files.
func verifyContent(metadata []backend.MetadataStream, files []backend.File, filesDel []string) ([]file, error) {
// Make sure all metadata is within maxima.
for _, v := range metadata {
if v.ID > pd.MetadataStreamsMax-1 {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusInvalidMDID,
ErrorContext: []string{
strconv.FormatUint(v.ID, 10),
},
}
}
}
for i := range metadata {
for j := range metadata {
// Skip self and non duplicates.
if i == j || metadata[i].ID != metadata[j].ID {
continue
}
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusDuplicateMDID,
ErrorContext: []string{
strconv.FormatUint(metadata[i].ID, 10),
},
}
}
}
// Prevent paths
for i := range files {
if filepath.Base(files[i].Name) != files[i].Name {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusInvalidFilename,
ErrorContext: []string{
files[i].Name,
},
}
}
}
for _, v := range filesDel {
if filepath.Base(v) != v {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusInvalidFilename,
ErrorContext: []string{
v,
},
}
}
}
// Now check files
if len(files) == 0 {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusEmpty,
}
}
// Prevent bad filenames and duplicate filenames
for i := range files {
for j := range files {
if i == j {
continue
}
if files[i].Name == files[j].Name {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusDuplicateFilename,
ErrorContext: []string{
files[i].Name,
},
}
}
}
// Check against filesDel
for _, v := range filesDel {
if files[i].Name == v {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusDuplicateFilename,
ErrorContext: []string{
files[i].Name,
},
}
}
}
}
fa := make([]file, 0, len(files))
for i := range files {
if norma.Sanitize(files[i].Name) != files[i].Name {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusInvalidFilename,
ErrorContext: []string{
files[i].Name,
},
}
}
// Validate digest
d, ok := util.ConvertDigest(files[i].Digest)
if !ok {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusInvalidFileDigest,
ErrorContext: []string{
files[i].Name,
},
}
}
// Setup cooked file.
f := file{
name: files[i].Name,
}
// Decode base64 payload
var err error
f.payload, err = base64.StdEncoding.DecodeString(files[i].Payload)
if err != nil {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusInvalidBase64,
ErrorContext: []string{
files[i].Name,
},
}
}
// Calculate payload digest
dp := util.Digest(f.payload)
if !bytes.Equal(d[:], dp) {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusInvalidFileDigest,
ErrorContext: []string{
files[i].Name,
},
}
}
f.digest = dp
// Verify MIME
detectedMIMEType := mime.DetectMimeType(f.payload)
if detectedMIMEType != files[i].MIME {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusInvalidMIMEType,
ErrorContext: []string{
files[i].Name,
detectedMIMEType,
},
}
}
if !mime.MimeValid(files[i].MIME) {
return nil, backend.ContentVerificationError{
ErrorCode: pd.ErrorStatusUnsupportedMIMEType,
ErrorContext: []string{
files[i].Name,
files[i].MIME,
},
}
}
fa = append(fa, f)
}
return fa, nil
}
// loadRecord loads an entire record of disk. It returns an array of
// backend.File that is completely filled out.
//
// This function must be called with the lock held.
func loadRecord(path, id, version string) ([]backend.File, error) {
pathToVersion := getPathToVersion(path, id, version)
// Get dir.
recordDir := pijoin(pathToVersion, defaultPayloadDir)
files, err := ioutil.ReadDir(recordDir)
if err != nil {
return nil, err
}
bf := make([]backend.File, 0, len(files))
// Load all files
for _, file := range files {
fn := pijoin(recordDir, file.Name())
if file.IsDir() {
return nil, fmt.Errorf("record corrupt: %v", path)
}
f := backend.File{Name: file.Name()}
f.MIME, f.Digest, f.Payload, err = util.LoadFile(fn)
if err != nil {
return nil, err
}
bf = append(bf, f)
}
return bf, nil
}
// mdFilename generates the proper filename for a specified repo + proposal and
// metadata stream.
func mdFilename(path, id string, mdID int) string {
return pijoin(joinLatest(path, id),
strconv.FormatUint(uint64(mdID), 10)+defaultMDFilenameSuffix)
}
// loadMDStreams loads all streams of disk. It returns an array of
// backend.MetadataStream that is completely filled out.
//
// This function must be called with the lock held.
func loadMDStreams(path, id, version string) ([]backend.MetadataStream, error) {
pathToVersion := getPathToVersion(path, id, version)
files, err := ioutil.ReadDir(pathToVersion)
if err != nil {
return nil, err
}
ms := make([]backend.MetadataStream, 0, len(files))
for _, v := range files {
// Skip irrelevant files
if !strings.HasSuffix(v.Name(), defaultMDFilenameSuffix) {
continue
}
// Fish out metadata stream ID from filename
ids := strings.TrimSuffix(v.Name(), defaultMDFilenameSuffix)
mdid, err := strconv.ParseUint(ids, 10, 64)
if err != nil {
return nil, err
}
// Load metadata stream
fn := pijoin(pathToVersion, v.Name())
md, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}
ms = append(ms, backend.MetadataStream{
ID: mdid,
Payload: string(md),
})
}
return ms, nil
}
// loadMD loads a RecordMetadata from the provided path/id. This may
// be unvetted/id or vetted/id.
//
// This function should be called with the lock held.
func loadMD(path, id, version string) (*backend.RecordMetadata, error) {
pathToVersion := getPathToVersion(path, id, version)
filename := pijoin(pathToVersion,
defaultRecordMetadataFilename)
f, err := os.Open(filename)
if err != nil {
if os.IsNotExist(err) {
err = backend.ErrRecordNotFound
}
return nil, err
}
defer f.Close()
var brm backend.RecordMetadata
decoder := json.NewDecoder(f)
if err = decoder.Decode(&brm); err != nil {
return nil, err
}
return &brm, nil
}
// createMD stores a RecordMetadata to the provided path/id. This may be
// unvetted/id or vetted/id.
//
// This function should be called with the lock held.
func createMD(path, id string, status backend.MDStatusT, iteration uint64, hashes []*[sha256.Size]byte) (*backend.RecordMetadata, error) {
// Create record metadata
m := *merkle.Root(hashes)
brm := backend.RecordMetadata{
Version: backend.VersionRecordMD,
Iteration: iteration,
Status: status,
Merkle: hex.EncodeToString(m[:]),
Timestamp: time.Now().Unix(),
Token: id,
}
err := updateMD(path, id, &brm)
if err != nil {
return nil, err
}
return &brm, nil
}
// updateMD updates the RecordMetadata status to the provided path/id.
//
// This function should be called with the lock held.
func updateMD(path, id string, brm *backend.RecordMetadata) error {
// Store metadata record.
filename := pijoin(joinLatest(path, id), defaultRecordMetadataFilename)
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
return json.NewEncoder(f).Encode(*brm)
}
// commitMD commits the MD into a git repo.
//
// This function should be called with the lock held.
func (g *gitBackEnd) commitMD(path, id, msg string) error {
// git add id/brm.json
filename := pijoin(joinLatest(path, id),
defaultRecordMetadataFilename)
err := g.gitAdd(path, filename)
if err != nil {
return err
}
// git commit -m "message"
return g.gitCommit(path, "Update record status "+id+" "+msg)
}
// deltaCommits returns sha1 extended digests and one line commit messages to
// the caller. If lastAnchor is empty then the range is from the dawn of time
// until now. If lastAnchor is a valid hash the range is from lastAnchor up
// until no.
//
// This function should be called with the lock held.
func (g *gitBackEnd) deltaCommits(path string, lastAnchor []byte) ([]*[sha256.Size]byte, []string, []string, error) {
// Sanity
if !(len(lastAnchor) == 0 || len(lastAnchor) == sha256.Size) {
return nil, nil, nil, fmt.Errorf("invalid digest size")
}
// Minimal git arguments
args := []string{"log", "--pretty=oneline"}
// Determine digest range
latestCommit, err := g.gitLastDigest(path)
if err != nil {
return nil, nil, nil, err
}
if len(lastAnchor) != 0 {
// git log lastAnchor..latestCommit --pretty=oneline
sha1LastAnchor := unextendSHA256(lastAnchor)
if bytes.Equal(sha1LastAnchor, latestCommit) {
return nil, nil, nil, errNothingToDo
}
args = append(args, hex.EncodeToString(sha1LastAnchor)+".."+
hex.EncodeToString(latestCommit))
}
// Execute git
out, err := g.git(path, args...)
if err != nil {
return nil, nil, nil, err
}
if len(out) == 0 {
return nil, nil, nil, fmt.Errorf("invalid git output")
}
// Generate return data
digests := make([]*[sha256.Size]byte, 0, len(out))
commitMessages := make([]string, 0, len(out))
for _, line := range out {
// Returned data is "<digest> <commit message>"
ds := strings.SplitN(line, " ", 2)
if len(ds) == 0 {
return nil, nil, nil, fmt.Errorf("invalid log")
}
// Ignore anchor confirmation commits
if regexAnchorConfirmation.MatchString(ds[1]) {
continue
}
// Validate returned digest
sha1Digest, err := hex.DecodeString(ds[0])
if err != nil {
return nil, nil, nil, err
}
if len(sha1Digest) != sha1.Size {
return nil, nil, nil, fmt.Errorf("invalid sha1 size")
}
sha256DigestB := extendSHA1(sha1Digest)
var sha256Digest [sha256.Size]byte
copy(sha256Digest[:], sha256DigestB)
// Fill out return values
digests = append(digests, &sha256Digest)
commitMessages = append(commitMessages, ds[1])
}
if len(digests) == 0 {
return nil, nil, nil, errNothingToDo
}
return digests, commitMessages, out, nil
}
// anchor takes a slice of commit digests and anchors them in hctime.
//
// This function is being clever with the anchors. It sends two values to
// hctime. We anchor the merkle root, and we *also* anchor all
// individual commit hashes. We do the last bit in order to be able to
// externally validate that a commit hash made it into the time stamp. If we
// don't do that we'd have to create a tool to verify individual hashes for the
// truly curious. This is essentially free because hctime compresses all
// digests into a single merkle root.
//
// This function should be called with the lock held.
// TODO: the physical write to hctime needs to come out of the lock.
func (g *gitBackEnd) anchor(digests []*[sha256.Size]byte) error {
// Anchor all digests
if g.test {
// We always append the anchorKey as the last element
x := len(digests) - 1
g.testAnchors[hex.EncodeToString(digests[x][:])] = false
return nil
}
return util.Timestamp(g.hctimeHost, digests)
}
// appendAuditTrail adds a record to the audit trail.
func (g *gitBackEnd) appendAuditTrail(path string, ts int64, merkle [sha256.Size]byte, lines []string) error {
f, err := os.OpenFile(pijoin(path, defaultAuditTrailFile),
os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return err
}
defer f.Close()
fmt.Fprintf(f, "%v: --- Audit Trail Record %x ---\n", ts, merkle)
for _, line := range lines {
fmt.Fprintf(f, "%v: %v\n", ts, strings.Trim(line, " \t\n"))
}
return nil
}
// anchorRepo drops an anchor for an individual repo.
// It prints the basename during its actions.
//
// This function should be called with the lock held.
func (g *gitBackEnd) anchorRepo(path string) (*[sha256.Size]byte, error) {
// Make sure we have a repo we understand
repo := filepath.Base(path)
// Fsck
log.Infof("Running git fsck on %v repository", repo)
err := g.gitCheckout(path, "master")
if err != nil {
return nil, fmt.Errorf("anchor checkout master %v: %v", repo,
err)
}
_, err = g.gitFsck(path)
if err != nil {
return nil, fmt.Errorf("anchor fsck master %v: %v", repo, err)
}
// Check for unanchored commits
last, err := g.readLastAnchorRecord()
if err != nil {
return nil, fmt.Errorf("could not find last %v digest: %v", repo,
err)
}
// Fill out unvetted digests
digests, messages, _, err := g.deltaCommits(path, last.Last)
if err != nil {
if err == errNothingToDo {
return nil, err
}
return nil, fmt.Errorf("could not determine delta %v: %v",
repo, err)
}
if len(digests) != len(messages) {
// Really can't happen
return nil, fmt.Errorf("invalid digests(%v)/messages(%v) count",
len(digests), len(messages))
}
// Create commit message BEFORE calling anchor. anchor calls
// merkle.Root which in turn sorts the digests and that is fine but not
// what we want to display to the user.
commitMessage := ""
auditLines := make([]string, 0, len(digests))
for k, digest := range digests {
line := fmt.Sprintf("%x %v\n", *digest, messages[k])
commitMessage += line
auditLines = append(auditLines, line)
}
// Create anchor record early for the same reason.
anchorRecord, anchorKey, err := newAnchorRecord(AnchorUnverified,
digests, messages)
if err != nil {
return nil, fmt.Errorf("newAnchorRecord: %v", err)
}
// Append MerkleRoot to digests. We have to do this since this is
// hcAutonomy's lookup key but hctime will likely return a different
// merkle. hctime returns a different merkle when there are
// additional digests in the set.
digests = append(digests, anchorKey)
// Anchor commits
log.Infof("Anchoring %v repository", repo)
err = g.anchor(digests)
if err != nil {
return nil, fmt.Errorf("anchor: %v", err)
}
// Prefix commitMessage with merkle root
commitMessage = fmt.Sprintf("%v %x\n\n%v", markerAnchor, *anchorKey,
commitMessage)
// Commit merkle root as an anchor and append included commits to audit
// trail
err = g.appendAuditTrail(path, anchorRecord.Time, *anchorKey,
auditLines)
if err != nil {
return nil, fmt.Errorf("could not append to audit trail: %v",
err)
}
err = g.gitAdd(path, defaultAuditTrailFile)
if err != nil {
return nil, fmt.Errorf("gitAdd: %v", err)
}
err = g.gitCommit(path, commitMessage)
if err != nil {
return nil, fmt.Errorf("gitCommit: %v", err)
}
return anchorKey, nil
}
// anchor verifies if there are new commits in all repos and if that is the
// case it drops and anchor in hctime for each of them.
func (g *gitBackEnd) anchorAllRepos() error {
log.Infof("Dropping anchor")
// Lock filesystem
g.Lock()
defer g.Unlock()
if g.shutdown {
return fmt.Errorf("anchorAllRepos: %v", backend.ErrShutdown)
}
// Anchor vetted
log.Infof("Anchoring %v", g.vetted)
mr, err := g.anchorRepo(g.vetted)
if err != nil {
if err == errNothingToDo {
log.Infof("Anchoring %v: nothing to do", g.vetted)
return nil
}
return fmt.Errorf("anchor repo %v: %v", g.vetted, err)
}
// Sync vetted to unvetted
// git pull --ff-only --rebase
err = g.gitPull(g.unvetted, true)
if err != nil {
return err
}
log.Infof("Dropping anchor complete: %x", *mr)
return nil
}
// periodicAnchorChecker must be run as a go routine. It sits around and
// periodically checks if there is work to do. It can also be tickled by
// messaging checkAnchor.
func (g *gitBackEnd) periodicAnchorChecker() {
log.Infof("Periodic anchor checker launched")
defer log.Infof("Periodic anchor checker exited")
for {
select {
case <-g.exit:
return
case <-g.checkAnchor:
case <-time.After(5 * time.Minute):
}
if g.shutdown {
return
}
// Do lengthy work, this may have to be its own go routine
err := g.anchorChecker()
if err != nil {
// Not much we can do past logging
log.Errorf("periodicAnchorChecker: %v", err)
}
}
}
// anchorChecker does the work for periodicAnchorChecker. It lives in its own
// function for testing purposes.
func (g *gitBackEnd) anchorChecker() error {
ua, err := g.readUnconfirmedAnchorRecord()
if err != nil {
return fmt.Errorf("anchorChecker read: %v", err)
}
// Check for work
if len(ua.Merkles) == 0 {
return nil
}
// Do one verify at a time for now
vrs := make([]v1.VerifyDigest, 0, len(ua.Merkles))
for _, u := range ua.Merkles {
digest := hex.EncodeToString(u)
vr, err := g.verifyAnchor(digest)
if err != nil {
log.Errorf("anchorChecker verify: %v", err)
continue
}
vrs = append(vrs, *vr)
}
err = g.afterAnchorVerify(vrs)
if err != nil {
return fmt.Errorf("afterAnchorVerify: %v", err)
}
return nil
}
// afterAnchorVerify completes the anchor verification process. It is a
// separate function in order not having to futz with locks.
func (g *gitBackEnd) afterAnchorVerify(vrs []v1.VerifyDigest) error {
// Lock filesystem
g.Lock()
defer g.Unlock()
var err error
if len(vrs) != 0 {
// git checkout master
err = g.gitCheckout(g.vetted, "master")
if err != nil {
return err
}
}
// Handle verified vrs
for _, vr := range vrs {
if vr.ChainInformation.ChainTimestamp == 0 {
// hctime returns 0 when there are not enough
// confirmations yet.
return fmt.Errorf("not enough confirmations: %v",
vr.Digest)
}
// Use the audit trail as the file to be committed
mr, ok := util.ConvertDigest(vr.Digest)
if !ok {
return fmt.Errorf("invalid digest: %v", vr.Digest)
}
txLine := fmt.Sprintf("%v anchored in TX %v\n", vr.Digest,
vr.ChainInformation.Transaction)
err = g.appendAuditTrail(g.vetted,
vr.ChainInformation.ChainTimestamp, mr, []string{txLine})
if err != nil {
return err
}
err = g.gitAdd(g.vetted, defaultAuditTrailFile)
if err != nil {
return err
}
// Store hctime information.
// In vetted store the ChainInformation as a json object in
// directory anchor.
// In Vetted in the record directory add a file called anchor
// that points to the TX id.
anchorDir := pijoin(g.vetted, defaultAnchorsDirectory)
err = os.MkdirAll(anchorDir, 0774)
if err != nil {
return err
}
ar, err := json.Marshal(vr.ChainInformation)
if err != nil {
return err
}
err = ioutil.WriteFile(pijoin(anchorDir, vr.Digest),
ar, 0664)
if err != nil {
return err
}
err = g.gitAdd(g.vetted,
pijoin(defaultAnchorsDirectory, vr.Digest))
if err != nil {
return err
}
// git commit anchor confirmation
commitMsg := markerAnchorConfirmation + " " + vr.Digest + "\n\n" + txLine
err = g.gitCommit(g.vetted, commitMsg)
if err != nil {
return err
}
// Mark test anchors as confirmed by hctime
if g.test {
g.testAnchors[vr.Digest] = true
}
}
if len(vrs) != 0 {
// git checkout master unvetted
err = g.gitCheckout(g.unvetted, "master")
if err != nil {
return err
}
// git pull --ff-only --rebase
err = g.gitPull(g.unvetted, true)
if err != nil {
return err
}
}
return nil
}
// anchorAllReposCronJob is the cron job that anchors all repos at a preset time.
func (g *gitBackEnd) anchorAllReposCronJob() {
err := g.anchorAllRepos()
if err != nil {
log.Errorf("%v", err)
}