/
processor.go
289 lines (238 loc) · 9.86 KB
/
processor.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
package documents
import (
"context"
"time"
coredocumentpb "github.com/centrifuge/centrifuge-protobufs/gen/go/coredocument"
p2ppb "github.com/centrifuge/centrifuge-protobufs/gen/go/p2p"
"github.com/centrifuge/go-centrifuge/anchors"
"github.com/centrifuge/go-centrifuge/config"
"github.com/centrifuge/go-centrifuge/contextutil"
"github.com/centrifuge/go-centrifuge/errors"
"github.com/centrifuge/go-centrifuge/identity"
"github.com/centrifuge/go-centrifuge/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
)
// AnchorProcessor identifies an implementation, which can do a bunch of things with a CoreDocument.
// E.g. send, anchor, etc.
type AnchorProcessor interface {
Send(ctx context.Context, cd coredocumentpb.CoreDocument, recipient identity.DID) (err error)
PrepareForSignatureRequests(ctx context.Context, doc Document) error
RequestSignatures(ctx context.Context, doc Document) error
PrepareForAnchoring(ctx context.Context, doc Document) error
PreAnchorDocument(ctx context.Context, doc Document) error
AnchorDocument(ctx context.Context, doc Document) error
SendDocument(ctx context.Context, doc Document) error
}
// Config defines required methods required for the documents package.
type Config interface {
GetNetworkID() uint32
GetIdentityID() ([]byte, error)
GetP2PConnectionTimeout() time.Duration
GetContractAddress(contractName config.ContractName) common.Address
}
// DocumentRequestProcessor offers methods to interact with the p2p layer to request documents.
type DocumentRequestProcessor interface {
RequestDocumentWithAccessToken(ctx context.Context, granterDID identity.DID, tokenIdentifier, documentIdentifier, delegatingDocumentIdentifier []byte) (*p2ppb.GetDocumentResponse, error)
}
// Client defines methods that can be implemented by any type handling p2p communications.
type Client interface {
// GetSignaturesForDocument gets the signatures for document
GetSignaturesForDocument(ctx context.Context, model Document) ([]*coredocumentpb.Signature, []error, error)
// after all signatures are collected the sender sends the document including the signatures
SendAnchoredDocument(ctx context.Context, receiverID identity.DID, in *p2ppb.AnchorDocumentRequest) (*p2ppb.AnchorDocumentResponse, error)
// GetDocumentRequest requests a document from a collaborator
GetDocumentRequest(ctx context.Context, requesterID identity.DID, in *p2ppb.GetDocumentRequest) (*p2ppb.GetDocumentResponse, error)
}
// defaultProcessor implements AnchorProcessor interface
type defaultProcessor struct {
identityService identity.Service
p2pClient Client
anchorSrv anchors.Service
config Config
}
// DefaultProcessor returns the default implementation of CoreDocument AnchorProcessor
func DefaultProcessor(idService identity.Service, p2pClient Client, anchorSrv anchors.Service, config Config) AnchorProcessor {
return defaultProcessor{
identityService: idService,
p2pClient: p2pClient,
anchorSrv: anchorSrv,
config: config,
}
}
// Send sends the given defaultProcessor to the given recipient on the P2P layer
func (dp defaultProcessor) Send(ctx context.Context, cd coredocumentpb.CoreDocument, id identity.DID) (err error) {
log.Infof("sending document %s to recipient %s", hexutil.Encode(cd.DocumentIdentifier), id.String())
ctx, cancel := context.WithTimeout(ctx, dp.config.GetP2PConnectionTimeout())
defer cancel()
resp, err := dp.p2pClient.SendAnchoredDocument(ctx, id, &p2ppb.AnchorDocumentRequest{Document: &cd})
if err != nil || !resp.Accepted {
return errors.New("failed to send document to the node: %v", err)
}
log.Infof("Sent document to %s\n", id.String())
return nil
}
// PrepareForSignatureRequests gets the core document from the model, and adds the node's own signature
func (dp defaultProcessor) PrepareForSignatureRequests(ctx context.Context, model Document) error {
self, err := contextutil.Account(ctx)
if err != nil {
return err
}
id := self.GetIdentityID()
did, err := identity.NewDIDFromBytes(id)
if err != nil {
return err
}
err = model.AddUpdateLog(did)
if err != nil {
return err
}
addr := dp.config.GetContractAddress(config.AnchorRepo)
model.SetUsedAnchorRepoAddress(addr)
// execute compute fields
err = model.ExecuteComputeFields(computeFieldsTimeout)
if err != nil {
return err
}
// calculate the signing root
sr, err := model.CalculateSigningRoot()
if err != nil {
return errors.New("failed to calculate signing root: %v", err)
}
sig, err := self.SignMsg(ConsensusSignaturePayload(sr, false))
if err != nil {
return err
}
model.AppendSignatures(sig)
return nil
}
// RequestSignatures gets the core document from the model, validates pre signature requirements,
// collects signatures, and validates the signatures,
func (dp defaultProcessor) RequestSignatures(ctx context.Context, model Document) error {
psv := SignatureValidator(dp.identityService, dp.anchorSrv)
err := psv.Validate(nil, model)
if err != nil {
return errors.New("failed to validate model for signature request: %v", err)
}
// we ignore signature collection errors and anchor anyways
signs, _, err := dp.p2pClient.GetSignaturesForDocument(ctx, model)
if err != nil {
return errors.New("failed to collect signatures from the collaborators: %v", err)
}
model.AppendSignatures(signs...)
return nil
}
// PrepareForAnchoring validates the signatures and generates the document root
func (dp defaultProcessor) PrepareForAnchoring(ctx context.Context, model Document) error {
psv := SignatureValidator(dp.identityService, dp.anchorSrv)
err := psv.Validate(nil, model)
if err != nil {
return errors.New("failed to validate signatures: %v", err)
}
return nil
}
// PreAnchorDocument pre-commits a document
func (dp defaultProcessor) PreAnchorDocument(ctx context.Context, model Document) error {
signingRoot, err := model.CalculateSigningRoot()
if err != nil {
return err
}
anchorID, err := anchors.ToAnchorID(model.CurrentVersion())
if err != nil {
return err
}
sRoot, err := anchors.ToDocumentRoot(signingRoot)
if err != nil {
return err
}
log.Infof("Pre-anchoring document with identifiers: [document: %#x, current: %#x, next: %#x], signingRoot: %#x", model.ID(), model.CurrentVersion(), model.NextVersion(), sRoot)
err = dp.anchorSrv.PreCommitAnchor(ctx, anchorID, sRoot)
if err != nil {
return errors.New("failed to pre-commit anchor: %v", err)
}
log.Infof("Pre-anchored document with identifiers: [document: %#x, current: %#x, next: %#x], signingRoot: %#x", model.ID(), model.CurrentVersion(), model.NextVersion(), sRoot)
return nil
}
// AnchorDocument validates the model, and anchors the document
func (dp defaultProcessor) AnchorDocument(ctx context.Context, model Document) error {
pav := PreAnchorValidator(dp.identityService, dp.anchorSrv)
err := pav.Validate(nil, model)
if err != nil {
return errors.New("pre anchor validation failed: %v", err)
}
dr, err := model.CalculateDocumentRoot()
if err != nil {
return errors.New("failed to get document root: %v", err)
}
rootHash, err := anchors.ToDocumentRoot(dr)
if err != nil {
return errors.New("failed to convert document root: %v", err)
}
anchorIDPreimage, err := anchors.ToAnchorID(model.CurrentVersionPreimage())
if err != nil {
return errors.New("failed to get anchor ID: %v", err)
}
signaturesRootProof, err := model.CalculateSignaturesRoot()
if err != nil {
return errors.New("failed to get signature root: %v", err)
}
signaturesRootHash, err := utils.SliceToByte32(signaturesRootProof)
if err != nil {
return errors.New("failed to get signing root proof in ethereum format: %v", err)
}
log.Infof("Anchoring document with identifiers: [document: %#x, current: %#x, next: %#x], rootHash: %#x", model.ID(), model.CurrentVersion(), model.NextVersion(), dr)
err = dp.anchorSrv.CommitAnchor(ctx, anchorIDPreimage, rootHash, signaturesRootHash)
if err != nil {
return errors.New("failed to commit anchor: %v", err)
}
log.Infof("Anchored document with identifiers: [document: %#x, current: %#x, next: %#x], rootHash: %#x", model.ID(), model.CurrentVersion(), model.NextVersion(), dr)
return nil
}
// RequestDocumentWithAccessToken requests a document with an access token
func (dp defaultProcessor) RequestDocumentWithAccessToken(ctx context.Context, granterDID identity.DID, tokenIdentifier, documentIdentifier, delegatingDocumentIdentifier []byte) (*p2ppb.GetDocumentResponse, error) {
accessTokenRequest := &p2ppb.AccessTokenRequest{DelegatingDocumentIdentifier: delegatingDocumentIdentifier, AccessTokenId: tokenIdentifier}
request := &p2ppb.GetDocumentRequest{DocumentIdentifier: documentIdentifier,
AccessType: p2ppb.AccessType_ACCESS_TYPE_ACCESS_TOKEN_VERIFICATION,
AccessTokenRequest: accessTokenRequest,
}
response, err := dp.p2pClient.GetDocumentRequest(ctx, granterDID, request)
if err != nil {
return nil, err
}
return response, nil
}
// SendDocument does post anchor validations and sends the document to collaborators
func (dp defaultProcessor) SendDocument(ctx context.Context, model Document) error {
av := PostAnchoredValidator(dp.identityService, dp.anchorSrv)
err := av.Validate(nil, model)
if err != nil {
return errors.New("post anchor validations failed: %v", err)
}
selfDID, err := contextutil.AccountDID(ctx)
if err != nil {
return err
}
cs, err := model.GetSignerCollaborators(selfDID)
if err != nil {
return errors.New("get external collaborators failed: %v", err)
}
cd, err := model.PackCoreDocument()
if err != nil {
return errors.New("failed to pack core document: %v", err)
}
for _, c := range cs {
err := dp.Send(ctx, cd, c)
if err != nil {
log.Error(err)
}
}
return err
}
// ConsensusSignaturePayload forms the payload needed to be signed during the document consensus flow
func ConsensusSignaturePayload(dataRoot []byte, validated bool) []byte {
tFlag := byte(0)
if validated {
tFlag = byte(1)
}
return append(dataRoot, tFlag)
}