-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathstartCompute.ts
More file actions
774 lines (754 loc) · 24.6 KB
/
Copy pathstartCompute.ts
File metadata and controls
774 lines (754 loc) · 24.6 KB
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
import { Readable } from 'stream'
import { P2PCommandResponse } from '../../../@types/index.js'
import { CORE_LOGGER } from '../../../utils/logging/common.js'
import {
FreeComputeStartCommand,
PaidComputeStartCommand
} from '../../../@types/commands.js'
import { CommandHandler } from '../handler/handler.js'
import { getAlgoChecksums, validateAlgoForDataset } from './utils.js'
import {
ValidateParams,
buildInvalidRequestMessage,
validateCommandParameters
} from '../../httpRoutes/validateCommands.js'
import { isAddress } from 'ethers'
import {
AssetUtils,
getFilesObjectFromConfidentialEVM,
isConfidentialChainDDO,
isDataTokenTemplate4,
isERC20Template4Active
} from '../../../utils/asset.js'
import { EncryptMethod } from '../../../@types/fileObject.js'
import { ComputeResourceRequestWithPrice } from '../../../@types/C2D/C2D.js'
import { decrypt } from '../../../utils/crypt.js'
// import { verifyProviderFees } from '../utils/feesHandler.js'
import { Blockchain } from '../../../utils/blockchain.js'
import { validateOrderTransaction } from '../utils/validateOrders.js'
import { getConfiguration, isPolicyServerConfigured } from '../../../utils/index.js'
import { sanitizeServiceFiles } from '../../../utils/util.js'
import { FindDdoHandler } from '../handler/ddoHandler.js'
// import { ProviderFeeValidation } from '../../../@types/Fees.js'
import { isOrderingAllowedForAsset } from '../handler/downloadHandler.js'
import { DDOManager } from '@oceanprotocol/ddo-js'
import { getNonceAsNumber, checkNonce, NonceResponse } from '../utils/nonceHandler.js'
import { createHash } from 'crypto'
import { PolicyServer } from '../../policyServer/index.js'
import { areKnownCredentialTypes, checkCredentials } from '../../../utils/credentials.js'
export class PaidComputeStartHandler extends CommandHandler {
validate(command: PaidComputeStartCommand): ValidateParams {
const commandValidation = validateCommandParameters(command, [
'consumerAddress',
'signature',
'nonce',
'environment',
'algorithm',
'datasets',
'maxJobDuration'
])
if (commandValidation.valid) {
if (!isAddress(command.consumerAddress)) {
return buildInvalidRequestMessage(
'Parameter : "consumerAddress" is not a valid web3 address'
)
}
if (parseInt(String(command.maxJobDuration)) <= 0) {
return buildInvalidRequestMessage('Invalid maxJobDuration')
}
}
return commandValidation
}
async handle(task: PaidComputeStartCommand): Promise<P2PCommandResponse> {
const validationResponse = await this.verifyParamsAndRateLimits(task)
if (this.shouldDenyTaskHandling(validationResponse)) {
return validationResponse
}
try {
const node = this.getOceanNode()
// split compute env (which is already in hash-envId format) and get the hash
// then get env which might contain dashes as well
const eIndex = task.environment.indexOf('-')
const hash = task.environment.slice(0, eIndex)
let engine
let env
try {
engine = await node.getC2DEngines().getC2DByHash(hash)
} catch (e) {
return {
stream: null,
status: {
httpStatus: 500,
error: 'Invalid C2D Environment'
}
}
}
try {
env = await engine.getComputeEnvironment(null, task.environment)
if (!env) {
return {
stream: null,
status: {
httpStatus: 500,
error: 'Invalid C2D Environment'
}
}
}
if (!task.maxJobDuration || task.maxJobDuration > env.maxJobDuration) {
task.maxJobDuration = env.maxJobDuration
}
task.payment.resources = await engine.checkAndFillMissingResources(
task.payment.resources,
env,
false
)
await engine.checkIfResourcesAreAvailable(task.payment.resources, env, true)
} catch (e) {
return {
stream: null,
status: {
httpStatus: 400,
error: e
}
}
}
const { algorithm } = task
const algoChecksums = await getAlgoChecksums(
task.algorithm.documentId,
task.algorithm.serviceId,
node
)
if (!algoChecksums.container || !algoChecksums.files) {
CORE_LOGGER.error(`Error retrieveing algorithm checksums!`)
return {
stream: null,
status: {
httpStatus: 500,
error: `Error retrieveing algorithm checksums!`
}
}
}
// check algo
for (const elem of [...[task.algorithm], ...task.datasets]) {
console.log(elem)
const result: any = { validOrder: false }
if ('documentId' in elem && elem.documentId) {
result.did = elem.documentId
result.serviceId = elem.documentId
const ddo = await new FindDdoHandler(node).findAndFormatDdo(elem.documentId)
if (!ddo) {
const error = `DDO ${elem.documentId} not found`
return {
stream: null,
status: {
httpStatus: 500,
error
}
}
}
const isOrdable = isOrderingAllowedForAsset(ddo)
if (!isOrdable.isOrdable) {
CORE_LOGGER.error(isOrdable.reason)
return {
stream: null,
status: {
httpStatus: 500,
error: isOrdable.reason
}
}
}
// check credentials (DDO level)
let accessGrantedDDOLevel: boolean
if (ddo.credentials) {
// if POLICY_SERVER_URL exists, then ocean-node will NOT perform any checks.
// It will just use the existing code and let PolicyServer decide.
if (isPolicyServerConfigured() && task.policyServer) {
accessGrantedDDOLevel = await (
await new PolicyServer().checkStartCompute(
ddo.id,
ddo,
elem.serviceId,
0,
elem.transferTxId,
task.consumerAddress,
task.policyServer
)
).success
} else {
accessGrantedDDOLevel = areKnownCredentialTypes(ddo.credentials)
? checkCredentials(ddo.credentials, task.consumerAddress)
: true
}
if (!accessGrantedDDOLevel) {
CORE_LOGGER.logMessage(`Error: Access to asset ${ddo.id} was denied`, true)
return {
stream: null,
status: {
httpStatus: 403,
error: `Error: Access to asset ${ddo.id} was denied`
}
}
}
}
const service = AssetUtils.getServiceById(ddo, elem.serviceId)
if (!service) {
const error = `Cannot find service ${elem.serviceId} in DDO ${elem.documentId}`
return {
stream: null,
status: {
httpStatus: 500,
error
}
}
}
// check credentials on service level
// if using a policy server and we are here it means that access was granted (they are merged/assessed together)
if (service.credentials) {
let accessGrantedServiceLevel: boolean
if (isPolicyServerConfigured() && task.policyServer) {
// we use the previous check or we do it again
// (in case there is no DDO level credentials and we only have Service level ones)
accessGrantedServiceLevel =
accessGrantedDDOLevel ||
(await (
await new PolicyServer().checkStartCompute(
ddo.id,
ddo,
elem.serviceId,
0,
elem.transferTxId,
task.consumerAddress,
task.policyServer
)
).success)
} else {
accessGrantedServiceLevel = areKnownCredentialTypes(service.credentials)
? checkCredentials(service.credentials, task.consumerAddress)
: true
}
if (!accessGrantedServiceLevel) {
CORE_LOGGER.logMessage(
`Error: Access to service with id ${service.id} was denied`,
true
)
return {
stream: null,
status: {
httpStatus: 403,
error: `Error: Access to service with id ${service.id} was denied`
}
}
}
}
const config = await getConfiguration()
const ddoInstance = DDOManager.getDDOClass(ddo)
const {
chainId: ddoChainId,
services,
metadata,
nftAddress
} = ddoInstance.getDDOFields()
const { rpc, network, chainId, fallbackRPCs } =
config.supportedNetworks[ddoChainId]
const blockchain = new Blockchain(rpc, network, chainId, fallbackRPCs)
const { ready, error } = await blockchain.isNetworkReady()
if (!ready) {
return {
stream: null,
status: {
httpStatus: 400,
error: `Start Compute : ${error}`
}
}
}
const signer = blockchain.getSigner()
// let's see if we can access this asset
// check if oasis evm or similar
const confidentialEVM = isConfidentialChainDDO(BigInt(ddo.chainId), service)
let canDecrypt = false
try {
if (!confidentialEVM) {
await decrypt(
Uint8Array.from(Buffer.from(sanitizeServiceFiles(service.files), 'hex')),
EncryptMethod.ECIES
)
canDecrypt = true
} else {
// TODO 'Start compute on confidential EVM!'
const isTemplate4 = await isDataTokenTemplate4(
service.datatokenAddress,
signer
)
if (isTemplate4 && (await isERC20Template4Active(ddoChainId, signer))) {
// we need to get the proper data for the signature
const consumeData =
task.consumerAddress +
task.datasets[0].documentId +
getNonceAsNumber(task.consumerAddress)
// call smart contract to decrypt
const serviceIndex = AssetUtils.getServiceIndexById(ddo, service.id)
const filesObject = await getFilesObjectFromConfidentialEVM(
serviceIndex,
service.datatokenAddress,
signer,
task.consumerAddress,
task.signature, // we will need to have a signature verification
consumeData
)
if (filesObject != null) {
canDecrypt = true
}
}
}
} catch (e) {
// do nothing
CORE_LOGGER.error('Could not decrypt DDO files Object: ' + e.message)
}
if (service.type === 'compute' && !canDecrypt) {
const error = `Service ${elem.serviceId} from DDO ${elem.documentId} cannot be used in compute on this provider`
return {
stream: null,
status: {
httpStatus: 500,
error
}
}
}
if (metadata.type !== 'algorithm') {
const validAlgoForDataset = await validateAlgoForDataset(
task.algorithm.documentId,
algoChecksums,
ddoInstance,
services[0].id,
node
)
if (!validAlgoForDataset) {
return {
stream: null,
status: {
httpStatus: 400,
error: `Algorithm ${
task.algorithm.documentId
} not allowed to run on the dataset: ${ddoInstance.getDid()}`
}
}
}
}
const provider = blockchain.getProvider()
result.datatoken = service.datatokenAddress
result.chainId = ddoChainId
if (!('transferTxId' in elem) || !elem.transferTxId) {
const error = `Missing transferTxId for DDO ${elem.documentId}`
return {
stream: null,
status: {
httpStatus: 500,
error
}
}
}
// search for that compute env and see if it has access to dataset
const paymentValidation = await validateOrderTransaction(
elem.transferTxId,
env.consumerAddress,
provider,
nftAddress,
service.datatokenAddress,
AssetUtils.getServiceIndexById(ddo, service.id),
service.timeout,
blockchain.getSigner()
)
if (paymentValidation.isValid === false) {
const error = `TxId Service ${elem.transferTxId} is not valid for DDO ${elem.documentId} and service ${service.id}`
return {
stream: null,
status: {
httpStatus: 500,
error
}
}
}
result.validOrder = elem.transferTxId
if (!('meta' in algorithm) && ddo.metadata.type === 'algorithm') {
const { entrypoint, image, tag, checksum } = ddo.metadata.algorithm.container
const container = { entrypoint, image, tag, checksum }
algorithm.meta = {
language: metadata.algorithm.language,
version: metadata.algorithm.version,
container
}
}
}
}
// let's lock the amount
const prices = engine.getEnvPricesForToken(
env,
task.payment.chainId,
task.payment.token
)
if (!prices) {
return {
stream: null,
status: {
httpStatus: 500,
error: `This compute env does not accept payments on chain: ${task.payment.chainId} using token ${task.payment.token}`
}
}
}
const resources: ComputeResourceRequestWithPrice[] = []
for (const res of task.payment.resources) {
const price = engine.getResourcePrice(prices, res.id)
resources.push({
id: res.id,
amount: res.amount,
price
})
}
const s = {
assets: task.datasets,
algorithm,
output: task.output,
environment: env.id,
owner: task.consumerAddress,
maxJobDuration: task.maxJobDuration,
chainId: task.payment.chainId,
agreementId: '',
resources
}
// job ID unicity
const timestamp =
BigInt(Date.now()) * 1_000_000n + (process.hrtime.bigint() % 1_000_000n)
const random = Math.random()
const jobId = createHash('sha256')
.update(JSON.stringify(s) + timestamp.toString() + random.toString())
.digest('hex')
// let's calculate payment needed based on resources request and maxJobDuration
const cost = engine.calculateResourcesCost(
task.payment.resources,
env,
task.payment.chainId,
task.payment.token,
task.maxJobDuration
)
let agreementId
try {
agreementId = await engine.escrow.createLock(
task.payment.chainId,
jobId,
task.payment.token,
task.consumerAddress,
cost,
task.maxJobDuration
)
} catch (e) {
return {
stream: null,
status: {
httpStatus: 400,
error: e
}
}
}
try {
const response = await engine.startComputeJob(
task.datasets,
algorithm,
task.output,
env.id,
task.consumerAddress,
task.maxJobDuration,
task.payment.resources,
{
chainId: task.payment.chainId,
token: task.payment.token,
lockTx: agreementId,
claimTx: null
}
)
CORE_LOGGER.logMessage(
'ComputeStartCommand Response: ' + JSON.stringify(response, null, 2),
true
)
return {
stream: Readable.from(JSON.stringify(response)),
status: {
httpStatus: 200
}
}
} catch (e) {
try {
await engine.escrow.cancelExpiredLocks(
task.payment.chainId,
jobId,
task.payment.token,
task.consumerAddress
)
} catch (e) {
// is fine if it fails
}
return {
stream: null,
status: {
httpStatus: 400,
error: e
}
}
}
} catch (error) {
CORE_LOGGER.error(error.message)
return {
stream: null,
status: {
httpStatus: 500,
error: error.message
}
}
}
}
}
export class FreeComputeStartHandler extends CommandHandler {
validate(command: FreeComputeStartCommand): ValidateParams {
const commandValidation = validateCommandParameters(command, [
'algorithm',
'datasets',
'consumerAddress',
'signature',
'nonce',
'environment'
])
if (commandValidation.valid) {
if (!isAddress(command.consumerAddress)) {
return buildInvalidRequestMessage(
'Parameter : "consumerAddress" is not a valid web3 address'
)
}
}
return commandValidation
}
async handle(task: FreeComputeStartCommand): Promise<P2PCommandResponse> {
const validationResponse = await this.verifyParamsAndRateLimits(task)
if (this.shouldDenyTaskHandling(validationResponse)) {
return validationResponse
}
const thisNode = this.getOceanNode()
// Validate nonce and signature
const nonceCheckResult: NonceResponse = await checkNonce(
thisNode.getDatabase().nonce,
task.consumerAddress,
parseInt(task.nonce),
task.signature,
String(task.nonce)
)
if (!nonceCheckResult.valid) {
CORE_LOGGER.logMessage(
'Invalid nonce or signature, unable to proceed: ' + nonceCheckResult.error,
true
)
return {
stream: null,
status: {
httpStatus: 500,
error:
'Invalid nonce or signature, unable to proceed: ' + nonceCheckResult.error
}
}
}
let engine = null
try {
// split compute env (which is already in hash-envId format) and get the hash
// then get env which might contain dashes as well
const eIndex = task.environment.indexOf('-')
const hash = task.environment.slice(0, eIndex)
// const envId = task.environment.slice(eIndex + 1)
try {
engine = await thisNode.getC2DEngines().getC2DByHash(hash)
} catch (e) {
return {
stream: null,
status: {
httpStatus: 500,
error: 'Invalid C2D Environment'
}
}
}
if (engine === null) {
return {
stream: null,
status: {
httpStatus: 500,
error: 'Invalid C2D Environment'
}
}
}
for (const elem of [...[task.algorithm], ...task.datasets]) {
if (!('documentId' in elem)) {
continue
}
const ddo = await new FindDdoHandler(this.getOceanNode()).findAndFormatDdo(
elem.documentId
)
if (!ddo) {
const error = `DDO ${elem.documentId} not found`
return {
stream: null,
status: {
httpStatus: 500,
error
}
}
}
// check credentials (DDO level)
let accessGrantedDDOLevel: boolean
if (ddo.credentials) {
// if POLICY_SERVER_URL exists, then ocean-node will NOT perform any checks.
// It will just use the existing code and let PolicyServer decide.
if (isPolicyServerConfigured() && task.policyServer) {
accessGrantedDDOLevel = await (
await new PolicyServer().checkStartCompute(
ddo.id,
ddo,
elem.serviceId,
0,
elem.transferTxId,
task.consumerAddress,
task.policyServer
)
).success
} else {
accessGrantedDDOLevel = areKnownCredentialTypes(ddo.credentials)
? checkCredentials(ddo.credentials, task.consumerAddress)
: true
}
if (!accessGrantedDDOLevel) {
CORE_LOGGER.logMessage(`Error: Access to asset ${ddo.id} was denied`, true)
return {
stream: null,
status: {
httpStatus: 403,
error: `Error: Access to asset ${ddo.id} was denied`
}
}
}
}
const service = AssetUtils.getServiceById(ddo, elem.serviceId)
if (!service) {
const error = `Cannot find service ${elem.serviceId} in DDO ${elem.documentId}`
return {
stream: null,
status: {
httpStatus: 500,
error
}
}
}
// check credentials on service level
// if using a policy server and we are here it means that access was granted (they are merged/assessed together)
if (service.credentials) {
let accessGrantedServiceLevel: boolean
if (isPolicyServerConfigured() && task.policyServer) {
// we use the previous check or we do it again
// (in case there is no DDO level credentials and we only have Service level ones)
accessGrantedServiceLevel =
accessGrantedDDOLevel ||
(await (
await new PolicyServer().checkStartCompute(
ddo.id,
ddo,
elem.serviceId,
0,
elem.transferTxId,
task.consumerAddress,
task.policyServer
)
).success)
} else {
accessGrantedServiceLevel = areKnownCredentialTypes(service.credentials)
? checkCredentials(service.credentials, task.consumerAddress)
: true
}
if (!accessGrantedServiceLevel) {
CORE_LOGGER.logMessage(
`Error: Access to service with id ${service.id} was denied`,
true
)
return {
stream: null,
status: {
httpStatus: 403,
error: `Error: Access to service with id ${service.id} was denied`
}
}
}
}
}
try {
const env = await engine.getComputeEnvironment(null, task.environment)
if (!env) {
return {
stream: null,
status: {
httpStatus: 500,
error: 'Invalid C2D Environment'
}
}
}
task.resources = await engine.checkAndFillMissingResources(
task.resources,
env,
true
)
await engine.checkIfResourcesAreAvailable(task.resources, env, true)
if (!task.maxJobDuration || task.maxJobDuration > env.free.maxJobDuration) {
task.maxJobDuration = env.free.maxJobDuration
}
} catch (e) {
console.error(e)
return {
stream: null,
status: {
httpStatus: 400,
error: String(e)
}
}
}
// console.log(task.resources)
/*
return {
stream: null,
status: {
httpStatus: 200,
error: null
}
} */
const response = await engine.startComputeJob(
task.datasets,
task.algorithm,
task.output,
task.environment,
task.consumerAddress,
task.maxJobDuration,
task.resources,
null
)
CORE_LOGGER.logMessage(
'FreeComputeStartCommand Response: ' + JSON.stringify(response, null, 2),
true
)
return {
stream: Readable.from(JSON.stringify(response)),
status: {
httpStatus: 200
}
}
} catch (error) {
CORE_LOGGER.error(error.message)
return {
stream: null,
status: {
httpStatus: 500,
error: error.message
}
}
}
}
}