forked from holochain/holochain-proto
/
action.go
1688 lines (1460 loc) · 41.2 KB
/
action.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) 2013-2017, The MetaCurrency Project (Eric Harris-Braun, Arthur Brock, et. al.)
// Use of this source code is governed by GPLv3 found in the LICENSE file
//----------------------------------------------------------------------------------------
//
package holochain
import (
"bytes"
"encoding/json"
"errors"
"fmt"
b58 "github.com/jbenet/go-base58"
ic "github.com/libp2p/go-libp2p-crypto"
peer "github.com/libp2p/go-libp2p-peer"
. "github.com/metacurrency/holochain/hash"
"io/ioutil"
"net/http"
"reflect"
"time"
)
type ArgType int8
// these constants define the argument types for actions, i.e. system functions callable
// from within nuclei
const (
HashArg = iota
StringArg
EntryArg // special arg type for entries, can be a string or a hash
IntArg
BoolArg
MapArg
ToStrArg // special arg type that converts anything to a string, used for the debug action
ArgsArg // special arg type for arguments passed to the call action
)
const (
DHTChangeOK = iota
DHTChangeUnknownHashQueuedForRetry
)
type Arg struct {
Name string
Type ArgType
Optional bool
MapType reflect.Type
value interface{}
}
type ModAgentOptions struct {
Identity string
Revocation string
}
// Action provides an abstraction for grouping all the aspects of a nucleus function, i.e.
// the initiating actions, receiving them, validation, ribosome generation etc
type Action interface {
Name() string
Do(h *Holochain) (response interface{}, err error)
Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)
Args() []Arg
}
// CommittingAction provides an abstraction for grouping actions which carry Entry data
type CommittingAction interface {
Name() string
Do(h *Holochain) (response interface{}, err error)
SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)
Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)
CheckValidationRequest(def *EntryDef) (err error)
Args() []Arg
EntryType() string
Entry() Entry
SetHeader(header *Header)
}
// ValidatingAction provides an abstraction for grouping all the actions that participate in validation loop
type ValidatingAction interface {
Name() string
Do(h *Holochain) (response interface{}, err error)
SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)
Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)
CheckValidationRequest(def *EntryDef) (err error)
Args() []Arg
}
var NonDHTAction error = errors.New("Not a DHT action")
var NonCallableAction error = errors.New("Not a callable action")
var ErrNotValidForDNAType error = errors.New("Invalid action for DNA type")
var ErrNotValidForAgentType error = errors.New("Invalid action for Agent type")
var ErrNotValidForKeyType error = errors.New("Invalid action for Key type")
var ErrNilEntryInvalid error = errors.New("nil entry invalid")
func prepareSources(sources []peer.ID) (srcs []string) {
srcs = make([]string, 0)
for _, s := range sources {
srcs = append(srcs, peer.IDB58Encode(s))
}
return
}
// ValidateAction runs the different phases of validating an action
func (h *Holochain) ValidateAction(a ValidatingAction, entryType string, pkg *Package, sources []peer.ID) (def *EntryDef, err error) {
defer func() {
if err != nil {
h.dht.dlog.Logf("%T Validation failed with: %v", a, err)
}
}()
var z *Zome
z, def, err = h.GetEntryDef(entryType)
if err != nil {
return
}
// run the action's system level validations
err = a.SysValidation(h, def, pkg, sources)
if err != nil {
h.Debugf("Sys ValidateAction(%T) err:%v\n", a, err)
return
}
if !def.IsSysEntry() {
// validation actions for application defined entry types
var vpkg *ValidationPackage
vpkg, err = MakeValidationPackage(h, pkg)
if err != nil {
return
}
// run the action's app level validations
var n Ribosome
n, err = z.MakeRibosome(h)
if err != nil {
return
}
err = n.ValidateAction(a, def, vpkg, prepareSources(sources))
if err != nil {
h.Debugf("Ribosome ValidateAction(%T) err:%v\n", a, err)
}
}
return
}
// GetValidationResponse check the validation request and builds the validation package based
// on the app's requirements
func (h *Holochain) GetValidationResponse(a ValidatingAction, hash Hash) (resp ValidateResponse, err error) {
var entry Entry
entry, resp.Type, err = h.chain.GetEntry(hash)
if err == ErrHashNotFound {
if hash.String() == h.nodeIDStr {
resp.Type = KeyEntryType
var pk []byte
pk, err = ic.MarshalPublicKey(h.agent.PubKey())
if err != nil {
return
}
resp.Entry.C = pk
err = nil
} else {
return
}
} else if err != nil {
return
} else {
resp.Entry = *(entry.(*GobEntry))
var hd *Header
hd, err = h.chain.GetEntryHeader(hash)
if err != nil {
return
}
resp.Header = *hd
}
switch resp.Type {
case DNAEntryType:
err = ErrNotValidForDNAType
return
case KeyEntryType:
// if key entry there no extra info to return in the package so do nothing
case AgentEntryType:
// if agent, the package to return is the entry-type chain
// so that sys validation can confirm this agent entry in the chain
req := PackagingReq{PkgReqChain: int64(PkgReqChainOptFull), PkgReqEntryTypes: []string{AgentEntryType}}
resp.Package, err = MakePackage(h, req)
default:
// app defined entry types
var def *EntryDef
var z *Zome
z, def, err = h.GetEntryDef(resp.Type)
if err != nil {
return
}
err = a.CheckValidationRequest(def)
if err != nil {
return
}
// get the packaging request from the app
var n Ribosome
n, err = z.MakeRibosome(h)
if err != nil {
return
}
var req PackagingReq
req, err = n.ValidatePackagingRequest(a, def)
if err != nil {
h.Debugf("Ribosome GetValidationPackage(%T) err:%v\n", a, err)
}
resp.Package, err = MakePackage(h, req)
}
return
}
// MakeActionFromMessage generates an action from an action protocol messsage
func MakeActionFromMessage(msg *Message) (a Action, err error) {
var t reflect.Type
switch msg.Type {
case APP_MESSAGE:
a = &ActionSend{}
t = reflect.TypeOf(AppMsg{})
case PUT_REQUEST:
a = &ActionPut{}
t = reflect.TypeOf(PutReq{})
case GET_REQUEST:
a = &ActionGet{}
t = reflect.TypeOf(GetReq{})
case MOD_REQUEST:
a = &ActionMod{}
t = reflect.TypeOf(ModReq{})
case DEL_REQUEST:
a = &ActionDel{}
t = reflect.TypeOf(DelReq{})
case LINK_REQUEST:
a = &ActionLink{}
t = reflect.TypeOf(LinkReq{})
case GETLINK_REQUEST:
a = &ActionGetLinks{}
t = reflect.TypeOf(LinkQuery{})
case LISTADD_REQUEST:
a = &ActionListAdd{}
t = reflect.TypeOf(ListAddReq{})
default:
err = fmt.Errorf("message type %d not in holochain-action protocol", int(msg.Type))
}
if err == nil && reflect.TypeOf(msg.Body) != t {
err = fmt.Errorf("Unexpected request body type '%T' in %s request, expecting %v", msg.Body, a.Name(), t)
}
return
}
var ErrWrongNargs = errors.New("wrong number of arguments")
func checkArgCount(args []Arg, l int) (err error) {
var min int
for _, a := range args {
if !a.Optional {
min++
}
}
if l < min || l > len(args) {
err = ErrWrongNargs
}
return
}
func argErr(typeName string, index int, arg Arg) error {
return fmt.Errorf("argument %d (%s) should be %s", index, arg.Name, typeName)
}
//------------------------------------------------------------
// Property
type ActionProperty struct {
prop string
}
func NewPropertyAction(prop string) *ActionProperty {
a := ActionProperty{prop: prop}
return &a
}
func (a *ActionProperty) Name() string {
return "property"
}
func (a *ActionProperty) Args() []Arg {
return []Arg{{Name: "name", Type: StringArg}}
}
func (a *ActionProperty) Do(h *Holochain) (response interface{}, err error) {
response, err = h.GetProperty(a.prop)
return
}
//------------------------------------------------------------
// Debug
type ActionDebug struct {
msg string
}
func NewDebugAction(msg string) *ActionDebug {
a := ActionDebug{msg: msg}
return &a
}
func (a *ActionDebug) Name() string {
return "debug"
}
func (a *ActionDebug) Args() []Arg {
return []Arg{{Name: "value", Type: ToStrArg}}
}
func (a *ActionDebug) Do(h *Holochain) (response interface{}, err error) {
h.Config.Loggers.App.Log(a.msg)
return
}
//------------------------------------------------------------
// MakeHash
type ActionMakeHash struct {
entryType string
entry Entry
}
func NewMakeHashAction(entry Entry) *ActionMakeHash {
a := ActionMakeHash{entry: entry}
return &a
}
func (a *ActionMakeHash) Name() string {
return "makeHash"
}
func (a *ActionMakeHash) Args() []Arg {
return []Arg{{Name: "entryType", Type: StringArg}, {Name: "entry", Type: EntryArg}}
}
func (a *ActionMakeHash) Do(h *Holochain) (response interface{}, err error) {
var hash Hash
hash, err = a.entry.Sum(h.hashSpec)
if err != nil {
return
}
response = hash
return
}
//------------------------------------------------------------
// GetBridges
type ActionGetBridges struct {
}
func NewGetBridgesAction(doc []byte) *ActionGetBridges {
a := ActionGetBridges{}
return &a
}
func (a *ActionGetBridges) Name() string {
return "getBridges"
}
func (a *ActionGetBridges) Args() []Arg {
return []Arg{}
}
func (a *ActionGetBridges) Do(h *Holochain) (response interface{}, err error) {
response, err = h.GetBridges()
return
}
//------------------------------------------------------------
// Sign
type ActionSign struct {
doc []byte
}
func NewSignAction(doc []byte) *ActionSign {
a := ActionSign{doc: doc}
return &a
}
func (a *ActionSign) Name() string {
return "sign"
}
func (a *ActionSign) Args() []Arg {
return []Arg{{Name: "doc", Type: StringArg}}
}
func (a *ActionSign) Do(h *Holochain) (response interface{}, err error) {
var b []byte
b, err = h.Sign(a.doc)
if err != nil {
return
}
response = b
return
}
//------------------------------------------------------------
// VerifySignature
type ActionVerifySignature struct {
signature string
data string
pubKey string
}
func NewVerifySignatureAction(signature string, data string, pubKey string) *ActionVerifySignature {
a := ActionVerifySignature{signature: signature, data: data, pubKey: pubKey}
return &a
}
func (a *ActionVerifySignature) Name() string {
return "verifySignature"
}
func (a *ActionVerifySignature) Args() []Arg {
return []Arg{{Name: "signature", Type: StringArg}, {Name: "data", Type: StringArg}, {Name: "pubKey", Type: StringArg}}
}
func (a *ActionVerifySignature) Do(h *Holochain) (response bool, err error) {
var b bool
var pubKeyIC ic.PubKey
var sig []byte
sig = b58.Decode(a.signature)
var pubKeyBytes []byte
pubKeyBytes = b58.Decode(a.pubKey)
pubKeyIC, err = ic.UnmarshalPublicKey(pubKeyBytes)
if err != nil {
return
}
b, err = h.VerifySignature(sig, a.data, pubKeyIC)
if err != nil {
return
}
response = b
return
}
//------------------------------------------------------------
// Call
type ActionCall struct {
zome string
function string
args interface{}
}
func NewCallAction(zome string, function string, args interface{}) *ActionCall {
a := ActionCall{zome: zome, function: function, args: args}
return &a
}
func (a *ActionCall) Name() string {
return "call"
}
func (a *ActionCall) Args() []Arg {
return []Arg{{Name: "zome", Type: StringArg}, {Name: "function", Type: StringArg}, {Name: "args", Type: ArgsArg}}
}
func (a *ActionCall) Do(h *Holochain) (response interface{}, err error) {
response, err = h.Call(a.zome, a.function, a.args, ZOME_EXPOSURE)
return
}
//------------------------------------------------------------
// Bridge
type ActionBridge struct {
token string
url string
zome string
function string
args interface{}
}
func NewBridgeAction(zome string, function string, args interface{}) *ActionBridge {
a := ActionBridge{zome: zome, function: function, args: args}
return &a
}
func (a *ActionBridge) Name() string {
return "call"
}
func (a *ActionBridge) Args() []Arg {
return []Arg{{Name: "app", Type: HashArg}, {Name: "zome", Type: StringArg}, {Name: "function", Type: StringArg}, {Name: "args", Type: ArgsArg}}
}
func (a *ActionBridge) Do(h *Holochain) (response interface{}, err error) {
body := bytes.NewBuffer([]byte(a.args.(string)))
var resp *http.Response
resp, err = http.Post(fmt.Sprintf("%s/bridge/%s/%s/%s", a.url, a.token, a.zome, a.function), "", body)
if err != nil {
return
}
defer resp.Body.Close()
var b []byte
b, err = ioutil.ReadAll(resp.Body)
response = string(b)
return
}
//------------------------------------------------------------
// Send
type Callback struct {
Function string
ID string
zomeType string
}
type SendOptions struct {
Callback *Callback
Timeout int
}
type ActionSend struct {
to peer.ID
msg AppMsg
options *SendOptions
}
func NewSendAction(to peer.ID, msg AppMsg) *ActionSend {
a := ActionSend{to: to, msg: msg}
return &a
}
func (a *ActionSend) Name() string {
return "send"
}
func (a *ActionSend) Args() []Arg {
return []Arg{{Name: "to", Type: HashArg}, {Name: "msg", Type: MapArg}, {Name: "options", Type: MapArg, MapType: reflect.TypeOf(SendOptions{}), Optional: true}}
}
func (a *ActionSend) Do(h *Holochain) (response interface{}, err error) {
var r interface{}
var timeout time.Duration
if a.options != nil {
timeout = time.Duration(a.options.Timeout) * time.Millisecond
}
msg := h.node.NewMessage(APP_MESSAGE, a.msg)
if a.options != nil && a.options.Callback != nil {
err = h.SendAsync(ActionProtocol, a.to, msg, a.options.Callback, timeout)
} else {
r, err = h.Send(h.node.ctx, ActionProtocol, a.to, msg, timeout)
if err == nil {
response = r.(AppMsg).Body
}
}
return
}
func (a *ActionSend) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error) {
t := msg.Body.(AppMsg)
var r Ribosome
r, _, err = dht.h.MakeRibosome(t.ZomeType)
if err != nil {
return
}
rsp := AppMsg{ZomeType: t.ZomeType}
rsp.Body, err = r.Receive(peer.IDB58Encode(msg.From), t.Body)
if err == nil {
response = rsp
}
return
}
//------------------------------------------------------------
// Query
type ActionQuery struct {
options *QueryOptions
}
func NewQueryAction(options *QueryOptions) *ActionQuery {
a := ActionQuery{options: options}
return &a
}
func (a *ActionQuery) Name() string {
return "query"
}
func (a *ActionQuery) Args() []Arg {
return []Arg{{Name: "options", Type: MapArg, MapType: reflect.TypeOf(QueryOptions{}), Optional: true}}
}
func (a *ActionQuery) Do(h *Holochain) (response interface{}, err error) {
response, err = h.Query(a.options)
return
}
//------------------------------------------------------------
// Get
type ActionGet struct {
req GetReq
options *GetOptions
}
func NewGetAction(req GetReq, options *GetOptions) *ActionGet {
a := ActionGet{req: req, options: options}
return &a
}
func (a *ActionGet) Name() string {
return "get"
}
func (a *ActionGet) Args() []Arg {
return []Arg{{Name: "hash", Type: HashArg}, {Name: "options", Type: MapArg, MapType: reflect.TypeOf(GetOptions{}), Optional: true}}
}
func (a *ActionGet) Do(h *Holochain) (response interface{}, err error) {
if a.options.Local {
var entry Entry
var entryType string
entry, entryType, err = h.chain.GetEntry(a.req.H)
if err != nil {
return
}
resp := GetResp{Entry: *entry.(*GobEntry)}
mask := a.options.GetMask
if (mask & GetMaskEntryType) != 0 {
resp.EntryType = entryType
}
if (mask & GetMaskEntry) != 0 {
resp.Entry = *entry.(*GobEntry)
}
response = resp
return
}
rsp, err := h.dht.Query(a.req.H, GET_REQUEST, a.req)
if err != nil {
// follow the modified hash
if a.req.StatusMask == StatusDefault && err == ErrHashModified {
var hash Hash
hash, err = NewHash(rsp.(GetResp).FollowHash)
if err != nil {
return
}
if hash.String() == a.req.H.String() {
err = errors.New("FollowHash loop detected")
return
}
req := GetReq{H: hash, StatusMask: StatusDefault, GetMask: a.options.GetMask}
modResp, err := NewGetAction(req, a.options).Do(h)
if err == nil {
response = modResp
}
}
return
}
switch t := rsp.(type) {
case GetResp:
response = t
default:
err = fmt.Errorf("expected GetResp response from GET_REQUEST, got: %T", t)
return
}
return
}
func (a *ActionGet) SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error) {
return
}
func (a *ActionGet) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error) {
var entryData []byte
//var status int
req := msg.Body.(GetReq)
mask := req.GetMask
if mask == GetMaskDefault {
mask = GetMaskEntry
}
resp := GetResp{}
var entryType string
// always get the entry type despite what the mas says because we need it for the switch below.
entryData, entryType, resp.Sources, _, err = dht.get(req.H, req.StatusMask, req.GetMask|GetMaskEntryType)
if (mask & GetMaskEntryType) != 0 {
resp.EntryType = entryType
}
if err == nil {
if (mask & GetMaskEntry) != 0 {
switch entryType {
case DNAEntryType:
// TODO: make this add the requester to the blockedlist rather than panicing, see ticket #421
err = errors.New("nobody should actually get the DNA!")
return
case KeyEntryType:
resp.Entry = GobEntry{C: entryData}
default:
var e GobEntry
err = e.Unmarshal(entryData)
if err != nil {
return
}
resp.Entry = e
}
}
} else {
if err == ErrHashModified {
resp.FollowHash = string(entryData)
} else if err == ErrHashNotFound {
closest := dht.h.node.betterPeersForHash(&req.H, msg.From, CloserPeerCount)
if len(closest) > 0 {
err = nil
resp := CloserPeersResp{}
resp.CloserPeers = dht.h.node.peers2PeerInfos(closest)
response = resp
return
}
}
}
response = resp
return
}
// doCommit adds an entry to the local chain after validating the action it's part of
func (h *Holochain) doCommit(a CommittingAction, change *StatusChange) (d *EntryDef, header *Header, entryHash Hash, err error) {
entryType := a.EntryType()
entry := a.Entry()
var l int
var hash Hash
var added bool
// retry loop incase someone sneaks a new commit in between prepareHeader and addEntry
for !added {
h.chain.lk.RLock()
count := len(h.chain.Headers)
l, hash, header, err = h.chain.prepareHeader(time.Now(), entryType, entry, h.agent.PrivKey(), change)
h.chain.lk.RUnlock()
if err != nil {
return
}
a.SetHeader(header)
d, err = h.ValidateAction(a, entryType, nil, []peer.ID{h.nodeID})
if err != nil {
return
}
h.chain.lk.Lock()
if count == len(h.chain.Headers) {
err = h.chain.addEntry(l, hash, header, entry)
if err == nil {
added = true
}
}
h.chain.lk.Unlock()
if err != nil {
return
}
}
entryHash = header.EntryLink
return
}
//------------------------------------------------------------
// Commit
type ActionCommit struct {
entryType string
entry Entry
header *Header
}
func NewCommitAction(entryType string, entry Entry) *ActionCommit {
a := ActionCommit{entryType: entryType, entry: entry}
return &a
}
func (a *ActionCommit) Entry() Entry {
return a.entry
}
func (a *ActionCommit) EntryType() string {
return a.entryType
}
func (a *ActionCommit) Name() string {
return "commit"
}
func (a *ActionCommit) Args() []Arg {
return []Arg{{Name: "entryType", Type: StringArg}, {Name: "entry", Type: EntryArg}}
}
func (a *ActionCommit) SetHeader(header *Header) {
a.header = header
}
func (a *ActionCommit) Do(h *Holochain) (response interface{}, err error) {
var d *EntryDef
var entryHash Hash
// var header *Header
d, _, entryHash, err = h.doCommit(a, nil)
if err != nil {
return
}
if d.DataFormat == DataFormatLinks {
// if this is a Link entry we have to send the DHT Link message
var le LinksEntry
entryStr := a.entry.Content().(string)
err = json.Unmarshal([]byte(entryStr), &le)
if err != nil {
return
}
bases := make(map[string]bool)
for _, l := range le.Links {
_, exists := bases[l.Base]
if !exists {
b, _ := NewHash(l.Base)
h.dht.Change(b, LINK_REQUEST, LinkReq{Base: b, Links: entryHash})
//TODO errors from the send??
bases[l.Base] = true
}
}
} else if d.Sharing == Public {
// otherwise we check to see if it's a public entry and if so send the DHT put message
err = h.dht.Change(entryHash, PUT_REQUEST, PutReq{H: entryHash})
if err == ErrEmptyRoutingTable {
// will still have committed locally and can gossip later
err = nil
}
}
response = entryHash
return
}
// sysValidateEntry does system level validation for adding an entry (put or commit)
// It checks that entry is not nil, and that it conforms to the entry schema in the definition
// if it's a Links entry that the contents are correctly structured
// if it's a new agent entry, that identity matches the defined identity structure
// if it's a key that the structure is actually a public key
func sysValidateEntry(h *Holochain, def *EntryDef, entry Entry, pkg *Package) (err error) {
switch def.Name {
case DNAEntryType:
err = ErrNotValidForDNAType
return
case KeyEntryType:
pk, ok := entry.Content().([]byte)
if !ok || len(pk) != 36 {
err = ValidationFailedErr
return
} else {
_, err = ic.UnmarshalPublicKey(pk)
if err != nil {
err = ValidationFailedErr
return err
}
}
case AgentEntryType:
ae, ok := entry.Content().(AgentEntry)
if !ok {
err = ValidationFailedErr
return
}
// check that the public key is unmarshalable
_, err = ic.UnmarshalPublicKey(ae.PublicKey)
if err != nil {
err = ValidationFailedErr
return err
}
// if there's a revocation, confirm that has a reasonable format
if ae.Revocation != nil {
revocation := &SelfRevocation{}
err := revocation.Unmarshal(ae.Revocation)
if err != nil {
err = ValidationFailedErr
return err
}
}
// TODO check anything in the package
}
if entry == nil {
err = ErrNilEntryInvalid
return
}
// see if there is a schema validator for the entry type and validate it if so
if def.validator != nil {
var input interface{}
if def.DataFormat == DataFormatJSON {
if err = json.Unmarshal([]byte(entry.Content().(string)), &input); err != nil {
return
}
} else {
input = entry
}
h.Debugf("Validating %v against schema", input)
if err = def.validator.Validate(input); err != nil {
return
}
} else if def.DataFormat == DataFormatLinks {
// Perform base validation on links entries, i.e. that all items exist and are of the right types
// so first unmarshall the json, and then check that the hashes are real.
var l struct{ Links []map[string]string }
err = json.Unmarshal([]byte(entry.Content().(string)), &l)
if err != nil {
err = fmt.Errorf("invalid links entry, invalid json: %v", err)
return
}
if len(l.Links) == 0 {
err = errors.New("invalid links entry: you must specify at least one link")
return
}
for _, link := range l.Links {
h, ok := link["Base"]
if !ok {
err = errors.New("invalid links entry: missing Base")
return
}
if _, err = NewHash(h); err != nil {
err = fmt.Errorf("invalid links entry: Base %v", err)
return
}
h, ok = link["Link"]
if !ok {
err = errors.New("invalid links entry: missing Link")
return
}
if _, err = NewHash(h); err != nil {
err = fmt.Errorf("invalid links entry: Link %v", err)
return
}
_, ok = link["Tag"]
if !ok {
err = errors.New("invalid links entry: missing Tag")
return
}
}
}
return
}
func (a *ActionCommit) SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error) {
err = sysValidateEntry(h, def, a.entry, pkg)
return
}
func (a *ActionCommit) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error) {
err = NonDHTAction
return
}
func (a *ActionCommit) CheckValidationRequest(def *EntryDef) (err error) {
return
}
//------------------------------------------------------------
// Put
type ActionPut struct {
entryType string
entry Entry
header *Header
}
func NewPutAction(entryType string, entry Entry, header *Header) *ActionPut {
a := ActionPut{entryType: entryType, entry: entry, header: header}
return &a
}
func (a *ActionPut) Name() string {
return "put"
}
func (a *ActionPut) Args() []Arg {
return nil
}
func (a *ActionPut) Do(h *Holochain) (response interface{}, err error) {
err = NonCallableAction
return
}