From 7f5f7606dc96dbfe25863ad769c21bd5fa0808df Mon Sep 17 00:00:00 2001 From: Sebastian Gerske Date: Thu, 18 Oct 2018 13:06:52 +0200 Subject: [PATCH] adapted changes from squid discussion, updated interface definition --- src/keeper/Market.ts | 5 +-- src/ocean/Account.ts | 9 ++--- src/ocean/Asset.ts | 47 -------------------------- src/ocean/Ocean.ts | 5 ++- src/ocean/Order.ts | 68 +++++++++++++++++++++++++++----------- test/ocean/Account.test.ts | 18 ++++++++-- test/ocean/Asset.test.ts | 33 ------------------ test/ocean/Ocean.test.ts | 14 +++++++- test/ocean/Order.test.ts | 17 +++++++++- 9 files changed, 102 insertions(+), 114 deletions(-) diff --git a/src/keeper/Market.ts b/src/keeper/Market.ts index bbf48f6..c1792d1 100644 --- a/src/keeper/Market.ts +++ b/src/keeper/Market.ts @@ -38,9 +38,10 @@ export default class OceanMarket extends ContractWrapperBase { } public async payOrder(order: Order, publisherAddress: string, - price: number, consumerAddress: string): Promise { + price: number, consumerAddress: string, + timeout: number): Promise { return this.sendTransaction("sendPayment", consumerAddress, [ - order.getId(), publisherAddress, price, order.getTimeout(), + order.getId(), publisherAddress, price, timeout, ]) } } diff --git a/src/ocean/Account.ts b/src/ocean/Account.ts index 3837a9e..5339403 100644 --- a/src/ocean/Account.ts +++ b/src/ocean/Account.ts @@ -11,7 +11,7 @@ export default class Account extends OceanBase { return (await Keeper.getInstance()).token.balanceOf(this.id) } - public async getEthBalance(): Promise { + public async getEtherBalance(): Promise { // Logger.log("getting balance for", account); return Web3Provider.getWeb3().eth .getBalance(this.id, "latest") @@ -25,7 +25,7 @@ export default class Account extends OceanBase { if (!this.balance) { this.balance = { - eth: await this.getEthBalance(), + eth: await this.getEtherBalance(), ocn: await this.getOceanBalance(), } as Balance } @@ -34,7 +34,8 @@ export default class Account extends OceanBase { } // Transactions with gas cost - public async requestTokens(amount: number): Promise { - return (await Keeper.getInstance()).market.requestTokens(amount, this.id) + public async requestTokens(amount: number): Promise { + await (await Keeper.getInstance()).market.requestTokens(amount, this.id) + return amount } } diff --git a/src/ocean/Asset.ts b/src/ocean/Asset.ts index c548dfd..5b43f42 100644 --- a/src/ocean/Asset.ts +++ b/src/ocean/Asset.ts @@ -1,10 +1,6 @@ import * as EthCrypto from "eth-crypto" -import * as EthEcies from "eth-ecies" import * as EthjsUtil from "ethereumjs-util" -import * as JWT from "jsonwebtoken" import Keeper from "../keeper/Keeper" -import Web3Provider from "../keeper/Web3Provider" -import ProviderProvider from "../provider/ProviderProvider" import Logger from "../utils/Logger" import Account from "./Account" import OceanBase from "./OceanBase" @@ -19,11 +15,6 @@ export default class Asset extends OceanBase { super() } - public async isActive(): Promise { - const {market} = await Keeper.getInstance() - return market.isAssetActive(this.getId()) - } - public async purchase(consumer: Account, timeout: number): Promise { const {token, market, auth} = await Keeper.getInstance() @@ -62,42 +53,4 @@ export default class Asset extends OceanBase { return order } - public async consume(order: Order, consumer: Account): Promise { - const {auth} = await Keeper.getInstance() - - const encryptedAccessToken = await auth.getEncryptedAccessToken(order.getId(), consumer.getId()) - - // grab the access token from acl contract - const tokenNo0x = encryptedAccessToken.slice(2) - const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex") - - const privateKey = order.getKey().privateKey.slice(2) - const accessTokenEncoded: string = - EthEcies.decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer).toString() - const accessToken = JWT.decode(accessTokenEncoded) // Returns a json object - - if (!accessToken) { - throw new Error(`AccessToken is not an jwt: ${accessTokenEncoded}`) - } - - const signature = Web3Provider.getWeb3().eth.sign(encryptedAccessToken, consumer.getId()) - const encryptedAccessTokenSha3 = Web3Provider.getWeb3().utils.sha3(encryptedAccessToken) - - // Download the data set from the provider using the url in the access token - // decode the access token, grab the service_endpoint, request_id, - - // payload keys: ['consumerId', 'fixed_msg', 'sigEncJWT', 'jwt'] - const payload = JSON.stringify({ - consumerId: consumer.getId(), - fixed_msg: encryptedAccessTokenSha3, - sigEncJWT: signature, - jwt: accessTokenEncoded, - }) - - const accessUrl = await ProviderProvider.getProvider().getAccessUrl(accessToken, payload) - - Logger.log("consume url: ", accessUrl) - - return accessUrl - } } diff --git a/src/ocean/Ocean.ts b/src/ocean/Ocean.ts index c41f117..8798d8e 100644 --- a/src/ocean/Ocean.ts +++ b/src/ocean/Ocean.ts @@ -54,8 +54,8 @@ export default class Ocean { return assetId } - public async getOrdersByConsumer(consumer: Account): Promise { - const {auth, market} = this.keeper + public async getOrdersByAccount(consumer: Account): Promise { + const {auth} = this.keeper Logger.log("Getting orders") @@ -80,7 +80,6 @@ export default class Ocean { null, null) order.setId(returnValues._id) - order.setPaid(await market.verifyOrderPayment(returnValues._id)) return order }), diff --git a/src/ocean/Order.ts b/src/ocean/Order.ts index c321c0d..fbac0c0 100644 --- a/src/ocean/Order.ts +++ b/src/ocean/Order.ts @@ -1,6 +1,9 @@ import * as EthEcies from "eth-ecies" +import * as JWT from "jsonwebtoken" import Keeper from "../keeper/Keeper" +import Web3Provider from "../keeper/Web3Provider" import AccessStatus from "../models/AccessStatus" +import ProviderProvider from "../provider/ProviderProvider" import Logger from "../utils/Logger" import Account from "./Account" import Asset from "./Asset" @@ -8,8 +11,6 @@ import OceanBase from "./OceanBase" export default class Order extends OceanBase { - private paid: boolean - constructor(private asset: Asset, private timeout: number, private pubkey: string, private key: any) { super() @@ -20,33 +21,18 @@ export default class Order extends OceanBase { return auth.getOrderStatus(this.id) } - public setPaid(paid: boolean) { - this.paid = paid - } - - public getPaid() { - return this.paid - } - - public getTimeout() { - return this.timeout - } - - public getKey() { - return this.key - } - public async pay(consumer: Account): Promise { const {market} = await Keeper.getInstance() Logger.log( `Sending payment: ${this.getId()} ${this.asset.publisher.getId()} ${this.asset.price} ${this.timeout}`, ) - const payReceipt = await market.payOrder(this, this.asset.publisher.getId(), this.asset.price, consumer.getId()) + const payReceipt = + await market.payOrder(this, this.asset.publisher.getId(), this.asset.price, consumer.getId(), this.timeout) return payReceipt.events.PaymentReceived.returnValues._paymentId } - public async commit(accessToken: string) { + public async commit(accessToken: string): Promise { const {auth} = await Keeper.getInstance() const commitAccessRequestReceipt = await auth.commitAccessRequest(this, this.asset.publisher.getId()) if (commitAccessRequestReceipt.events.AccessRequestRejected) { @@ -65,5 +51,47 @@ export default class Order extends OceanBase { EthEcies.encrypt(new Buffer(pubKey, "hex"), new Buffer(accessToken)).toString("hex") await auth.deliverAccessToken(this.getId(), `0x${encryptedAccessToken}`, this.asset.publisher.getId()) + + return true } + + public async consume(consumer: Account): Promise { + const {auth} = await Keeper.getInstance() + + const encryptedAccessToken = await auth.getEncryptedAccessToken(this.getId(), consumer.getId()) + + // grab the access token from acl contract + const tokenNo0x = encryptedAccessToken.slice(2) + const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex") + + const privateKey = this.key.privateKey.slice(2) + const accessTokenEncoded: string = + EthEcies.decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer).toString() + const accessToken = JWT.decode(accessTokenEncoded) // Returns a json object + + if (!accessToken) { + throw new Error(`AccessToken is not an jwt: ${accessTokenEncoded}`) + } + + const signature = Web3Provider.getWeb3().eth.sign(encryptedAccessToken, consumer.getId()) + const encryptedAccessTokenSha3 = Web3Provider.getWeb3().utils.sha3(encryptedAccessToken) + + // Download the data set from the provider using the url in the access token + // decode the access token, grab the service_endpoint, request_id, + + // payload keys: ['consumerId', 'fixed_msg', 'sigEncJWT', 'jwt'] + const payload = JSON.stringify({ + consumerId: consumer.getId(), + fixed_msg: encryptedAccessTokenSha3, + sigEncJWT: signature, + jwt: accessTokenEncoded, + }) + + const accessUrl = await ProviderProvider.getProvider().getAccessUrl(accessToken, payload) + + Logger.log("consume url: ", accessUrl) + + return accessUrl + } + } diff --git a/test/ocean/Account.test.ts b/test/ocean/Account.test.ts index 10836d1..6914f05 100644 --- a/test/ocean/Account.test.ts +++ b/test/ocean/Account.test.ts @@ -23,9 +23,9 @@ describe("Account", () => { it("should get initial ocean balance", async () => { - const balance = await accounts[0].getOceanBalance() + const balance = await accounts[8].getOceanBalance() - assert(0 === balance) + assert(0 === balance, `Expected 0 got ${balance}`) }) it("should get the correct balance", async () => { @@ -44,7 +44,7 @@ describe("Account", () => { it("should get initial ether balance", async () => { const account: Account = accounts[9] - const balance = await account.getEthBalance() + const balance = await account.getEtherBalance() const web3 = Web3Provider.getWeb3() assert(Number(web3.utils.toWei("100", "ether")) === balance) @@ -63,4 +63,16 @@ describe("Account", () => { assert(0 === balance.ocn) }) }) + + describe("#requestTokens()", () => { + + it("should return the amount of tokens granted", async () => { + + const tokens = 500 + const account: Account = accounts[0] + const tokensGranted: number = await account.requestTokens(tokens) + + assert(tokensGranted === tokens) + }) + }) }) diff --git a/test/ocean/Asset.test.ts b/test/ocean/Asset.test.ts index cdaf99d..4f9d96c 100644 --- a/test/ocean/Asset.test.ts +++ b/test/ocean/Asset.test.ts @@ -13,7 +13,6 @@ const testName = "Test Asset 2" const testDescription = "This asset is pure owange" const testPrice = 100 const timeout = 100000 -const accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1Mzk3ODcxMDEsImV4cCI6NDcyNjk5NjcwNCwiYXVkIjoiIiwic3ViIjoiIiwic2VydmljZV9lbmRwb2ludCI6Imh0dHA6Ly9hZGFzZCIsInJlc291cmNlX2lkIjoiMTIzNDUifQ.2H3TRC3CAToVE9divSckwHi_HNvgOHKrtJPo8128qrKBHTk7YYb0UNfVCuYqwhGR" let ocean: Ocean let testAsset: Asset @@ -35,22 +34,6 @@ before(async () => { describe("Asset", () => { - describe("#isActive()", () => { - - it("should return true on new asset", async () => { - - const isAssetActive = await testAsset.isActive() - assert(true === isAssetActive) - }) - - it("should return false on unknown asset", async () => { - - const isAssetActive = await new Asset(testName, testDescription, testPrice, testPublisher) - .isActive() - assert(false === isAssetActive) - }) - }) - describe("#purchase()", () => { it("should purchase an asset", async () => { @@ -61,20 +44,4 @@ describe("Asset", () => { assert(order) }) }) - - describe("#consume()", () => { - - it("should consume an asset", async () => { - const consumerAccount = accounts[5] - await consumerAccount.requestTokens(testAsset.price) - // place order - consumer - const order: Order = await testAsset.purchase(consumerAccount, timeout) - // commit order - provider - await order.commit(accessToken) - // pay order - consumer - await order.pay(consumerAccount) - const url = await testAsset.consume(order, consumerAccount) - assert(url) - }) - }) }) diff --git a/test/ocean/Ocean.test.ts b/test/ocean/Ocean.test.ts index 152f42d..fc855ee 100644 --- a/test/ocean/Ocean.test.ts +++ b/test/ocean/Ocean.test.ts @@ -29,6 +29,17 @@ before(async () => { describe("Ocean", () => { + describe("#getInstance()", () => { + + it("should list accounts", async () => { + + const ocn = Ocean.getInstance(config) + + assert(ocn) + }) + + }) + describe("#getAccounts()", () => { it("should list accounts", async () => { @@ -51,6 +62,7 @@ describe("Ocean", () => { assert(assetId.length === 66) assert(assetId.startsWith("0x")) }) + }) describe("#getOrdersByConsumer()", () => { @@ -63,7 +75,7 @@ describe("Ocean", () => { await ocean.register(asset) const order: Order = await asset.purchase(testConsumer, timeout) - const orders = await ocean.getOrdersByConsumer(testConsumer) + const orders = await ocean.getOrdersByAccount(testConsumer) assert(orders.length === 1) assert(orders[0].getId() === order.getId()) diff --git a/test/ocean/Order.test.ts b/test/ocean/Order.test.ts index 7e971e3..8624502 100644 --- a/test/ocean/Order.test.ts +++ b/test/ocean/Order.test.ts @@ -12,7 +12,7 @@ const testName = "Order Test Asset" const testDescription = "This asset is pure owange" const testPrice = 100 const timeout = 1000000 -const accessToken = "eyJhbGciOiJIUzI1" +const accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1Mzk3ODcxMDEsImV4cCI6NDcyNjk5NjcwNCwiYXVkIjoiIiwic3ViIjoiIiwic2VydmljZV9lbmRwb2ludCI6Imh0dHA6Ly9hZGFzZCIsInJlc291cmNlX2lkIjoiMTIzNDUifQ.2H3TRC3CAToVE9divSckwHi_HNvgOHKrtJPo8128qrKBHTk7YYb0UNfVCuYqwhGR" let ocean: Ocean let testAsset: Asset @@ -83,4 +83,19 @@ describe("Order", () => { }) }) + describe("#consume()", () => { + + it("should consume an asset", async () => { + const consumerAccount = accounts[5] + await consumerAccount.requestTokens(testAsset.price) + // place order - consumer + const order: Order = await testAsset.purchase(consumerAccount, timeout) + // commit order - provider + await order.commit(accessToken) + // pay order - consumer + await order.pay(consumerAccount) + const url = await order.consume(consumerAccount) + assert(url) + }) + }) })