This repository has been archived by the owner on Sep 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathaction.go
388 lines (350 loc) · 10.4 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
// Copyright (C) 2013-2018, 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 (
"errors"
"fmt"
. "github.com/holochain/holochain-proto/hash"
b58 "github.com/jbenet/go-base58"
ic "github.com/libp2p/go-libp2p-crypto"
peer "github.com/libp2p/go-libp2p-peer"
"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
)
// Arg holds the definition of an API function argument
type Arg struct {
Name string
Type ArgType
Optional bool
MapType reflect.Type
value interface{}
}
// APIFunction abstracts the argument structure and the calling of an api function
type APIFunction interface {
Name() string
Args() []Arg
Call(h *Holochain) (response interface{}, err error)
}
// Action provides an abstraction for handling node interaction
type Action interface {
Name() string
Receive(dht *DHT, msg *Message) (response interface{}, err error)
}
// CommittingAction provides an abstraction for grouping actions which carry Entry data
type CommittingAction interface {
Name() string
// Performs all validation logic, including sysValidation (must be called explicitly)
SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)
Receive(dht *DHT, msg *Message) (response interface{}, err error)
CheckValidationRequest(def *EntryDef) (err error)
EntryType() string
// returns a GobEntry containing the action's entry in a serialized format
Entry() Entry
SetHeader(header *Header)
GetHeader() (header *Header)
// Low level implementation of putting to DHT (assumes validation has been done)
Share(h *Holochain, def *EntryDef) (err error)
}
// ValidatingAction provides an abstraction for grouping all the actions that participate in validation loop
type ValidatingAction interface {
Name() string
SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)
Receive(dht *DHT, msg *Message) (response interface{}, err error)
CheckValidationRequest(def *EntryDef) (err error)
}
type ModAgentOptions struct {
Identity string
Revocation string
}
var NonDHTAction error = errors.New("Not a DHT 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 ErrNotValidForHeadersType error = errors.New("Invalid action for Headers type")
var ErrNotValidForDelType error = errors.New("Invalid action for Del type")
var ErrModInvalidForLinks error = errors.New("mod: invalid for Links entry")
var ErrModMissingHeader error = errors.New("mod: missing header")
var ErrModReplacesHashNotDifferent error = errors.New("mod: replaces must be different from original hash")
var ErrEntryDefInvalid = errors.New("Invalid Entry Defintion")
var ErrActionMissingHeader error = errors.New("Action is missing header")
var ErrActionReceiveInvalid error = errors.New("Action receive is invalid")
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 string
pk, err = h.agent.EncodePubKey()
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 HeadersEntryType:
// if headers entry there no extra info to return in the package so do nothing
case DelEntryType:
// if del 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)
case MigrateEntryType:
// if migrate entry there no extra info to return in the package so do nothing
// TODO: later this might not be true, could return whole chain?
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(HoldReq{})
case GET_REQUEST:
a = &ActionGet{}
t = reflect.TypeOf(GetReq{})
case MOD_REQUEST:
a = &ActionMod{}
t = reflect.TypeOf(HoldReq{})
case DEL_REQUEST:
a = &ActionDel{}
t = reflect.TypeOf(HoldReq{})
case LINK_REQUEST:
a = &ActionLink{}
t = reflect.TypeOf(HoldReq{})
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)
}
// doCommit adds an entry to the local chain after validating the action it's part of
func (h *Holochain) doCommit(a CommittingAction, change Hash) (d *EntryDef, err error) {
entryType := a.EntryType()
entry := a.Entry()
var l int
var hash Hash
var header *Header
var added bool
chain := h.Chain()
bundle := chain.BundleStarted()
if bundle != nil {
chain = bundle.chain
}
// retry loop incase someone sneaks a new commit in between prepareHeader and addEntry
for !added {
chain.lk.RLock()
count := len(chain.Headers)
l, hash, header, err = chain.prepareHeader(time.Now(), entryType, entry, h.agent.PrivKey(), change)
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
}
chain.lk.Lock()
if count == len(chain.Headers) {
err = chain.addEntry(l, hash, header, entry)
if err == nil {
added = true
}
}
chain.lk.Unlock()
if err != nil {
return
}
}
return
}
func (h *Holochain) commitAndShare(a CommittingAction, change Hash) (response Hash, err error) {
var def *EntryDef
def, err = h.doCommit(a, change)
if err != nil {
return
}
bundle := h.Chain().BundleStarted()
if bundle == nil {
err = a.Share(h, def)
} else {
bundle.sharing = append(bundle.sharing, a)
}
if err != nil {
return
}
response = a.GetHeader().EntryLink
return
}
func isValidPubKey(b58pk string) bool {
if len(b58pk) != 49 {
return false
}
pk := b58.Decode(b58pk)
_, err := ic.UnmarshalPublicKey(pk)
if err != nil {
return false
}
return true
}
const (
ValidationFailureBadPublicKeyFormat = "bad public key format"
ValidationFailureBadRevocationFormat = "bad revocation format"
)
func RunValidationPhase(h *Holochain, source peer.ID, msgType MsgType, query Hash, handler func(resp ValidateResponse) error) (err error) {
var r interface{}
msg := h.node.NewMessage(msgType, ValidateQuery{H: query})
r, err = h.Send(h.node.ctx, ValidateProtocol, source, msg, 0)
if err != nil {
return
}
switch resp := r.(type) {
case ValidateResponse:
err = handler(resp)
default:
err = fmt.Errorf("expected ValidateResponse from validator got %T", r)
}
return
}