1
0
mirror of https://github.com/oceanprotocol-archive/squid-js.git synced 2024-02-02 15:31:51 +01:00

added OceanAgreementsConditions submodule

This commit is contained in:
Pedro Gutiérrez 2019-03-04 13:05:27 +01:00 committed by Pedro Gutiérrez
parent f7cd71ac33
commit 86906b393f
10 changed files with 325 additions and 105 deletions

View File

@ -11,11 +11,11 @@ describe("Register Escrow Access Secret Store Template", () => {
let ocean: Ocean let ocean: Ocean
let keeper: Keeper let keeper: Keeper
const agreementId = `0x${generateId()}` let template: templates.EscrowAccessSecretStoreTemplate
const escrowAmount = 12
const did = `0x${generateId()}`
const url = 'https://example.com/did/ocean/test-attr-example.txt' const url = 'https://example.com/did/ocean/test-attr-example.txt'
const checksum = "b".repeat(32) const checksum = "b".repeat(32)
const escrowAmount = 12
let templateManagerOwner: Account let templateManagerOwner: Account
let publisher: Account let publisher: Account
@ -25,12 +25,6 @@ describe("Register Escrow Access Secret Store Template", () => {
let lockRewardCondition: conditions.LockRewardCondition let lockRewardCondition: conditions.LockRewardCondition
let escrowReward: conditions.EscrowReward let escrowReward: conditions.EscrowReward
let template: templates.EscrowAccessSecretStoreTemplate
let conditionIdAccess: string
let conditionIdLock: string
let conditionIdEscrow: string
before(async () => { before(async () => {
ocean = await Ocean.getInstance(config) ocean = await Ocean.getInstance(config)
keeper = await Keeper.getInstance() keeper = await Keeper.getInstance()
@ -48,107 +42,161 @@ describe("Register Escrow Access Secret Store Template", () => {
escrowReward = await EscrowReward.getInstance() escrowReward = await EscrowReward.getInstance()
}) })
it("should propose the template", async () => { describe("Propose and approve template", () => {
await keeper.templateStoreManager.proposeTemplate(template.getAddress(), consumer.getId(), true) it("should propose the template", async () => {
// TODO: Use a event to detect template mined await keeper.templateStoreManager.proposeTemplate(template.getAddress(), consumer.getId(), true)
await new Promise(_ => setTimeout(_, 6 * 1000)) // TODO: Use a event to detect template mined
await new Promise(_ => setTimeout(_, 6 * 1000))
})
it("should approve the template", async () => {
await keeper.templateStoreManager.approveTemplate(template.getAddress(), templateManagerOwner.getId(), true)
// TODO: Use a event to detect template mined
await new Promise(_ => setTimeout(_, 6 * 1000))
})
}) })
it("should approve the template", async () => { describe("Full flow", () => {
await keeper.templateStoreManager.approveTemplate(template.getAddress(), templateManagerOwner.getId(), true) const agreementId = `0x${generateId()}`
// TODO: Use a event to detect template mined const did = `0x${generateId()}`
await new Promise(_ => setTimeout(_, 6 * 1000))
let conditionIdAccess: string
let conditionIdLock: string
let conditionIdEscrow: string
it("should register a DID", async () => {
await keeper.didRegistry.registerAttribute(did.replace("0x", ""), checksum, url, publisher.getId())
})
it("should generate the condition IDs", async () => {
conditionIdAccess = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer.getId())
conditionIdLock = await lockRewardCondition.generateIdHash(agreementId, await escrowReward.getAddress(), escrowAmount)
conditionIdEscrow = await escrowReward.generateIdHash(
agreementId,
escrowAmount,
consumer.getId(),
publisher.getId(),
conditionIdLock,
conditionIdAccess,
)
})
it("should have conditions types", async () => {
const conditionTypes = await template.getConditionTypes()
assert.equal(conditionTypes.length, 3, "Expected 3 conditions.")
assert.deepEqual(
[...conditionTypes].sort(),
[accessSecretStoreCondition.getAddress(), escrowReward.getAddress(), lockRewardCondition.getAddress()].sort(),
"The conditions doesn't match",
)
})
it("should have condition instances asociated", async () => {
const conditions = await template.getConditions()
assert.equal(conditions.length, 3, "Expected 3 conditions.")
const conditionClasses = [AccessSecretStoreCondition, EscrowReward, LockRewardCondition]
conditionClasses
.forEach(conditionClass => {
if (!conditions.find(condition => condition instanceof conditionClass)) {
throw `${conditionClass.name} is not part of the conditions.`;
}
})
})
it("should create a new agreement", async () => {
const agreement = await template.createAgreement(
agreementId,
did,
[conditionIdAccess, conditionIdLock, conditionIdEscrow],
[0, 0, 0],
[0, 0, 0],
consumer.getId(),
)
assert.isTrue(agreement.status)
})
it("should not grant the access to the consumer", async () => {
const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
assert.isFalse(accessGranted, "Consumer has been granted.")
})
it("should fulfill LockRewardCondition", async () => {
await consumer.requestTokens(escrowAmount)
await keeper.token.approve(lockRewardCondition.getAddress(), escrowAmount, consumer.getId())
const fulfill = await lockRewardCondition.fulfill(agreementId, escrowReward.getAddress(), escrowAmount, consumer.getId())
assert.isDefined(fulfill.events.Fulfilled, "Not Fulfilled event.")
})
it("should fulfill AccessSecretStoreCondition", async () => {
const fulfill = await accessSecretStoreCondition.fulfill(agreementId, did, consumer.getId(), publisher.getId())
assert.isDefined(fulfill.events.Fulfilled, "Not Fulfilled event.")
})
it("should fulfill EscrowReward", async () => {
const fulfill = await escrowReward.fulfill(
agreementId,
escrowAmount,
consumer.getId(),
publisher.getId(),
conditionIdLock,
conditionIdAccess,
consumer.getId(),
)
assert.isDefined(fulfill.events.Fulfilled, "Not Fulfilled event.")
})
it("should grant the access to the consumer", async () => {
const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
assert.isTrue(accessGranted, "Consumer has not been granted.")
})
}) })
it("should register a DID", async () => { describe("Short flow", () => {
await keeper.didRegistry.registerAttribute(did.replace("0x", ""), checksum, url, publisher.getId()) const did = `0x${generateId()}`
})
it("should generate the condition IDs", async () => { let agreementId
conditionIdAccess = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer.getId())
conditionIdLock = await lockRewardCondition.generateIdHash(agreementId, await escrowReward.getAddress(), escrowAmount)
conditionIdEscrow = await escrowReward.generateIdHash(
agreementId,
escrowAmount,
consumer.getId(),
publisher.getId(),
conditionIdLock,
conditionIdAccess,
)
})
it("should have conditions types", async () => { it("should register a DID", async () => {
const conditionTypes = await template.getConditionTypes() await keeper.didRegistry.registerAttribute(did.replace("0x", ""), checksum, url, publisher.getId())
})
assert.equal(conditionTypes.length, 3, "Expected 3 conditions.") it("should create a new agreement (short way)", async () => {
assert.deepEqual( agreementId = await template.createFullAgreement(did, escrowAmount, consumer.getId())
[...conditionTypes].sort(),
[accessSecretStoreCondition.getAddress(), escrowReward.getAddress(), lockRewardCondition.getAddress()].sort(),
"The conditions doesn't match",
)
})
it("should have condition instances asociated", async () => { assert.match(agreementId, /^0x[a-f0-9]{64}$/i)
const conditions = await template.getConditions() })
assert.equal(conditions.length, 3, "Expected 3 conditions.") it("should not grant the access to the consumer", async () => {
const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
assert.isFalse(accessGranted, "Consumer has been granted.")
})
const conditionClasses = [AccessSecretStoreCondition, EscrowReward, LockRewardCondition] it("should fulfill the conditions from consumer side", async () => {
conditionClasses await ocean.agreements.conditions.lockReward(agreementId, escrowAmount, consumer)
.forEach(conditionClass => { })
if (!conditions.find(condition => condition instanceof conditionClass)) {
throw `${conditionClass.name} is not part of the conditions.`;
}
})
})
it("should create a new agreement", async () => { it("should fulfill the conditions from publisher side", async () => {
const agreement = await template.createAgreement( await ocean.agreements.conditions.grantAccess(agreementId, did, consumer.getId(), publisher)
agreementId, await ocean.agreements.conditions.releaseReward(agreementId, escrowAmount, did, consumer.getId(), publisher.getId(), publisher)
did, })
[conditionIdAccess, conditionIdLock, conditionIdEscrow],
[0, 0, 0],
[0, 0, 0],
consumer.getId(),
)
assert.isTrue(agreement.status) it("should grant the access to the consumer", async () => {
}) const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
it("should fulfill LockRewardCondition", async () => { assert.isTrue(accessGranted, "Consumer has not been granted.")
await consumer.requestTokens(escrowAmount) })
await keeper.token.approve(lockRewardCondition.getAddress(), escrowAmount, consumer.getId())
const fulfill = await lockRewardCondition.fulfill(agreementId, escrowReward.getAddress(), escrowAmount, consumer.getId())
assert.isDefined(fulfill.events.Fulfilled, "Not Fulfilled event.")
})
it("should fulfill AccessSecretStoreCondition", async () => {
const fulfill = await accessSecretStoreCondition.fulfill(agreementId, did, consumer.getId(), publisher.getId())
assert.isDefined(fulfill.events.Fulfilled, "Not Fulfilled event.")
})
it("should fulfill EscrowReward", async () => {
const fulfill = await escrowReward.fulfill(
agreementId,
escrowAmount,
consumer.getId(),
publisher.getId(),
conditionIdLock,
conditionIdAccess,
consumer.getId(),
)
assert.isDefined(fulfill.events.Fulfilled, "Not Fulfilled event.")
})
it("should grant the access to the consumer", async () => {
const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
assert.isTrue(accessGranted, "Consumer has not been granted.")
}) })
}) })

View File

@ -40,10 +40,15 @@ export default abstract class ContractBase {
this.contract = await ContractHandler.get(this.contractName) this.contract = await ContractHandler.get(this.contractName)
} }
protected async sendFrom(name: string, args: any[], from?: string): Promise<TransactionReceipt> { protected async getFromAddress(from?: string): Promise<string> {
if (!from) { if (!from) {
from = (await Web3Provider.getWeb3().eth.getAccounts())[0] from = (await Web3Provider.getWeb3().eth.getAccounts())[0]
} }
return from
}
protected async sendFrom(name: string, args: any[], from?: string): Promise<TransactionReceipt> {
from = await this.getFromAddress(from)
return this.send(name, from, args) return this.send(name, from, args)
} }

View File

@ -13,11 +13,11 @@ export default class DIDRegistry extends ContractBase {
return this.send("registerAttribute", ownerAddress, ["0x" + did, Web3Provider.getWeb3().utils.fromAscii(checksum), value]) return this.send("registerAttribute", ownerAddress, ["0x" + did, Web3Provider.getWeb3().utils.fromAscii(checksum), value])
} }
public async getOwner(did: string): Promise<string> { public async getDIDOwner(did: string): Promise<string> {
return this.call("getOwner", ["0x" + did]) return this.call("getDIDOwner", [did])
} }
public async getUpdateAt(did: string): Promise<number> { public async getBlockNumberUpdated(did: string): Promise<number> {
return +await this.call("getUpdateAt", ["0x" + did]) return +await this.call("getBlockNumberUpdated", [did])
} }
} }

View File

@ -3,7 +3,7 @@ import { Condition } from "./Condition.abstract"
export class AccessSecretStoreCondition extends Condition { export class AccessSecretStoreCondition extends Condition {
public static async getInstance(): Promise<AccessSecretStoreCondition> { public static async getInstance(): Promise<AccessSecretStoreCondition> {
return Condition.getInstance("AccessSecretStoreCondition", AccessSecretStoreCondition) as any return Condition.getInstance("AccessSecretStoreCondition", AccessSecretStoreCondition)
} }
hashValues(did: string, grantee: string) { hashValues(did: string, grantee: string) {

View File

@ -13,7 +13,7 @@ export abstract class Condition extends ContractBase {
super(contractName) super(contractName)
} }
public static async getInstance(conditionName: string, conditionsClass: any): Promise<Condition> { public static async getInstance(conditionName: string, conditionsClass: any): Promise<Condition & any> {
const condition: Condition = new (conditionsClass as any)(conditionName) const condition: Condition = new (conditionsClass as any)(conditionName)
await condition.init() await condition.init()
return condition return condition

View File

@ -8,7 +8,7 @@ export abstract class AgreementTemplate extends ContractBase {
super(contractName) super(contractName)
} }
public static async getInstance(conditionName: string, templateClass: any): Promise<AgreementTemplate> { public static async getInstance(conditionName: string, templateClass: any): Promise<AgreementTemplate & any> {
const condition: AgreementTemplate = new (templateClass as any)(conditionName) const condition: AgreementTemplate = new (templateClass as any)(conditionName)
await condition.init() await condition.init()
return condition return condition

View File

@ -1,4 +1,7 @@
import { AgreementTemplate } from "./AgreementTemplate.abstract" import { AgreementTemplate } from "./AgreementTemplate.abstract"
import { LockRewardCondition, EscrowReward, AccessSecretStoreCondition } from '../conditions'
import DIDRegistry from '../DIDRegistry'
import { generateId } from '../../../utils/GeneratorHelpers'
export class EscrowAccessSecretStoreTemplate extends AgreementTemplate { export class EscrowAccessSecretStoreTemplate extends AgreementTemplate {
@ -6,6 +9,17 @@ export class EscrowAccessSecretStoreTemplate extends AgreementTemplate {
return AgreementTemplate.getInstance("EscrowAccessSecretStoreTemplate", EscrowAccessSecretStoreTemplate) return AgreementTemplate.getInstance("EscrowAccessSecretStoreTemplate", EscrowAccessSecretStoreTemplate)
} }
/**
* Create a agreement using EscrowAccessSecretStoreTemplate.
* @param {string} agreementId Generated agreement ID.
* @param {string} did Asset DID.
* @param {string[]} conditionIds List of conditions IDs.
* @param {number[]} timeLocks Timelocks.
* @param {number[]} timeOuts Timeouts.
* @param {string} accessConsumer Consumer address.
* @param {string} from Action sender.
* @param {any} Transaction receipt.
*/
public createAgreement( public createAgreement(
agreementId: string, agreementId: string,
did: string, did: string,
@ -25,4 +39,45 @@ export class EscrowAccessSecretStoreTemplate extends AgreementTemplate {
from, from,
) )
} }
/**
* Create a agreement using EscrowAccessSecretStoreTemplate using only the most important information.
* @param {string} did Asset DID.
* @param {number} amount Asset price.
* @param {string} from Consumer address.
* @return {Promise<string>} Agreement ID.
*/
public async createFullAgreement(did: string, amount: number, from?: string): Promise<string> {
from = await this.getFromAddress(from)
const didRegistry = await DIDRegistry.getInstance()
const accessSecretStoreCondition = await AccessSecretStoreCondition.getInstance()
const lockRewardCondition = await LockRewardCondition.getInstance()
const escrowReward = await EscrowReward.getInstance()
const agreementId = `0x${generateId()}`
const publisher = await didRegistry.getDIDOwner(did)
const conditionIdAccess = await accessSecretStoreCondition.generateIdHash(agreementId, did, from)
const conditionIdLock = await lockRewardCondition.generateIdHash(agreementId, await escrowReward.getAddress(), amount)
const conditionIdEscrow = await escrowReward.generateIdHash(
agreementId,
amount,
from,
publisher,
conditionIdLock,
conditionIdAccess,
)
await this.createAgreement(
agreementId,
did,
[conditionIdAccess, conditionIdLock, conditionIdEscrow],
[0, 0, 0],
[0, 0, 0],
from,
)
return agreementId
}
} }

View File

@ -21,6 +21,7 @@ import Account from "./Account"
import DID from "./DID" import DID from "./DID"
import ServiceAgreement from "./ServiceAgreements/ServiceAgreement" import ServiceAgreement from "./ServiceAgreements/ServiceAgreement"
import Keeper from "../keeper/Keeper"
import EventListener from "../keeper/EventListener" import EventListener from "../keeper/EventListener"
/** /**
@ -44,6 +45,7 @@ export default class Ocean {
if (!Ocean.instance) { if (!Ocean.instance) {
Ocean.instance = new Ocean() Ocean.instance = new Ocean()
Ocean.instance.keeper = await Keeper.getInstance()
Ocean.instance.accounts = await OceanAccounts.getInstance() Ocean.instance.accounts = await OceanAccounts.getInstance()
Ocean.instance.assets = await OceanAssets.getInstance() Ocean.instance.assets = await OceanAssets.getInstance()
Ocean.instance.agreements = await OceanAgreements.getInstance() Ocean.instance.agreements = await OceanAgreements.getInstance()
@ -60,6 +62,12 @@ export default class Ocean {
*/ */
private static instance: Ocean = null private static instance: Ocean = null
/**
* Keeper instance.
* @type {Keeper}
*/
public keeper: Keeper
/** /**
* Ocean account submodule * Ocean account submodule
* @type {OceanAccounts} * @type {OceanAccounts}

View File

@ -5,6 +5,8 @@ import Account from "./Account"
import DID from "./DID" import DID from "./DID"
import ServiceAgreement from "./ServiceAgreements/ServiceAgreement" import ServiceAgreement from "./ServiceAgreements/ServiceAgreement"
import OceanAgreementsConditions from "./OceanAgreementsConditions"
export interface AgreementPreparionResult { export interface AgreementPreparionResult {
agreementId: string agreementId: string
signature: string signature: string
@ -22,6 +24,7 @@ export default class OceanAgreements {
public static async getInstance(): Promise<OceanAgreements> { public static async getInstance(): Promise<OceanAgreements> {
if (!OceanAgreements.instance) { if (!OceanAgreements.instance) {
OceanAgreements.instance = new OceanAgreements() OceanAgreements.instance = new OceanAgreements()
OceanAgreements.instance.conditions = await OceanAgreementsConditions.getInstance()
} }
return OceanAgreements.instance return OceanAgreements.instance
@ -33,6 +36,12 @@ export default class OceanAgreements {
*/ */
private static instance: OceanAgreements = null private static instance: OceanAgreements = null
/**
* Agreements Conditions submodule.
* @type {OceanAgreementsConditions}
*/
public conditions: OceanAgreementsConditions
/** /**
* Creates a consumer signature for the specified asset service. * Creates a consumer signature for the specified asset service.
* @param {string} did Decentralized ID. * @param {string} did Decentralized ID.

View File

@ -0,0 +1,95 @@
import Keeper from "../keeper/Keeper"
import Account from "./Account"
/**
* Agreements Conditions submodule of Ocean Protocol.
*/
export default class OceanAgreementsConditions {
/**
* Returns the instance of OceanAgreementsConditions.
* @return {Promise<OceanAgreementsConditions>}
*/
public static async getInstance(): Promise<OceanAgreementsConditions> {
if (!OceanAgreementsConditions.instance) {
OceanAgreementsConditions.instance = new OceanAgreementsConditions()
OceanAgreementsConditions.instance.keeper = await Keeper.getInstance()
}
return OceanAgreementsConditions.instance
}
/**
* OceanAgreementsConditions instance.
* @type {OceanAgreementsConditions}
*/
private static instance: OceanAgreementsConditions = null
private keeper: Keeper
/**
* Transfers tokens to the EscrowRewardCondition contract as an escrow payment.
* This is required before access can be given to the asset data.
* @param {string} agreementId Agreement ID.
* @param {number} amount Asset amount.
* @param {Account} from Account of sender.
*/
public async lockReward(agreementId: string, amount: number, from: Account = new Account()) {
const {lockRewardCondition, escrowReward} = this.keeper.conditions
await this.keeper.token.approve(lockRewardCondition.getAddress(), amount, from.getId())
return await lockRewardCondition.fulfill(agreementId, escrowReward.getAddress(), amount, from.getId())
}
/**
* Authorize the consumer defined in the agreement to access (consume) this asset.
* @param {string} agreementId Agreement ID.
* @param {string} did Asset ID.
* @param {string} grantee Consumer address.
* @param {Account} from Account of sender.
*/
public async grantAccess(agreementId: string, did: string, grantee: string, from: Account = new Account()) {
const {accessSecretStoreCondition} = this.keeper.conditions
return await accessSecretStoreCondition.fulfill(agreementId, did, grantee, from.getId())
}
/**
* Transfer the escrow or locked tokens from the LockRewardCondition contract to the publisher's account.
* This should be allowed after access has been given to the consumer and the asset data is downloaded.
*
* If the AccessSecretStoreCondition already timed out, this function will do a refund by transferring
* the token amount to the original consumer.
* @param {string} agreementId Agreement ID.
* @param {number} amount Asset amount.
* @param {string} did Asset ID.
* @param {string} consumer Consumer address.
* @param {string} publisher Publisher address.
* @param {Account} from Account of sender.
*/
public async releaseReward(
agreementId: string,
amount: number,
did: string,
consumer: string,
publisher: string,
from: Account = new Account(),
) {
const {escrowReward, accessSecretStoreCondition, lockRewardCondition} = this.keeper.conditions
const conditionIdAccess = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer)
const conditionIdLock = await lockRewardCondition.generateIdHash(agreementId, await escrowReward.getAddress(), amount)
return await escrowReward.fulfill(
agreementId,
amount,
consumer,
publisher,
conditionIdLock,
conditionIdAccess,
from.getId(),
)
}
}