forked from Consensys/quorum
/
api.go
441 lines (380 loc) · 14.9 KB
/
api.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
package extension
import (
"context"
"encoding/base64"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/multitenancy"
"github.com/ethereum/go-ethereum/permission/core"
)
var (
errNotAcceptor = errors.New("account is not acceptor of this extension request")
errNotCreator = errors.New("account is not the creator of this extension request")
)
const extensionCompleted = "DONE"
const extensionInProgress = "ACTIVE"
type PrivateExtensionAPI struct {
privacyService *PrivacyService
}
func NewPrivateExtensionAPI(privacyService *PrivacyService) *PrivateExtensionAPI {
return &PrivateExtensionAPI{
privacyService: privacyService,
}
}
// ActiveExtensionContracts returns the list of all currently outstanding extension contracts
func (api *PrivateExtensionAPI) ActiveExtensionContracts(ctx context.Context) []ExtensionContract {
api.privacyService.mu.Lock()
defer api.privacyService.mu.Unlock()
psi, err := api.privacyService.apiBackendHelper.PSMR().ResolveForUserContext(ctx)
if err != nil {
return nil
}
extracted := make([]ExtensionContract, 0)
for _, contract := range api.privacyService.psiContracts[psi.ID] {
extracted = append(extracted, *contract)
}
return extracted
}
// checks of the passed contract address is under extension process
func (api *PrivateExtensionAPI) checkIfContractUnderExtension(ctx context.Context, toExtend common.Address) bool {
for _, v := range api.ActiveExtensionContracts(ctx) {
if v.ContractExtended == toExtend {
return true
}
}
return false
}
// checks if the voter has already voted on the contract.
func (api *PrivateExtensionAPI) checkAlreadyVoted(addressToVoteOn, from common.Address, psi types.PrivateStateIdentifier) bool {
psiManagementContractClient := api.privacyService.managementContract(psi)
defer psiManagementContractClient.Close()
caller, _ := psiManagementContractClient.Caller(addressToVoteOn)
opts := bind.CallOpts{Pending: true, From: from}
voted, _ := caller.CheckIfVoted(&opts)
return voted
}
// checks if the contract extension is completed
func (api *PrivateExtensionAPI) checkIfExtensionComplete(addressToVoteOn, from common.Address, psi types.PrivateStateIdentifier) (bool, error) {
psiManagementContractClient := api.privacyService.managementContract(psi)
defer psiManagementContractClient.Close()
caller, _ := psiManagementContractClient.Caller(addressToVoteOn)
opts := bind.CallOpts{Pending: true, From: from}
status, err := caller.CheckIfExtensionFinished(&opts)
if err != nil {
return true, err
}
return status, nil
}
// checks if the contract being extended is a public contract
func (api *PrivateExtensionAPI) checkIfPublicContract(toExtend common.Address) (bool, error) {
// check if the passed contract is public contract
chain := api.privacyService.stateFetcher.chainAccessor
publicStateDb, _, err := chain.StateAtPSI(chain.CurrentBlock().Root(), types.DefaultPrivateStateIdentifier)
if err != nil {
return false, err
}
return publicStateDb != nil && publicStateDb.Exist(toExtend), nil
}
// checks if the contract being extended is available on the node
func (api *PrivateExtensionAPI) checkIfPrivateStateExists(psi types.PrivateStateIdentifier, toExtend common.Address) (bool, error) {
// check if the private contract exists on the node extending the contract
chain := api.privacyService.stateFetcher.chainAccessor
_, privateStateDb, err := chain.StateAtPSI(chain.CurrentBlock().Root(), psi)
if err != nil {
return false, err
}
return privateStateDb != nil && privateStateDb.GetCode(toExtend) != nil, nil
}
func (api *PrivateExtensionAPI) doMultiTenantChecks(ctx context.Context, address common.Address, txa ethapi.SendTxArgs) error {
backendHelper := api.privacyService.apiBackendHelper
if token, ok := backendHelper.SupportsMultitenancy(ctx); ok {
psm, err := backendHelper.PSMR().ResolveForUserContext(ctx)
if err != nil {
return err
}
eoaSecAttr := (&multitenancy.PrivateStateSecurityAttribute{}).WithPSI(psm.ID).WithNodeEOA(address)
psm, err = backendHelper.PSMR().ResolveForManagedParty(txa.PrivateFrom)
if err != nil {
return err
}
privateFromSecAttr := (&multitenancy.PrivateStateSecurityAttribute{}).WithPSI(psm.ID).WithNodeEOA(address)
if isAuthorized, _ := multitenancy.IsAuthorized(token, eoaSecAttr, privateFromSecAttr); !isAuthorized {
return multitenancy.ErrNotAuthorized
}
}
return nil
}
// GenerateExtensionApprovalUuid generates a uuid to be used for contract state extension approval when calling doVote within the management contract,
// allowing the approval method to be called with an external signer
func (api *PrivateExtensionAPI) GenerateExtensionApprovalUuid(ctx context.Context, addressToVoteOn common.Address, externalSignerAddress common.Address, txa ethapi.SendTxArgs) (string, error) {
err := api.doMultiTenantChecks(ctx, txa.From, txa)
if err != nil {
return "", err
}
psm, err := api.privacyService.apiBackendHelper.PSMR().ResolveForUserContext(ctx)
if err != nil {
return "", err
}
psi := psm.ID
// check if the extension has been completed. if yes
// no acceptance required
status, err := api.checkIfExtensionComplete(addressToVoteOn, externalSignerAddress, psi)
if err != nil {
return "", err
}
if status {
return "", errors.New("contract extension process complete. nothing to accept")
}
// get all participants for the contract being extended
participants, err := api.privacyService.GetAllParticipants(api.privacyService.stateFetcher.getCurrentBlockHash(), addressToVoteOn, psi)
if err == nil {
txa.PrivateFor = append(txa.PrivateFor, participants...)
}
txArgs, err := api.privacyService.GenerateTransactOptions(txa)
if err != nil {
return "", err
}
psiManagementContractClient := api.privacyService.managementContract(psi)
defer psiManagementContractClient.Close()
voterList, err := psiManagementContractClient.GetAllVoters(addressToVoteOn)
if err != nil {
return "", err
}
if isVoter := checkAddressInList(externalSignerAddress, voterList); !isVoter {
return "", errNotAcceptor
}
if api.checkAlreadyVoted(addressToVoteOn, externalSignerAddress, psi) {
return "", errors.New("already voted")
}
uuid, err := generateUuid(addressToVoteOn, txArgs.PrivateFrom, txArgs.PrivateFor, api.privacyService.ptm)
if err != nil {
return "", err
}
return uuid, nil
}
// ApproveContractExtension submits the vote to the specified extension management contract. The vote indicates whether to extend
// a given contract to a new participant or not
func (api *PrivateExtensionAPI) ApproveExtension(ctx context.Context, addressToVoteOn common.Address, vote bool, txa ethapi.SendTxArgs) (string, error) {
err := api.doMultiTenantChecks(ctx, txa.From, txa)
if err != nil {
return "", err
}
psm, err := api.privacyService.apiBackendHelper.PSMR().ResolveForUserContext(ctx)
if err != nil {
return "", err
}
psi := psm.ID
// check if the extension has been completed. if yes
// no acceptance required
status, err := api.checkIfExtensionComplete(addressToVoteOn, txa.From, psi)
if err != nil {
return "", err
}
if status {
return "", errors.New("contract extension process complete. nothing to accept")
}
if !core.CheckIfAdminAccount(txa.From) {
return "", errors.New("account cannot accept extension")
}
// get all participants for the contract being extended
participants, err := api.privacyService.GetAllParticipants(api.privacyService.stateFetcher.getCurrentBlockHash(), addressToVoteOn, psi)
if err == nil {
txa.PrivateFor = append(txa.PrivateFor, participants...)
}
txArgs, err := api.privacyService.GenerateTransactOptions(txa)
if err != nil {
return "", err
}
psiManagementContractClient := api.privacyService.managementContract(psi)
defer psiManagementContractClient.Close()
voterList, err := psiManagementContractClient.GetAllVoters(addressToVoteOn)
if err != nil {
return "", err
}
if isVoter := checkAddressInList(txArgs.From, voterList); !isVoter {
return "", errNotAcceptor
}
if api.checkAlreadyVoted(addressToVoteOn, txArgs.From, psi) {
return "", errors.New("already voted")
}
uuid, err := generateUuid(addressToVoteOn, txArgs.PrivateFrom, txArgs.PrivateFor, api.privacyService.ptm)
if err != nil {
return "", err
}
//Find the extension contract in order to interact with it
extender, err := psiManagementContractClient.Transactor(addressToVoteOn)
if err != nil {
return "", err
}
//Perform the vote transaction.
tx, err := extender.DoVote(txArgs, vote, uuid)
if err != nil {
return "", err
}
msg := fmt.Sprintf("0x%x", tx.Hash())
return msg, nil
}
// ExtendContract deploys a new extension management contract to the blockchain to start the process of extending
// a contract to a new participant
// Create a new extension contract that signifies that we want to add a new participant to an existing contract
// This should contain:
// - arguments for sending a new transaction (the same as sendTransaction)
// - the contract address we want to extend
// - the new PTM public key
// - the Ethereum addresses of who can vote to extend the contract
func (api *PrivateExtensionAPI) ExtendContract(ctx context.Context, toExtend common.Address, newRecipientPtmPublicKey string, recipientAddr common.Address, txa ethapi.SendTxArgs) (string, error) {
// check if the contract to be extended is already under extension
// if yes throw an error
if api.checkIfContractUnderExtension(ctx, toExtend) {
return "", errors.New("contract extension in progress for the given contract address")
}
// check if a public contract is being extended
isPublic, err := api.checkIfPublicContract(toExtend)
if err != nil {
return "", err
}
if isPublic {
return "", errors.New("extending a public contract!!! not allowed")
}
err = api.doMultiTenantChecks(ctx, txa.From, txa)
if err != nil {
return "", err
}
// check if recipient address is 0x0
if recipientAddr == (common.Address{0}) {
return "", errors.New("invalid recipient address")
}
psm, err := api.privacyService.apiBackendHelper.PSMR().ResolveForUserContext(ctx)
if err != nil {
return "", err
}
// check if a private contract exists
privateContractExists, err := api.checkIfPrivateStateExists(psm.ID, toExtend)
if err != nil {
return "", err
}
if !privateContractExists {
return "", errors.New("extending a non-existent private contract!!! not allowed")
}
// check if contract creator
if !api.privacyService.CheckIfContractCreator(api.privacyService.stateFetcher.getCurrentBlockHash(), toExtend, psm.ID) {
return "", errors.New("operation not allowed")
}
// if running in permissioned mode with new permissions model
// ensure that the account extending the contract is an admin
// account and recipient account is an admin account as well
if txa.From == recipientAddr {
return "", errors.New("account accepting the extension cannot be the account initiating extension")
}
if !core.CheckIfAdminAccount(txa.From) {
return "", errors.New("account not an org admin account, cannot initiate extension")
}
if !core.CheckIfAdminAccount(recipientAddr) {
return "", errors.New("recipient account address is not an org admin account. cannot accept extension")
}
// check the new key is valid
if _, err := base64.StdEncoding.DecodeString(newRecipientPtmPublicKey); err != nil {
return "", errors.New("invalid new recipient transaction manager key provided")
}
// check the the intended new recipient will actually receive the extension request
switch len(txa.PrivateFor) {
case 0:
txa.PrivateFor = append(txa.PrivateFor, newRecipientPtmPublicKey)
case 1:
if txa.PrivateFor[0] != newRecipientPtmPublicKey {
return "", errors.New("mismatch between recipient transaction manager key and privateFor argument")
}
default:
return "", errors.New("invalid transaction manager keys given in privateFor argument")
}
// get all participants for the contract being extended
participants, err := api.privacyService.GetAllParticipants(api.privacyService.stateFetcher.getCurrentBlockHash(), toExtend, psm.ID)
if err == nil {
txa.PrivateFor = append(txa.PrivateFor, participants...)
}
//generate some valid transaction options for sending in the transaction
txArgs, err := api.privacyService.GenerateTransactOptions(txa)
if err != nil {
return "", err
}
psiManagementContractClient := api.privacyService.managementContract(psm.ID)
defer psiManagementContractClient.Close()
//Deploy the contract
tx, err := psiManagementContractClient.Deploy(txArgs, toExtend, recipientAddr, newRecipientPtmPublicKey)
if err != nil {
return "", err
}
//Return the transaction hash for later lookup
msg := fmt.Sprintf("0x%x", tx.Hash())
return msg, nil
}
// CancelExtension allows the creator to cancel the given extension contract, ensuring
// that no more calls for votes or accepting can be made
func (api *PrivateExtensionAPI) CancelExtension(ctx context.Context, extensionContract common.Address, txa ethapi.SendTxArgs) (string, error) {
err := api.doMultiTenantChecks(ctx, txa.From, txa)
if err != nil {
return "", err
}
psm, err := api.privacyService.apiBackendHelper.PSMR().ResolveForUserContext(ctx)
if err != nil {
return "", err
}
// get all participants for the contract being extended
status, err := api.checkIfExtensionComplete(extensionContract, txa.From, psm.ID)
if err != nil {
return "", err
}
if status {
return "", errors.New("contract extension process complete. nothing to cancel")
}
participants, err := api.privacyService.GetAllParticipants(api.privacyService.stateFetcher.getCurrentBlockHash(), extensionContract, psm.ID)
if err == nil {
txa.PrivateFor = append(txa.PrivateFor, participants...)
}
txArgs, err := api.privacyService.GenerateTransactOptions(txa)
if err != nil {
return "", err
}
psiManagementContractClient := api.privacyService.managementContract(psm.ID)
defer psiManagementContractClient.Close()
caller, err := psiManagementContractClient.Caller(extensionContract)
if err != nil {
return "", err
}
creatorAddress, err := caller.Creator(nil)
if err != nil {
return "", err
}
if isCreator := checkAddressInList(txArgs.From, []common.Address{creatorAddress}); !isCreator {
return "", errNotCreator
}
extender, err := psiManagementContractClient.Transactor(extensionContract)
if err != nil {
return "", err
}
tx, err := extender.Finish(txArgs)
if err != nil {
return "", err
}
msg := fmt.Sprintf("0x%x", tx.Hash())
return msg, nil
}
// Returns the extension status from management contract
func (api *PrivateExtensionAPI) GetExtensionStatus(ctx context.Context, extensionContract common.Address) (string, error) {
psm, err := api.privacyService.apiBackendHelper.PSMR().ResolveForUserContext(ctx)
if err != nil {
return "", err
}
status, err := api.checkIfExtensionComplete(extensionContract, common.Address{}, psm.ID)
if err != nil {
return "", err
}
if status {
return extensionCompleted, nil
}
return extensionInProgress, nil
}