├── asset-transfer-typescript ├── .npmrc ├── .gitignore ├── src │ ├── index.ts │ ├── untyped.d.ts │ ├── asset.ts │ └── assetTransfer.ts ├── README.md ├── docker │ └── docker-entrypoint.sh ├── tsconfig.json ├── scripts │ ├── runmf.sh │ └── packagedebug.sh ├── Dockerfile ├── package.json └── .eslintrc.js ├── asset-tx-private-java ├── .gradle │ ├── 6.5.1 │ │ ├── gc.properties │ │ ├── fileChanges │ │ │ └── last-build.bin │ │ ├── fileHashes │ │ │ ├── fileHashes.bin │ │ │ └── fileHashes.lock │ │ ├── javaCompile │ │ │ ├── taskHistory.bin │ │ │ ├── classAnalysis.bin │ │ │ └── javaCompile.lock │ │ ├── fileContent │ │ │ └── fileContent.lock │ │ └── executionHistory │ │ │ ├── executionHistory.bin │ │ │ └── executionHistory.lock │ ├── vcs-1 │ │ └── gc.properties │ ├── buildOutputCleanup │ │ ├── cache.properties │ │ ├── outputFiles.bin │ │ └── buildOutputCleanup.lock │ └── checksums │ │ ├── checksums.lock │ │ ├── md5-checksums.bin │ │ └── sha1-checksums.bin ├── .gitignore ├── src │ ├── test │ │ ├── resources │ │ │ └── mockito-extensions │ │ │ │ └── org.mockito.plugins.MockMaker │ │ └── java │ │ │ └── org │ │ │ └── hyperledger │ │ │ └── fabric │ │ │ └── samples │ │ │ └── privatedata │ │ │ └── AssetTransferTest.java │ └── main │ │ └── java │ │ └── org │ │ └── hyperledger │ │ └── fabric │ │ └── samples │ │ └── privatedata │ │ ├── TransferAgreement.java │ │ ├── AssetPrivateDetails.java │ │ ├── Asset.java │ │ └── AssetTransfer.java ├── settings.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── .gitattributes ├── config │ └── checkstyle │ │ ├── suppressions.xml │ │ └── checkstyle.xml ├── META-INF │ └── statedb │ │ └── couchdb │ │ └── collections │ │ └── assetCollection │ │ └── indexes │ │ └── indexOwner.json ├── justfile ├── docker │ └── docker-entrypoint.sh ├── collections_config.json ├── Dockerfile ├── scripts │ ├── runmf.sh │ └── packagedebug.sh ├── build.gradle ├── gradlew.bat └── gradlew ├── javascript ├── .eslintignore ├── index.js ├── .gitignore ├── .eslintrc.js ├── scripts │ ├── runmf.sh │ └── packagedebug.sh ├── package.json ├── test │ └── assetTransfer.test.js └── lib │ └── chaincode.js ├── .gitignore ├── README.md ├── .github └── workflows │ ├── typescript.yaml │ └── java.yml └── LICENSE /asset-transfer-typescript/.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict=true -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/gc.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/vcs-1/gc.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /asset-tx-private-java/.gitignore: -------------------------------------------------------------------------------- 1 | _cfg 2 | build 3 | bin -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/fileChanges/last-build.bin: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /javascript/.eslintignore: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-License-Identifier: Apache-2.0 3 | # 4 | 5 | coverage 6 | -------------------------------------------------------------------------------- /asset-tx-private-java/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker: -------------------------------------------------------------------------------- 1 | mock-maker-inline 2 | -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/buildOutputCleanup/cache.properties: -------------------------------------------------------------------------------- 1 | #Tue Jan 24 14:48:28 GMT 2023 2 | gradle.version=6.5.1 3 | -------------------------------------------------------------------------------- /asset-tx-private-java/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | rootProject.name = 'private' 6 | -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/checksums/checksums.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/checksums/checksums.lock -------------------------------------------------------------------------------- /asset-tx-private-java/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/checksums/md5-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/checksums/md5-checksums.bin -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/checksums/sha1-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/checksums/sha1-checksums.bin -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/fileHashes/fileHashes.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/6.5.1/fileHashes/fileHashes.bin -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/fileHashes/fileHashes.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/6.5.1/fileHashes/fileHashes.lock -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/javaCompile/taskHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/6.5.1/javaCompile/taskHistory.bin -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/fileContent/fileContent.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/6.5.1/fileContent/fileContent.lock -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/javaCompile/classAnalysis.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/6.5.1/javaCompile/classAnalysis.bin -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/javaCompile/javaCompile.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/6.5.1/javaCompile/javaCompile.lock -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/buildOutputCleanup/outputFiles.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/buildOutputCleanup/outputFiles.bin -------------------------------------------------------------------------------- /asset-tx-private-java/.gitattributes: -------------------------------------------------------------------------------- 1 | # 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | # 4 | # These are explicitly windows files and should use crlf 5 | *.bat text eol=crlf 6 | 7 | -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/executionHistory/executionHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/6.5.1/executionHistory/executionHistory.bin -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/buildOutputCleanup/buildOutputCleanup.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/buildOutputCleanup/buildOutputCleanup.lock -------------------------------------------------------------------------------- /asset-tx-private-java/.gradle/6.5.1/executionHistory/executionHistory.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledgendary/fabric-contract-workflow/main/asset-tx-private-java/.gradle/6.5.1/executionHistory/executionHistory.lock -------------------------------------------------------------------------------- /javascript/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright IBM Corp. All Rights Reserved. 3 | * 4 | * SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | 'use strict'; 8 | 9 | const Chaincode = require('./lib/chaincode'); 10 | 11 | module.exports.contracts = [Chaincode]; 12 | -------------------------------------------------------------------------------- /asset-tx-private-java/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /asset-tx-private-java/config/checkstyle/suppressions.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /asset-tx-private-java/META-INF/statedb/couchdb/collections/assetCollection/indexes/indexOwner.json: -------------------------------------------------------------------------------- 1 | { 2 | "index": { 3 | "fields": [ 4 | "objectType", 5 | "owner" 6 | ] 7 | }, 8 | "ddoc": "indexOwnerDoc", 9 | "name": "indexOwner", 10 | "type": "json" 11 | } 12 | -------------------------------------------------------------------------------- /javascript/.gitignore: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-License-Identifier: Apache-2.0 3 | # 4 | 5 | # Coverage directory used by tools like istanbul 6 | coverage 7 | 8 | # Report cache used by istanbul 9 | .nyc_output 10 | 11 | # Dependency directories 12 | node_modules/ 13 | jspm_packages/ 14 | 15 | package-lock.json 16 | -------------------------------------------------------------------------------- /asset-transfer-typescript/.gitignore: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-License-Identifier: Apache-2.0 3 | # 4 | 5 | 6 | # Coverage directory used by tools like istanbul 7 | coverage 8 | 9 | # Dependency directories 10 | node_modules/ 11 | 12 | # Compiled TypeScript files 13 | dist 14 | 15 | # Files created during workshop run 16 | metadata.json -------------------------------------------------------------------------------- /asset-tx-private-java/justfile: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Ensure all properties are exported as shell env-vars 4 | set export 5 | 6 | # set the current directory, and the location of the test dats 7 | CWDIR := justfile_directory() 8 | 9 | _default: 10 | @just -f {{justfile()}} --list 11 | 12 | microfab: 13 | ./scripts/runmf.sh 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /asset-transfer-typescript/src/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | import { AssetTransferContract } from './assetTransfer'; 6 | 7 | export { AssetTransferContract } from './assetTransfer'; 8 | 9 | export const contracts: any[] = [AssetTransferContract]; // eslint-disable-line @typescript-eslint/no-explicit-any 10 | -------------------------------------------------------------------------------- /asset-transfer-typescript/src/untyped.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'json-stringify-deterministic' { 2 | interface Options { 3 | space?: string; 4 | cycles?: boolean; 5 | replacer?: (k, v) => v; 6 | stringify?: typeof JSON.stringify; 7 | } 8 | 9 | export default function stringify(o: unknown, options?: Options): string; 10 | } 11 | -------------------------------------------------------------------------------- /asset-transfer-typescript/README.md: -------------------------------------------------------------------------------- 1 | ## Typescript 2 | 3 | To develop this chaincode: 4 | 5 | 1. Install as usual with `npm install` 6 | 2. To run the Typescript Build `npm run build` 7 | 3. Only needed initially or if you need to reset 8 | - start Fabric `npm run start:fabric` 9 | - create a deployment package and deploy`npm run package:debug` 10 | 11 | 4. Start the chaincode `npm start` 12 | 5. Debug, quite the running chaincode, `npm run build` & `npm start` 13 | 14 | ### Tutorial 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /asset-tx-private-java/docker/docker-entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | set -euo pipefail 6 | : ${CORE_PEER_TLS_ENABLED:="false"} 7 | : ${DEBUG:="false"} 8 | 9 | if [ "${DEBUG,,}" = "true" ]; then 10 | exec java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0.0.0.0:8000 -jar /chaincode.jar 11 | elif [ "${CORE_PEER_TLS_ENABLED,,}" = "true" ]; then 12 | exec java -jar /chaincode.jar # todo 13 | else 14 | exec java -jar /chaincode.jar 15 | fi 16 | 17 | -------------------------------------------------------------------------------- /asset-transfer-typescript/docker/docker-entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | set -euo pipefail 6 | : ${CORE_PEER_TLS_ENABLED:="false"} 7 | : ${DEBUG:="false"} 8 | 9 | if [ "${DEBUG,,}" = "true" ]; then 10 | npm run start:server-debug 11 | 12 | elif [[ ! -v CHAINCODE_SERVER_ADDRESS ]]; then 13 | npm start -- --peer.address $CORE_PEER_ADDRESS 14 | 15 | elif [ "${CORE_PEER_TLS_ENABLED,,}" = "true" ]; then 16 | npm run start:server 17 | 18 | else 19 | npm run start:server-nontls 20 | fi 21 | 22 | -------------------------------------------------------------------------------- /asset-transfer-typescript/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/tsconfig", 3 | "extends": "@tsconfig/node16/tsconfig.json", 4 | "compilerOptions": { 5 | "experimentalDecorators": true, 6 | "emitDecoratorMetadata": true, 7 | "outDir": "dist", 8 | "declaration": true, 9 | "sourceMap": true, 10 | "noUnusedLocals": true, 11 | "noImplicitReturns": true 12 | }, 13 | "include": [ 14 | "./src/**/*" 15 | ], 16 | "exclude": [ 17 | "./src/**/*.spec.ts" 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /asset-tx-private-java/collections_config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "assetCollection", 4 | "policy": "OR('Org1MSP.member', 'Org2MSP.member')", 5 | "requiredPeerCount": 1, 6 | "maxPeerCount": 1, 7 | "blockToLive":1000000, 8 | "memberOnlyRead": true, 9 | "memberOnlyWrite": true 10 | }, 11 | { 12 | "name": "Org1MSPPrivateCollection", 13 | "policy": "OR('Org1MSP.member')", 14 | "requiredPeerCount": 0, 15 | "maxPeerCount": 1, 16 | "blockToLive":3, 17 | "memberOnlyRead": true, 18 | "memberOnlyWrite": false, 19 | "endorsementPolicy": { 20 | "signaturePolicy": "OR('Org1MSP.member')" 21 | } 22 | }, 23 | { 24 | "name": "Org2MSPPrivateCollection", 25 | "policy": "OR('Org2MSP.member')", 26 | "requiredPeerCount": 0, 27 | "maxPeerCount": 1, 28 | "blockToLive":3, 29 | "memberOnlyRead": true, 30 | "memberOnlyWrite": false, 31 | "endorsementPolicy": { 32 | "signaturePolicy": "OR('Org2MSP.member')" 33 | } 34 | } 35 | ] 36 | -------------------------------------------------------------------------------- /asset-tx-private-java/Dockerfile: -------------------------------------------------------------------------------- 1 | # the first stage 2 | FROM gradle:jdk11-alpine AS GRADLE_BUILD 3 | 4 | # copy the build.gradle and src code to the container 5 | COPY src/ src/ 6 | COPY build.gradle ./ 7 | 8 | # Build and package our code 9 | RUN gradle --no-daemon build shadowJar -x checkstyleMain -x checkstyleTest 10 | 11 | 12 | # the second stage of our build just needs the compiled files 13 | FROM openjdk:11-jre 14 | ARG CC_SERVER_PORT=9999 15 | 16 | # Setup tini to work better handle signals 17 | ENV TINI_VERSION v0.19.0 18 | ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini 19 | RUN chmod +x /tini 20 | 21 | RUN addgroup --system javauser && useradd -g javauser javauser 22 | 23 | # copy only the artifacts we need from the first stage and discard the rest 24 | COPY --chown=javauser:javauser --from=GRADLE_BUILD /home/gradle/build/libs/chaincode.jar /chaincode.jar 25 | COPY --chown=javauser:javauser docker/docker-entrypoint.sh /docker-entrypoint.sh 26 | 27 | ENV PORT $CC_SERVER_PORT 28 | EXPOSE $CC_SERVER_PORT 29 | 30 | USER javauser 31 | ENTRYPOINT [ "/tini", "--", "/docker-entrypoint.sh" ] 32 | -------------------------------------------------------------------------------- /javascript/.eslintrc.js: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | module.exports = { 6 | env: { 7 | node: true, 8 | mocha: true, 9 | es6: true 10 | }, 11 | parserOptions: { 12 | ecmaVersion: 8, 13 | sourceType: 'script' 14 | }, 15 | extends: "eslint:recommended", 16 | rules: { 17 | indent: ['error', 4], 18 | 'linebreak-style': ['error', 'unix'], 19 | quotes: ['error', 'single'], 20 | semi: ['error', 'always'], 21 | 'no-unused-vars': ['error', { args: 'none' }], 22 | 'no-console': 'off', 23 | curly: 'error', 24 | eqeqeq: 'error', 25 | 'no-throw-literal': 'error', 26 | strict: 'error', 27 | 'no-var': 'error', 28 | 'dot-notation': 'error', 29 | 'no-tabs': 'error', 30 | 'no-trailing-spaces': 'error', 31 | 'no-use-before-define': 'error', 32 | 'no-useless-call': 'error', 33 | 'no-with': 'error', 34 | 'operator-linebreak': 'error', 35 | yoda: 'error', 36 | 'quote-props': ['error', 'as-needed'], 37 | 'no-constant-condition': ["error", { "checkLoops": false }] 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /asset-transfer-typescript/src/asset.ts: -------------------------------------------------------------------------------- 1 | /* 2 | SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | import { Object as DataType, Property } from 'fabric-contract-api'; 6 | 7 | @DataType() 8 | export class Asset { 9 | @Property('ID', 'string') 10 | ID = ''; 11 | 12 | @Property('Color', 'string') 13 | Color = ''; 14 | 15 | @Property('Owner', 'string') 16 | Owner = ''; 17 | 18 | @Property('AppraisedValue', 'number') 19 | AppraisedValue = 0; 20 | 21 | @Property('Size', 'number') 22 | Size = 0; 23 | 24 | constructor() { 25 | // Nothing to do 26 | } 27 | 28 | static newInstance(state: Partial = {}): Asset { 29 | return { 30 | ID: assertHasValue(state.ID, 'Missing ID'), 31 | Color: state.Color ?? '', 32 | Size: state.Size ?? 0, 33 | Owner: assertHasValue(state.Owner, 'Missing Owner'), 34 | AppraisedValue: state.AppraisedValue ?? 0, 35 | }; 36 | } 37 | } 38 | 39 | function assertHasValue(value: T | undefined | null, message: string): T { 40 | if (value == undefined || (typeof value === 'string' && value.length === 0)) { 41 | throw new Error(message); 42 | } 43 | 44 | return value; 45 | } 46 | -------------------------------------------------------------------------------- /javascript/scripts/runmf.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e -o pipefail 3 | 4 | DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )"/.. && pwd )" 5 | export CFG="${DIR}/_cfg" 6 | mkdir -p "${CFG}" 7 | 8 | export CFG=$DIR/_cfg 9 | export MICROFAB_CONFIG='{ 10 | "endorsing_organizations":[ 11 | { 12 | "name": "org1" 13 | } 14 | ], 15 | "channels":[ 16 | { 17 | "name": "appchannel", 18 | "endorsing_organizations":[ 19 | "org1" 20 | ] 21 | } 22 | 23 | ], 24 | "capability_level":"V2_0" 25 | }' 26 | 27 | mkdir -p $CFG 28 | echo 29 | echo "Stating microfab...." 30 | 31 | docker kill microfab 1>/dev/null 2>&1 || true 32 | docker run --name microfab -p 8080:8080 --add-host host.docker.internal:host-gateway --rm -d -e MICROFAB_CONFIG="${MICROFAB_CONFIG}" ibmcom/ibp-microfab:0.0.16 33 | sleep 5 34 | 35 | curl -s http://console.127-0-0-1.nip.io:8080/ak/api/v1/components | weft microfab -w $CFG/_wallets -p $CFG/_gateways -m $CFG/_msp -f 36 | cat << EOF > $CFG/org1admin.env 37 | export CORE_PEER_LOCALMSPID=org1MSP 38 | export CORE_PEER_MSPCONFIGPATH=$CFG/_msp/org1/org1admin/msp 39 | export CORE_PEER_ADDRESS=org1peer-api.127-0-0-1.nip.io:8080 40 | export FABRIC_CFG_PATH=$CWDIR/config 41 | export CORE_PEER_CLIENT_CONNTIMEOUT=15s 42 | export CORE_PEER_DELIVERYCLIENT_CONNTIMEOUT=15s 43 | EOF 44 | 45 | echo 46 | echo "To get an peer cli environment run:" 47 | echo 48 | echo "source $(realpath --relative-to=$DIR $CFG)/org1admin.env" 49 | -------------------------------------------------------------------------------- /asset-transfer-typescript/scripts/runmf.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e -o pipefail 3 | 4 | DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )"/.. && pwd )" 5 | export CFG="${DIR}/_cfg" 6 | mkdir -p "${CFG}" 7 | 8 | export CFG=$DIR/_cfg 9 | export MICROFAB_CONFIG='{ 10 | "endorsing_organizations":[ 11 | { 12 | "name": "org1" 13 | } 14 | ], 15 | "channels":[ 16 | { 17 | "name": "appchannel", 18 | "endorsing_organizations":[ 19 | "org1" 20 | ] 21 | } 22 | 23 | ], 24 | "capability_level":"V2_0" 25 | }' 26 | 27 | mkdir -p $CFG 28 | echo 29 | echo "Stating microfab...." 30 | 31 | docker kill microfab 1>/dev/null 2>&1 || true 32 | docker run --name microfab -p 8080:8080 --add-host host.docker.internal:host-gateway --rm -d -e MICROFAB_CONFIG="${MICROFAB_CONFIG}" ibmcom/ibp-microfab:0.0.16 33 | sleep 5 34 | 35 | curl -s http://console.127-0-0-1.nip.io:8080/ak/api/v1/components | weft microfab -w $CFG/_wallets -p $CFG/_gateways -m $CFG/_msp -f 36 | cat << EOF > $CFG/org1admin.env 37 | export CORE_PEER_LOCALMSPID=org1MSP 38 | export CORE_PEER_MSPCONFIGPATH=$CFG/_msp/org1/org1admin/msp 39 | export CORE_PEER_ADDRESS=org1peer-api.127-0-0-1.nip.io:8080 40 | export FABRIC_CFG_PATH=$CWDIR/config 41 | export CORE_PEER_CLIENT_CONNTIMEOUT=15s 42 | export CORE_PEER_DELIVERYCLIENT_CONNTIMEOUT=15s 43 | EOF 44 | 45 | echo 46 | echo "To get an peer cli environment run:" 47 | echo 48 | echo "source $(realpath --relative-to=$DIR $CFG)/org1admin.env" 49 | -------------------------------------------------------------------------------- /asset-tx-private-java/scripts/runmf.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e -o pipefail 3 | 4 | DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )"/.. && pwd )" 5 | export CFG="${DIR}/_cfg" 6 | mkdir -p "${CFG}" 7 | 8 | export CFG=$DIR/_cfg 9 | export MICROFAB_CONFIG='{ 10 | "endorsing_organizations":[ 11 | { 12 | "name": "Org1" 13 | }, 14 | { 15 | "name": "Org2" 16 | } 17 | ], 18 | "channels":[ 19 | { 20 | "name": "mychannel", 21 | "endorsing_organizations":[ 22 | "Org1","Org2" 23 | ] 24 | } 25 | 26 | ], 27 | "capability_level":"V2_0" 28 | }' 29 | 30 | mkdir -p $CFG 31 | echo 32 | echo "Stating microfab...." 33 | 34 | docker kill microfab 1>/dev/null 2>&1 || true 35 | docker run --name microfab -p 8080:8080 --add-host host.docker.internal:host-gateway --rm -d -e MICROFAB_CONFIG="${MICROFAB_CONFIG}" ibmcom/ibp-microfab:0.0.16 36 | sleep 5 37 | 38 | curl -s http://console.127-0-0-1.nip.io:8080/ak/api/v1/components | weft microfab -w $CFG/_wallets -p $CFG/_gateways -m $CFG/_msp -f 39 | cat << EOF > $CFG/org1admin.env 40 | export CORE_PEER_LOCALMSPID=org1MSP 41 | export CORE_PEER_MSPCONFIGPATH=$CFG/_msp/org1/org1admin/msp 42 | export CORE_PEER_ADDRESS=org1peer-api.127-0-0-1.nip.io:8080 43 | export FABRIC_CFG_PATH=$CWDIR/config 44 | export CORE_PEER_CLIENT_CONNTIMEOUT=15s 45 | export CORE_PEER_DELIVERYCLIENT_CONNTIMEOUT=15s 46 | EOF 47 | 48 | echo 49 | echo "To get an peer cli environment run:" 50 | echo 51 | echo "source $(realpath --relative-to=$DIR $CFG)/org1admin.env" 52 | -------------------------------------------------------------------------------- /javascript/scripts/packagedebug.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e -o pipefail 3 | 4 | DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )"/.. && pwd )" 5 | 6 | ASSET_NAME=asset-transfer 7 | CHANNEL=appchannel 8 | 9 | # this is the ip address the peer will use to talk to the CHAINCODE_ID 10 | # remember this is relative from where the peer is running. 11 | export CHAINCODE_SERVER_ADDRESS=host.docker.internal:9999 12 | export CHAINCODE_ID=$(weft chaincode package caas --path . --label asset-transfer --address ${CHAINCODE_SERVER_ADDRESS} --archive asset-transfer.tgz --quiet) 13 | export CORE_PEER_LOCALMSPID=org1MSP 14 | 15 | export CORE_PEER_MSPCONFIGPATH=$DIR/_cfg/_msp/org1/org1admin/msp 16 | export CORE_PEER_ADDRESS=org1peer-api.127-0-0-1.nip.io:8080 17 | export CORE_PEER_CLIENT_CONNTIMEOUT=15s 18 | export CORE_PEER_DELIVERYCLIENT_CONNTIMEOUT=15s 19 | 20 | echo "CHAINCODE_ID=${CHAINCODE_ID}" 21 | 22 | set -x && peer lifecycle chaincode install $ASSET_NAME.tgz && { set +x; } 2>/dev/null 23 | echo 24 | set -x && peer lifecycle chaincode approveformyorg --channelID $CHANNEL --name $ASSET_NAME -v 0 --package-id $CHAINCODE_ID --sequence 1 --connTimeout 15s && { set +x; } 2>/dev/null 25 | echo 26 | set -x && peer lifecycle chaincode commit --channelID $CHANNEL --name $ASSET_NAME -v 0 --sequence 1 --connTimeout 15s && { set +x; } 2>/dev/null 27 | echo 28 | set -x && peer lifecycle chaincode querycommitted --channelID=$CHANNEL && { set +x; } 2>/dev/null 29 | echo 30 | 31 | 32 | cat << CC_EOF >> $DIR/_cfg/org1admin.env 33 | export CHAINCODE_SERVER_ADDRESS=0.0.0.0:9999 34 | export CHAINCODE_ID=${CHAINCODE_ID} 35 | CC_EOF 36 | -------------------------------------------------------------------------------- /asset-transfer-typescript/scripts/packagedebug.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e -o pipefail 3 | 4 | DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )"/.. && pwd )" 5 | 6 | ASSET_NAME=asset-transfer 7 | CHANNEL=appchannel 8 | 9 | # this is the ip address the peer will use to talk to the CHAINCODE_ID 10 | # remember this is relative from where the peer is running. 11 | export CHAINCODE_SERVER_ADDRESS=host.docker.internal:9999 12 | export CHAINCODE_ID=$(weft chaincode package caas --path . --label asset-transfer --address ${CHAINCODE_SERVER_ADDRESS} --archive asset-transfer.tgz --quiet) 13 | export CORE_PEER_LOCALMSPID=org1MSP 14 | 15 | export CORE_PEER_MSPCONFIGPATH=$DIR/_cfg/_msp/org1/org1admin/msp 16 | export CORE_PEER_ADDRESS=org1peer-api.127-0-0-1.nip.io:8080 17 | export CORE_PEER_CLIENT_CONNTIMEOUT=15s 18 | export CORE_PEER_DELIVERYCLIENT_CONNTIMEOUT=15s 19 | 20 | echo "CHAINCODE_ID=${CHAINCODE_ID}" 21 | 22 | set -x && peer lifecycle chaincode install $ASSET_NAME.tgz && { set +x; } 2>/dev/null 23 | echo 24 | set -x && peer lifecycle chaincode approveformyorg --channelID $CHANNEL --name $ASSET_NAME -v 0 --package-id $CHAINCODE_ID --sequence 1 --connTimeout 15s && { set +x; } 2>/dev/null 25 | echo 26 | set -x && peer lifecycle chaincode commit --channelID $CHANNEL --name $ASSET_NAME -v 0 --sequence 1 --connTimeout 15s && { set +x; } 2>/dev/null 27 | echo 28 | set -x && peer lifecycle chaincode querycommitted --channelID=$CHANNEL && { set +x; } 2>/dev/null 29 | echo 30 | 31 | 32 | cat << CC_EOF >> $DIR/_cfg/org1admin.env 33 | export CHAINCODE_SERVER_ADDRESS=0.0.0.0:9999 34 | export CHAINCODE_ID=${CHAINCODE_ID} 35 | CC_EOF 36 | -------------------------------------------------------------------------------- /asset-tx-private-java/src/main/java/org/hyperledger/fabric/samples/privatedata/TransferAgreement.java: -------------------------------------------------------------------------------- 1 | package org.hyperledger.fabric.samples.privatedata; 2 | 3 | import org.hyperledger.fabric.contract.annotation.DataType; 4 | import org.hyperledger.fabric.contract.annotation.Property; 5 | import org.hyperledger.fabric.shim.ChaincodeException; 6 | import org.json.JSONObject; 7 | 8 | import static java.nio.charset.StandardCharsets.UTF_8; 9 | 10 | @DataType() 11 | public final class TransferAgreement { 12 | 13 | @Property() 14 | private final String assetID; 15 | 16 | 17 | @Property() 18 | private String buyerID; 19 | 20 | public String getAssetID() { 21 | return assetID; 22 | } 23 | 24 | public String getBuyerID() { 25 | return buyerID; 26 | } 27 | 28 | public TransferAgreement(final String assetID, 29 | final String buyer) { 30 | this.assetID = assetID; 31 | this.buyerID = buyer; 32 | } 33 | 34 | public byte[] serialize() { 35 | String jsonStr = new JSONObject(this).toString(); 36 | return jsonStr.getBytes(UTF_8); 37 | } 38 | 39 | public static TransferAgreement deserialize(final byte[] assetJSON) { 40 | try { 41 | JSONObject json = new JSONObject(new String(assetJSON, UTF_8)); 42 | final String id = json.getString("assetID"); 43 | final String buyerID = json.getString("buyerID"); 44 | return new TransferAgreement(id, buyerID); 45 | } catch (Exception e) { 46 | throw new ChaincodeException("Deserialize error: " + e.getMessage(), "DATA_ERROR"); 47 | } 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /asset-tx-private-java/src/main/java/org/hyperledger/fabric/samples/privatedata/AssetPrivateDetails.java: -------------------------------------------------------------------------------- 1 | package org.hyperledger.fabric.samples.privatedata; 2 | 3 | import org.hyperledger.fabric.contract.annotation.DataType; 4 | import org.hyperledger.fabric.contract.annotation.Property; 5 | 6 | import org.hyperledger.fabric.shim.ChaincodeException; 7 | import org.json.JSONObject; 8 | 9 | import static java.nio.charset.StandardCharsets.UTF_8; 10 | 11 | @DataType() 12 | public final class AssetPrivateDetails { 13 | 14 | @Property() 15 | private final String assetID; 16 | 17 | @Property() 18 | private int appraisedValue; 19 | 20 | public String getAssetID() { 21 | return assetID; 22 | } 23 | 24 | public int getAppraisedValue() { 25 | return appraisedValue; 26 | } 27 | 28 | public AssetPrivateDetails(final String assetID, 29 | final int appraisedValue) { 30 | this.assetID = assetID; 31 | this.appraisedValue = appraisedValue; 32 | } 33 | 34 | public byte[] serialize() { 35 | String jsonStr = new JSONObject(this).toString(); 36 | return jsonStr.getBytes(UTF_8); 37 | } 38 | 39 | public static AssetPrivateDetails deserialize(final byte[] assetJSON) { 40 | try { 41 | JSONObject json = new JSONObject(new String(assetJSON, UTF_8)); 42 | final String id = json.getString("assetID"); 43 | final int appraisedValue = json.getInt("appraisedValue"); 44 | return new AssetPrivateDetails(id, appraisedValue); 45 | } catch (Exception e) { 46 | throw new ChaincodeException("Deserialize error: " + e.getMessage(), "DATA_ERROR"); 47 | } 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /asset-tx-private-java/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | plugins { 6 | id 'com.github.johnrengelman.shadow' version '5.1.0' 7 | id 'application' 8 | id 'checkstyle' 9 | id 'jacoco' 10 | } 11 | 12 | group 'org.hyperledger.fabric.samples' 13 | version '1.0-SNAPSHOT' 14 | 15 | dependencies { 16 | 17 | implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.5.+' 18 | implementation 'org.json:json:+' 19 | 20 | testImplementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.5.+' 21 | testImplementation 'org.junit.jupiter:junit-jupiter:5.4.2' 22 | testImplementation 'org.assertj:assertj-core:3.11.1' 23 | testImplementation 'org.mockito:mockito-core:2.+' 24 | } 25 | 26 | repositories { 27 | mavenCentral() 28 | maven { 29 | url 'https://jitpack.io' 30 | } 31 | } 32 | 33 | application { 34 | mainClass = 'org.hyperledger.fabric.contract.ContractRouter' 35 | } 36 | 37 | checkstyle { 38 | toolVersion '8.21' 39 | configFile file("config/checkstyle/checkstyle.xml") 40 | } 41 | 42 | checkstyleMain { 43 | source ='src/main/java' 44 | } 45 | 46 | checkstyleTest { 47 | source ='src/test/java' 48 | } 49 | 50 | jacocoTestReport { 51 | dependsOn test 52 | } 53 | 54 | test { 55 | useJUnitPlatform() 56 | testLogging { 57 | events "passed", "skipped", "failed" 58 | } 59 | } 60 | 61 | mainClassName = 'org.hyperledger.fabric.contract.ContractRouter' 62 | 63 | shadowJar { 64 | baseName = 'chaincode' 65 | version = null 66 | classifier = null 67 | 68 | manifest { 69 | attributes 'Main-Class': 'org.hyperledger.fabric.contract.ContractRouter' 70 | } 71 | } 72 | 73 | installDist.dependsOn check -------------------------------------------------------------------------------- /javascript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "asset-transfer-basic", 3 | "version": "1.0.0", 4 | "description": "Asset-Transfer-Basic contract implemented in JavaScript", 5 | "main": "index.js", 6 | "engines": { 7 | "node": ">=12", 8 | "npm": ">=5" 9 | }, 10 | "scripts": { 11 | "lint": "eslint *.js */**.js", 12 | "pretest": "npm run lint", 13 | "test": "nyc mocha --recursive", 14 | "start": "fabric-chaincode-node start", 15 | "package:debug": "./scripts/packagedebug.sh", 16 | "start:fabric": "./scripts/runmf.sh", 17 | "start:server-nontls": "set -x && fabric-chaincode-node server --chaincode-address=$CHAINCODE_SERVER_ADDRESS --chaincode-id=$CHAINCODE_ID" 18 | }, 19 | "engineStrict": true, 20 | "author": "Hyperledger", 21 | "license": "Apache-2.0", 22 | "dependencies": { 23 | "fabric-contract-api": "~2.5.2", 24 | "fabric-shim-api": "~2.5.2", 25 | "fabric-shim": "~2.5.2", 26 | 27 | "json-stringify-deterministic": "^1.0.1", 28 | "sort-keys-recursive": "^2.1.2" 29 | }, 30 | "devDependencies": { 31 | "chai": "^4.1.2", 32 | "eslint": "^4.19.1", 33 | "mocha": "^8.0.1", 34 | "nyc": "^14.1.1", 35 | "sinon": "^6.0.0", 36 | "sinon-chai": "^3.2.0" 37 | }, 38 | "nyc": { 39 | "exclude": [ 40 | "coverage/**", 41 | "test/**", 42 | "index.js", 43 | ".eslintrc.js" 44 | ], 45 | "reporter": [ 46 | "text-summary", 47 | "html" 48 | ], 49 | "all": true, 50 | "check-coverage": true, 51 | "statements": 100, 52 | "branches": 100, 53 | "functions": 100, 54 | "lines": 100 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /asset-transfer-typescript/Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-License-Identifier: Apache-2.0 3 | # 4 | FROM node:16.14 AS builder 5 | 6 | WORKDIR /usr/src/app 7 | 8 | # Copy node.js source and build, changing owner as well 9 | COPY --chown=node:node . /usr/src/app 10 | ENV npm_config_cache=/usr/src/app 11 | RUN npm install 12 | RUN npm run build && npm shrinkwrap 13 | 14 | 15 | FROM node:16.14 as prod-builder 16 | WORKDIR /usr/src/app 17 | COPY --chown=node:node --from=builder /usr/src/app/dist ./dist 18 | COPY --chown=node:node --from=builder /usr/src/app/package.json ./ 19 | COPY --chown=node:node --from=builder /usr/src/app/npm-shrinkwrap.json ./ 20 | RUN npm ci --omit=dev && npm cache clean --force 21 | 22 | # ------------------------------------------------------------------------------ 23 | # Builds the Chaincode as a Service docker version 24 | FROM node:16.14 AS ccaas 25 | WORKDIR /usr/src/app 26 | 27 | ARG TARGETARCH 28 | ARG TARGETOS 29 | 30 | COPY --chown=node:node --from=prod-builder /usr/src/app . 31 | COPY --chown=node:node docker/docker-entrypoint.sh /usr/src/app/docker-entrypoint.sh 32 | 33 | ARG CC_SERVER_PORT 34 | ENV PORT $CC_SERVER_PORT 35 | EXPOSE $CC_SERVER_PORT 36 | 37 | ENV TINI_VERSION=v0.19.0 38 | ENV PLATFORM=${TARGETARCH} 39 | ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini-${PLATFORM} /tini 40 | RUN chmod +x /tini 41 | 42 | ENV NODE_ENV=production 43 | USER node 44 | ENTRYPOINT [ "/tini", "--", "/usr/src/app/docker-entrypoint.sh" ] 45 | 46 | 47 | 48 | # ------------------------------------------------------------------------------ 49 | # Builds the chaincode for the k8s builder 50 | FROM node:16.14 AS k8s 51 | WORKDIR /usr/src/app 52 | 53 | ARG TARGETARCH 54 | ARG TARGETOS 55 | 56 | COPY --chown=node:node --from=prod-builder /usr/src/app . 57 | COPY --chown=node:node docker/docker-entrypoint.sh /usr/src/app/docker-entrypoint.sh 58 | 59 | RUN printenv 60 | 61 | ENV TINI_VERSION=v0.19.0 62 | ENV PLATFORM=${TARGETARCH} 63 | ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini-${PLATFORM} /tini 64 | RUN chmod +x /tini 65 | 66 | ENV NODE_ENV=production 67 | USER node 68 | ENTRYPOINT [ "/tini", "--", "/usr/src/app/docker-entrypoint.sh" ] 69 | 70 | -------------------------------------------------------------------------------- /asset-tx-private-java/scripts/packagedebug.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e -o pipefail 3 | 4 | DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )"/.. && pwd )" 5 | 6 | ASSET_NAME=asset-private-transfer 7 | CHANNEL=mychannel 8 | 9 | # this is the ip address the peer will use to talk to the CHAINCODE_ID 10 | # remember this is relative from where the peer is running. 11 | export CHAINCODE_SERVER_ADDRESS=host.docker.internal:9999 12 | CHAINCODE_ID=$(weft chaincode package caas --path . --label asset-private-transfer --address ${CHAINCODE_SERVER_ADDRESS} --archive asset-private-transfer-org1.tgz --quiet) 13 | export CHAINCODE_ID 14 | 15 | export CORE_PEER_LOCALMSPID=Org1MSP 16 | export CORE_PEER_MSPCONFIGPATH=$DIR/_cfg/_msp/Org1/org1admin/msp 17 | export CORE_PEER_ADDRESS=org1peer-api.127-0-0-1.nip.io:8080 18 | 19 | export CORE_PEER_CLIENT_CONNTIMEOUT=15s 20 | export CORE_PEER_DELIVERYCLIENT_CONNTIMEOUT=15s 21 | 22 | echo "CHAINCODE_ID=${CHAINCODE_ID}" 23 | 24 | set -x && peer lifecycle chaincode install asset-private-transfer-org1.tgz && { set +x; } 2>/dev/null 25 | echo 26 | set -x && peer lifecycle chaincode approveformyorg --channelID $CHANNEL --name $ASSET_NAME -v 0 --package-id $CHAINCODE_ID --sequence 1 --connTimeout 15s --collections-config collections_config.json && { set +x; } 2>/dev/null 27 | echo 28 | 29 | export CORE_PEER_LOCALMSPID=Org2MSP 30 | export CORE_PEER_MSPCONFIGPATH=$DIR/_cfg/_msp/Org2/org2admin/msp 31 | export CORE_PEER_ADDRESS=org2peer-api.127-0-0-1.nip.io:8080 32 | 33 | export CHAINCODE_SERVER_ADDRESS=host.docker.internal:9990 34 | CHAINCODE_ID=$(weft chaincode package caas --path . --label asset-private-transfer --address ${CHAINCODE_SERVER_ADDRESS} --archive asset-private-transfer-org2.tgz --quiet) 35 | export CHAINCODE_ID 36 | 37 | set -x && peer lifecycle chaincode install asset-private-transfer-org2.tgz && { set +x; } 2>/dev/null 38 | echo 39 | set -x && peer lifecycle chaincode approveformyorg --channelID $CHANNEL --name $ASSET_NAME -v 0 --package-id $CHAINCODE_ID --sequence 1 --connTimeout 15s --collections-config collections_config.json && { set +x; } 2>/dev/null 40 | echo 41 | 42 | 43 | set -x && peer lifecycle chaincode commit --channelID $CHANNEL --name $ASSET_NAME -v 0 --sequence 1 --collections-config collections_config.json --connTimeout 15s && { set +x; } 2>/dev/null 44 | echo 45 | set -x && peer lifecycle chaincode querycommitted --channelID=$CHANNEL && { set +x; } 2>/dev/null 46 | echo 47 | 48 | 49 | cat << CC_EOF >> $DIR/_cfg/org1admin.env 50 | export CHAINCODE_SERVER_ADDRESS=0.0.0.0:9999 51 | export CHAINCODE_ID=${CHAINCODE_ID} 52 | CC_EOF 53 | 54 | cat << CC_EOF >> $DIR/_cfg/org2admin.env 55 | export CHAINCODE_SERVER_ADDRESS=0.0.0.0:9990 56 | export CHAINCODE_ID=${CHAINCODE_ID} 57 | CC_EOF -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fabric-contract-workflow 2 | An example of how to build Hyperledger Smart Contracts in GitHub Actions 3 | 4 | - Smart Contract is a copy of the one used in the full stack application sample 5 | - It's built in GithubActions and pushed to the github repository 6 | 7 | Each organization's Fabric Deployment Workflow would then pull in new versions of this packaged Smart Contract to run as needed 8 | Typically you would follow these steps. 9 | 10 | 1. Make change to the implementation 11 | 2. Make a PR to update the main branch, compile and tests run 12 | 3. Create a new tag & release. 13 | 14 | This will trigger the publish build that will create the docker image, and push assets to the release notes. 15 | 16 | 4. The **'gitops'** repo that manages your Fabric Infrastructure can then pick up the updated code 17 | ## Workflow Overview 18 | 19 | Each workflow has the same basic structure 20 | 21 | - _build_ the code as needed and run any unit tests. 22 | 23 | Use standard build and test tools per you choice of language and approach. Typically for unit testing you would create some mock objects that represent the functions in the chaincode API 24 | 25 | - _publishdocker_ create the docker image for use with the Fabric K8S Builder 26 | 27 | The docker image to use for running in K8S. This will be pushed to the ghcr.io registry in this example; but could be pushed to other repositories as needed. Remember that the chaincode package needs a reference to the *digest* of the docker image. This is only available when the image is push to a repository. If you move the image to another repoisitory check if the digest has been changed. If it has then the chaincode package will need to be updated. 28 | 29 | This step would really only run when a release was tagged. 30 | 31 | - _package_ create the Chaincode Package for instaling to a peer. In the case the K8S Builder this will be information about the docker iamge to use 32 | 33 | `*tgz` file added to the release assets 34 | 35 | This step would really only run when a release was tagged. 36 | 37 | _ _collections-config.json_ added to the release assets as well 38 | 39 | This step would really only run when a release was tagged. 40 | 41 | ## Packaging Chaincode 42 | The chaincode page is at `tgz` file with a few specific files. Easy to create, but there is a github action specifically for this. For example. 43 | 44 | ``` 45 | - name: Create package 46 | uses: hyperledgendary/package-k8s-chaincode-action@ba10aea43e3d4f7991116527faf96e3c2b07abc7 47 | with: 48 | chaincode-label: ${{ env.chaincode-label }} 49 | chaincode-image: ${{ env.docker-registry }}/${{ github.repository_owner }}/${{ env.image-name }} 50 | chaincode-digest: ${{ needs.publishdocker.outputs.image_digest }} 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /asset-transfer-typescript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "asset-transfer", 3 | "version": "1.0.0", 4 | "description": "Asset Transfer contract implemented in TypeScript", 5 | "main": "dist/index.js", 6 | "typings": "dist/index.d.ts", 7 | "engines": { 8 | "node": ">=14" 9 | }, 10 | "scripts": { 11 | "lint": "eslint ./src --ext .ts", 12 | "pretest": "npm run lint", 13 | "test": "", 14 | "start": "set -x && fabric-chaincode-node start", 15 | "build": "tsc", 16 | "build:watch": "tsc -w", 17 | "prepublishOnly": "npm run build", 18 | "metadata": "set -x && fabric-chaincode-node metadata generate --file metadata.json", 19 | "docker": "docker build -f ./Dockerfile -t asset-transfer-basic .", 20 | "package:caas": "npm run build && weft chaincode package caas --path . --label asset-transfer --address ${CHAINCODE_SERVER_ADDRESS} --archive asset-transfer-caas.tgz --quiet", 21 | "package:k8s": "npm run build && weft chaincode package caas --path . --label asset-transfer --address ${CHAINCODE_SERVER_ADDRESS} --archive asset-transfer-caas.tgz --quiet", 22 | "package:debug": "./scripts/packagedebug.sh", 23 | "start:fabric": "./scripts/runmf.sh", 24 | "start:server-nontls": "set -x && fabric-chaincode-node server --chaincode-address=$CHAINCODE_SERVER_ADDRESS --chaincode-id=$CHAINCODE_ID", 25 | "start:server-debug": "set -x && NODE_OPTIONS='--inspect=0.0.0.0:9229' fabric-chaincode-node server --chaincode-address=$CHAINCODE_SERVER_ADDRESS --chaincode-id=$CHAINCODE_ID", 26 | "start:server": "set -x && fabric-chaincode-node server --chaincode-address=$CHAINCODE_SERVER_ADDRESS --chaincode-id=$CHAINCODE_ID --chaincode-tls-key-file=/hyperledger/privatekey.pem --chaincode-tls-client-cacert-file=/hyperledger/rootcert.pem --chaincode-tls-cert-file=/hyperledger/cert.pem" 27 | }, 28 | "author": "Hyperledger", 29 | "license": "Apache-2.0", 30 | "dependencies": { 31 | "fabric-contract-api": "~2.5.2", 32 | "fabric-ledger": "~2.5.2", 33 | "fabric-shim": "~2.5.2", 34 | "fabric-shim-api": "~2.5.2", 35 | "json-stringify-deterministic": "^1.0.7", 36 | "sort-keys-recursive": "^2.1.7" 37 | }, 38 | "devDependencies": { 39 | "@tsconfig/node16": "^1.0.3", 40 | "@types/node": "^16.11.46", 41 | "@typescript-eslint/eslint-plugin": "^5.30.7", 42 | "@typescript-eslint/parser": "^5.30.7", 43 | "eslint": "^8.20.0", 44 | "typescript": "~4.7.4" 45 | }, 46 | "nyc": { 47 | "extension": [ 48 | ".ts", 49 | ".tsx" 50 | ], 51 | "exclude": [ 52 | "coverage/**", 53 | "dist/**" 54 | ], 55 | "reporter": [ 56 | "text-summary", 57 | "html" 58 | ], 59 | "all": true, 60 | "check-coverage": true, 61 | "statements": 100, 62 | "branches": 100, 63 | "functions": 100, 64 | "lines": 100 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /asset-tx-private-java/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /asset-transfer-typescript/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | node: true, 4 | es2021: true, 5 | }, 6 | extends: [ 7 | 'eslint:recommended', 8 | ], 9 | root: true, 10 | ignorePatterns: [ 11 | 'dist/', 12 | ], 13 | rules: { 14 | 'arrow-spacing': ['error'], 15 | 'comma-style': ['error'], 16 | complexity: ['error', 10], 17 | 'eol-last': ['error'], 18 | 'generator-star-spacing': ['error', 'after'], 19 | 'key-spacing': [ 20 | 'error', 21 | { 22 | beforeColon: false, 23 | afterColon: true, 24 | mode: 'minimum', 25 | }, 26 | ], 27 | 'keyword-spacing': ['error'], 28 | 'no-multiple-empty-lines': ['error'], 29 | 'no-trailing-spaces': ['error'], 30 | 'no-whitespace-before-property': ['error'], 31 | 'object-curly-newline': ['error'], 32 | 'padded-blocks': ['error', 'never'], 33 | 'rest-spread-spacing': ['error'], 34 | 'semi-style': ['error'], 35 | 'space-before-blocks': ['error'], 36 | 'space-in-parens': ['error'], 37 | 'space-unary-ops': ['error'], 38 | 'spaced-comment': ['error'], 39 | 'template-curly-spacing': ['error'], 40 | 'yield-star-spacing': ['error', 'after'], 41 | }, 42 | overrides: [ 43 | { 44 | files: [ 45 | '**/*.ts', 46 | ], 47 | parser: '@typescript-eslint/parser', 48 | parserOptions: { 49 | sourceType: 'module', 50 | ecmaFeatures: { 51 | impliedStrict: true, 52 | }, 53 | project: './tsconfig.json', 54 | tsconfigRootDir: process.env.TSCONFIG_ROOT_DIR || __dirname, 55 | }, 56 | plugins: [ 57 | '@typescript-eslint', 58 | ], 59 | extends: [ 60 | 'eslint:recommended', 61 | 'plugin:@typescript-eslint/recommended', 62 | 'plugin:@typescript-eslint/recommended-requiring-type-checking', 63 | ], 64 | rules: { 65 | '@typescript-eslint/comma-spacing': ['error'], 66 | '@typescript-eslint/explicit-function-return-type': [ 67 | 'error', 68 | { 69 | allowExpressions: true, 70 | }, 71 | ], 72 | '@typescript-eslint/func-call-spacing': ['error'], 73 | '@typescript-eslint/member-delimiter-style': ['error'], 74 | '@typescript-eslint/indent': [ 75 | 'error', 76 | 4, 77 | { 78 | SwitchCase: 0, 79 | ignoredNodes: ["PropertyDefinition"] 80 | }, 81 | ], 82 | 83 | '@typescript-eslint/prefer-nullish-coalescing': ['error'], 84 | '@typescript-eslint/prefer-optional-chain': ['error'], 85 | '@typescript-eslint/prefer-reduce-type-parameter': ['error'], 86 | '@typescript-eslint/prefer-return-this-type': ['error'], 87 | '@typescript-eslint/quotes': ['error', 'single'], 88 | '@typescript-eslint/type-annotation-spacing': ['error'], 89 | '@typescript-eslint/semi': ['error'], 90 | '@typescript-eslint/space-before-function-paren': [ 91 | 'error', 92 | { 93 | anonymous: 'never', 94 | named: 'never', 95 | asyncArrow: 'always', 96 | }, 97 | ], 98 | }, 99 | }, 100 | ], 101 | }; -------------------------------------------------------------------------------- /asset-tx-private-java/src/main/java/org/hyperledger/fabric/samples/privatedata/Asset.java: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | package org.hyperledger.fabric.samples.privatedata; 6 | 7 | import java.util.Objects; 8 | 9 | import static java.nio.charset.StandardCharsets.UTF_8; 10 | 11 | import org.hyperledger.fabric.contract.annotation.DataType; 12 | import org.hyperledger.fabric.contract.annotation.Property; 13 | 14 | import org.hyperledger.fabric.shim.ChaincodeException; 15 | import org.json.JSONObject; 16 | 17 | @DataType() 18 | public final class Asset { 19 | 20 | @Property() 21 | private final String assetID; 22 | 23 | @Property() 24 | private final String objectType; 25 | 26 | @Property() 27 | private final String color; 28 | 29 | @Property() 30 | private final int size; 31 | 32 | @Property() 33 | private String owner; 34 | 35 | public String getAssetID() { 36 | return assetID; 37 | } 38 | 39 | public String getColor() { 40 | return color; 41 | } 42 | 43 | public int getSize() { 44 | return size; 45 | } 46 | 47 | public String getOwner() { 48 | return owner; 49 | } 50 | 51 | public String getObjectType() { 52 | return objectType; 53 | } 54 | 55 | public void setOwner(final String newowner) { 56 | owner = newowner; 57 | } 58 | 59 | public Asset(final String type, 60 | final String assetID, final String color, 61 | final int size, final String owner) { 62 | this.objectType = type; 63 | this.assetID = assetID; 64 | this.color = color; 65 | this.size = size; 66 | this.owner = owner; 67 | } 68 | 69 | public byte[] serialize() { 70 | String jsonStr = new JSONObject(this).toString(); 71 | return jsonStr.getBytes(UTF_8); 72 | } 73 | 74 | public static Asset deserialize(final byte[] assetJSON) { 75 | return deserialize(new String(assetJSON, UTF_8)); 76 | } 77 | 78 | public static Asset deserialize(final String assetJSON) { 79 | try { 80 | JSONObject json = new JSONObject(assetJSON); 81 | final String id = json.getString("assetID"); 82 | final String type = json.getString("objectType"); 83 | final String color = json.getString("color"); 84 | final String owner = json.getString("owner"); 85 | final int size = json.getInt("size"); 86 | return new Asset(type, id, color, size, owner); 87 | } catch (Exception e) { 88 | throw new ChaincodeException("Deserialize error: " + e.getMessage(), "DATA_ERROR"); 89 | } 90 | } 91 | 92 | @Override 93 | public boolean equals(final Object obj) { 94 | if (this == obj) { 95 | return true; 96 | } 97 | 98 | if ((obj == null) || (getClass() != obj.getClass())) { 99 | return false; 100 | } 101 | 102 | Asset other = (Asset) obj; 103 | 104 | return Objects.deepEquals( 105 | new String[]{getAssetID(), getColor(), getOwner()}, 106 | new String[]{other.getAssetID(), other.getColor(), other.getOwner()}) 107 | && 108 | Objects.deepEquals( 109 | new int[]{getSize()}, 110 | new int[]{other.getSize()}); 111 | } 112 | 113 | @Override 114 | public int hashCode() { 115 | return Objects.hash(getObjectType(), getAssetID(), getColor(), getSize(), getOwner()); 116 | } 117 | 118 | @Override 119 | public String toString() { 120 | return this.getClass().getSimpleName() + "@" + Integer.toHexString(hashCode()) 121 | + " [assetID=" + assetID + ", type=" + objectType + ", color=" 122 | + color + ", size=" + size + ", owner=" + owner + "]"; 123 | } 124 | 125 | 126 | } 127 | -------------------------------------------------------------------------------- /.github/workflows/typescript.yaml: -------------------------------------------------------------------------------- 1 | name: Typescript Contract 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | workflow_dispatch: 9 | create: 10 | tags: 11 | - "v2.*" 12 | 13 | # label should be RFC 1123 lowercase - and . 14 | env: 15 | chaincode-label: assettxts 16 | image-name: assettx 17 | docker-registry: ghcr.io 18 | 19 | jobs: 20 | build: 21 | runs-on: ubuntu-latest 22 | defaults: 23 | run: 24 | shell: bash 25 | working-directory: asset-transfer-typescript 26 | 27 | strategy: 28 | matrix: 29 | node-version: [16.x] 30 | 31 | steps: 32 | - uses: actions/checkout@v3 33 | - name: Use Node.js ${{ matrix.node-version }} 34 | uses: actions/setup-node@v3 35 | with: 36 | node-version: ${{ matrix.node-version }} 37 | - run: npm ci 38 | - run: npm run build --if-present 39 | - run: npm test 40 | 41 | publishdocker: 42 | runs-on: ubuntu-20.04 43 | needs: [build] 44 | permissions: 45 | contents: read 46 | packages: write 47 | outputs: 48 | image_digest: ${{ steps.push.outputs.digest }} 49 | steps: 50 | - name: Set up QEMU 51 | uses: docker/setup-qemu-action@v2 52 | 53 | - name: Set up Docker Buildx 54 | uses: docker/setup-buildx-action@v2 55 | with: 56 | buildkitd-flags: --debug 57 | config-inline: | 58 | [worker.oci] 59 | max-parallelism = 1 60 | - name: Checkout 61 | uses: actions/checkout@v3 62 | 63 | - name: Login to the ${{ env.docker-registry }} Container Registry 64 | uses: docker/login-action@v2 65 | with: 66 | registry: ${{ env.docker-registry }} 67 | username: ${{ env.docker-registry == 'docker.io' && secrets.DOCKERHUB_USERNAME || github.actor }} 68 | password: ${{ env.docker-registry == 'docker.io' && secrets.DOCKERHUB_TOKEN || secrets.GITHUB_TOKEN }} 69 | 70 | - name: Docker meta 71 | id: meta 72 | uses: docker/metadata-action@v4 73 | with: 74 | images: ${{ env.docker-registry }}/${{ github.repository_owner }}/${{ env.image-name }} 75 | tags: | 76 | type=semver,pattern={{version}} 77 | type=semver,pattern={{major}}.{{minor}} 78 | type=semver,pattern={{major}}.{{minor}}.{{patch}} 79 | type=sha 80 | - name: Build and push ${{ matrix.COMPONENT }} Image 81 | id: push 82 | uses: docker/build-push-action@v3 83 | with: 84 | platforms: linux/amd64 85 | file: asset-transfer-typescript/Dockerfile 86 | context: asset-transfer-typescript 87 | tags: ${{ steps.meta.outputs.tags }} 88 | push: ${{ github.event_name != 'pull_request' }} 89 | labels: ${{ steps.meta.outputs.labels }} 90 | 91 | 92 | package: 93 | needs: [build,publishdocker] 94 | runs-on: ubuntu-latest 95 | defaults: 96 | run: 97 | shell: bash 98 | steps: 99 | - name: Checkout 100 | uses: actions/checkout@v3 101 | 102 | - name: Create package 103 | uses: hyperledgendary/package-k8s-chaincode-action@ba10aea43e3d4f7991116527faf96e3c2b07abc7 104 | with: 105 | chaincode-label: ${{ env.chaincode-label }} 106 | chaincode-image: ${{ env.docker-registry }}/${{ github.repository_owner }}/${{ env.image-name }} 107 | chaincode-digest: ${{ needs.publishdocker.outputs.image_digest }} 108 | 109 | - name: --debug 110 | run: | 111 | ls -lart 112 | 113 | - name: Rename package 114 | if: startsWith(github.ref, 'refs/tags/v') 115 | run: mv ${CHAINCODE_LABEL}.tgz ${CHAINCODE_LABEL}-${CHAINCODE_VERSION}.tgz 116 | env: 117 | CHAINCODE_LABEL: ${{ env.chaincode-label }} 118 | CHAINCODE_VERSION: ${{ github.ref_name }} 119 | 120 | - name: Upload package 121 | run: gh release upload $GITHUB_REF_NAME ${CHAINCODE_LABEL}-${CHAINCODE_VERSION}.tgz 122 | if: startsWith(github.ref, 'refs/tags/v') 123 | env: 124 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 125 | CHAINCODE_LABEL: ${{ env.chaincode-label }} 126 | CHAINCODE_VERSION: ${{ github.ref_name }} 127 | -------------------------------------------------------------------------------- /.github/workflows/java.yml: -------------------------------------------------------------------------------- 1 | name: Java Contract 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | workflow_dispatch: 9 | create: 10 | tags: 11 | - "v2.*" 12 | 13 | # label should be RFC 1123 lowercase - and . 14 | env: 15 | chaincode-label: assettxprivate-java 16 | image-name: assettxprivate 17 | docker-registry: ghcr.io 18 | 19 | jobs: 20 | build: 21 | runs-on: ubuntu-latest 22 | defaults: 23 | run: 24 | shell: bash 25 | working-directory: asset-tx-private-java 26 | 27 | steps: 28 | - uses: actions/checkout@v3 29 | - uses: actions/setup-java@v3 30 | with: 31 | distribution: 'temurin' 32 | java-version: '11' 33 | cache: 'gradle' 34 | - name: Validate Gradle wrapper 35 | uses: gradle/wrapper-validation-action@v1.0.5 36 | - name: Build and Unit test 37 | uses: gradle/gradle-build-action@v2.3.3 38 | with: 39 | build-root-directory: asset-tx-private-java 40 | arguments: | 41 | build shadowJar 42 | 43 | publishdocker: 44 | runs-on: ubuntu-20.04 45 | needs: [build] 46 | permissions: 47 | contents: read 48 | packages: write 49 | outputs: 50 | image_digest: ${{ steps.push.outputs.digest }} 51 | steps: 52 | - name: Set up QEMU 53 | uses: docker/setup-qemu-action@v2 54 | 55 | - name: Set up Docker Buildx 56 | uses: docker/setup-buildx-action@v2 57 | with: 58 | buildkitd-flags: --debug 59 | config-inline: | 60 | [worker.oci] 61 | max-parallelism = 1 62 | - name: Checkout 63 | uses: actions/checkout@v3 64 | 65 | - name: Login to the ${{ env.docker-registry }} Container Registry 66 | uses: docker/login-action@v2 67 | with: 68 | registry: ${{ env.docker-registry }} 69 | username: ${{ env.docker-registry == 'docker.io' && secrets.DOCKERHUB_USERNAME || github.actor }} 70 | password: ${{ env.docker-registry == 'docker.io' && secrets.DOCKERHUB_TOKEN || secrets.GITHUB_TOKEN }} 71 | 72 | - name: Docker meta 73 | id: meta 74 | uses: docker/metadata-action@v4 75 | with: 76 | images: ${{ env.docker-registry }}/${{ github.repository_owner }}/${{ env.image-name }} 77 | tags: | 78 | type=semver,pattern={{version}} 79 | type=semver,pattern={{major}}.{{minor}} 80 | type=semver,pattern={{major}}.{{minor}}.{{patch}} 81 | type=sha 82 | - name: Build and push ${{ matrix.COMPONENT }} Image 83 | id: push 84 | uses: docker/build-push-action@v3 85 | with: 86 | platforms: linux/amd64 87 | file: asset-tx-private-java/Dockerfile 88 | context: asset-tx-private-java 89 | tags: ${{ steps.meta.outputs.tags }} 90 | push: ${{ github.event_name != 'pull_request' }} 91 | labels: ${{ steps.meta.outputs.labels }} 92 | 93 | 94 | package: 95 | needs: [build,publishdocker] 96 | runs-on: ubuntu-latest 97 | defaults: 98 | run: 99 | shell: bash 100 | steps: 101 | - name: Checkout 102 | uses: actions/checkout@v3 103 | 104 | - name: Create package 105 | uses: hyperledgendary/package-k8s-chaincode-action@ba10aea43e3d4f7991116527faf96e3c2b07abc7 106 | with: 107 | chaincode-label: ${{ env.chaincode-label }} 108 | chaincode-image: ${{ env.docker-registry }}/${{ github.repository_owner }}/${{ env.image-name }} 109 | chaincode-digest: ${{ needs.publishdocker.outputs.image_digest }} 110 | 111 | - name: --debug 112 | run: | 113 | ls -lart 114 | 115 | - name: Rename package 116 | if: startsWith(github.ref, 'refs/tags/v') 117 | run: mv ${CHAINCODE_LABEL}.tgz ${CHAINCODE_LABEL}-${CHAINCODE_VERSION}.tgz 118 | env: 119 | CHAINCODE_LABEL: ${{ env.chaincode-label }} 120 | CHAINCODE_VERSION: ${{ github.ref_name }} 121 | 122 | - name: Upload chaincode package 123 | run: gh release upload $GITHUB_REF_NAME ${CHAINCODE_LABEL}-${CHAINCODE_VERSION}.tgz 124 | if: startsWith(github.ref, 'refs/tags/v') 125 | env: 126 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 127 | CHAINCODE_LABEL: ${{ env.chaincode-label }} 128 | CHAINCODE_VERSION: ${{ github.ref_name }} 129 | 130 | - name: Upload Collections Configuration 131 | run: gh release upload $GITHUB_REF_NAME asset-tx-private-java/collections_config.json 132 | if: startsWith(github.ref, 'refs/tags/v') 133 | env: 134 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 135 | 136 | -------------------------------------------------------------------------------- /asset-tx-private-java/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=$((i+1)) 158 | done 159 | case $i in 160 | (0) set -- ;; 161 | (1) set -- "$args0" ;; 162 | (2) set -- "$args0" "$args1" ;; 163 | (3) set -- "$args0" "$args1" "$args2" ;; 164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=$(save "$@") 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 185 | cd "$(dirname "$0")" 186 | fi 187 | 188 | exec "$JAVACMD" "$@" 189 | -------------------------------------------------------------------------------- /asset-tx-private-java/config/checkstyle/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 20 | 21 | 22 | 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 | -------------------------------------------------------------------------------- /asset-tx-private-java/src/test/java/org/hyperledger/fabric/samples/privatedata/AssetTransferTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | package org.hyperledger.fabric.samples.privatedata; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | import static org.assertj.core.api.ThrowableAssert.catchThrowable; 9 | import static java.nio.charset.StandardCharsets.UTF_8; 10 | import static org.hyperledger.fabric.samples.privatedata.AssetTransfer.AGREEMENT_KEYPREFIX; 11 | import static org.hyperledger.fabric.samples.privatedata.AssetTransfer.ASSET_COLLECTION_NAME; 12 | import static org.mockito.ArgumentMatchers.anyString; 13 | import static org.mockito.Mockito.mock; 14 | import static org.mockito.Mockito.verify; 15 | import static org.mockito.Mockito.verifyZeroInteractions; 16 | import static org.mockito.Mockito.when; 17 | 18 | import java.io.IOException; 19 | import java.security.cert.CertificateException; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import org.hyperledger.fabric.contract.ClientIdentity; 23 | import org.hyperledger.fabric.contract.Context; 24 | import org.hyperledger.fabric.shim.ChaincodeException; 25 | import org.hyperledger.fabric.shim.ChaincodeStub; 26 | import org.hyperledger.fabric.shim.ledger.CompositeKey; 27 | import org.junit.jupiter.api.Nested; 28 | import org.junit.jupiter.api.Test; 29 | 30 | public final class AssetTransferTest { 31 | 32 | @Nested 33 | class InvokeWriteTransaction { 34 | 35 | @Test 36 | public void createAssetWhenAssetExists() { 37 | AssetTransfer contract = new AssetTransfer(); 38 | Context ctx = mock(Context.class); 39 | ChaincodeStub stub = mock(ChaincodeStub.class); 40 | when(ctx.getStub()).thenReturn(stub); 41 | Map m = new HashMap(); 42 | m.put("asset_properties", dataAsset1Bytes); 43 | when(ctx.getStub().getTransient()).thenReturn(m); 44 | when(stub.getPrivateData(ASSET_COLLECTION_NAME, testAsset1ID)) 45 | .thenReturn(dataAsset1Bytes); 46 | 47 | Throwable thrown = catchThrowable(() -> { 48 | contract.CreateAsset(ctx); 49 | }); 50 | 51 | assertThat(thrown).isInstanceOf(ChaincodeException.class).hasNoCause() 52 | .hasMessage("Asset asset1 already exists"); 53 | assertThat(((ChaincodeException) thrown).getPayload()).isEqualTo("ASSET_ALREADY_EXISTS".getBytes()); 54 | } 55 | 56 | @Test 57 | public void createAssetWhenNewAssetIsCreated() throws CertificateException, IOException { 58 | AssetTransfer contract = new AssetTransfer(); 59 | Context ctx = mock(Context.class); 60 | ChaincodeStub stub = mock(ChaincodeStub.class); 61 | when(ctx.getStub()).thenReturn(stub); 62 | when(stub.getMspId()).thenReturn(testOrgOneMSP); 63 | ClientIdentity ci = mock(ClientIdentity.class); 64 | when(ci.getId()).thenReturn(testOrg1Client); 65 | when(ci.getMSPID()).thenReturn(testOrgOneMSP); 66 | when(ctx.getClientIdentity()).thenReturn(ci); 67 | 68 | Map m = new HashMap(); 69 | m.put("asset_properties", dataAsset1Bytes); 70 | when(ctx.getStub().getTransient()).thenReturn(m); 71 | 72 | when(stub.getPrivateData(ASSET_COLLECTION_NAME, testAsset1ID)) 73 | .thenReturn(new byte[0]); 74 | 75 | Asset created = contract.CreateAsset(ctx); 76 | assertThat(created).isEqualTo(testAsset1); 77 | 78 | verify(stub).putPrivateData(ASSET_COLLECTION_NAME, testAsset1ID, created.serialize()); 79 | } 80 | 81 | @Test 82 | public void transferAssetWhenExistingAssetIsTransferred() throws CertificateException, IOException { 83 | AssetTransfer contract = new AssetTransfer(); 84 | Context ctx = mock(Context.class); 85 | ChaincodeStub stub = mock(ChaincodeStub.class); 86 | when(ctx.getStub()).thenReturn(stub); 87 | when(stub.getMspId()).thenReturn(testOrgOneMSP); 88 | ClientIdentity ci = mock(ClientIdentity.class); 89 | when(ci.getId()).thenReturn(testOrg1Client); 90 | when(ctx.getClientIdentity()).thenReturn(ci); 91 | when(ci.getMSPID()).thenReturn(testOrgOneMSP); 92 | final String recipientOrgMsp = "TestOrg2"; 93 | final String buyerIdentity = "TestOrg2User"; 94 | Map m = new HashMap(); 95 | m.put("asset_owner", ("{ \"buyerMSP\": \"" + recipientOrgMsp + "\", \"assetID\": \"" + testAsset1ID + "\" }").getBytes()); 96 | when(ctx.getStub().getTransient()).thenReturn(m); 97 | 98 | when(stub.getPrivateDataHash(anyString(), anyString())).thenReturn("TestHashValue".getBytes()); 99 | when(stub.getPrivateData(ASSET_COLLECTION_NAME, testAsset1ID)) 100 | .thenReturn(dataAsset1Bytes); 101 | CompositeKey ck = mock(CompositeKey.class); 102 | when(ck.toString()).thenReturn(AGREEMENT_KEYPREFIX + testAsset1ID); 103 | when(stub.createCompositeKey(AGREEMENT_KEYPREFIX, testAsset1ID)).thenReturn(ck); 104 | when(stub.getPrivateData(ASSET_COLLECTION_NAME, AGREEMENT_KEYPREFIX + testAsset1ID)).thenReturn(buyerIdentity.getBytes(UTF_8)); 105 | contract.TransferAsset(ctx); 106 | 107 | Asset exptectedAfterTransfer = Asset.deserialize("{ \"objectType\": \"testasset\", \"assetID\": \"asset1\", \"color\": \"blue\", \"size\": 5, \"owner\": \"" + buyerIdentity + "\", \"appraisedValue\": 300 }"); 108 | 109 | verify(stub).putPrivateData(ASSET_COLLECTION_NAME, testAsset1ID, exptectedAfterTransfer.serialize()); 110 | String collectionOwner = testOrgOneMSP + "PrivateCollection"; 111 | verify(stub).delPrivateData(collectionOwner, testAsset1ID); 112 | verify(stub).delPrivateData(ASSET_COLLECTION_NAME, AGREEMENT_KEYPREFIX + testAsset1ID); 113 | } 114 | } 115 | 116 | @Nested 117 | class QueryReadAssetTransaction { 118 | 119 | @Test 120 | public void whenAssetExists() { 121 | AssetTransfer contract = new AssetTransfer(); 122 | Context ctx = mock(Context.class); 123 | ChaincodeStub stub = mock(ChaincodeStub.class); 124 | when(ctx.getStub()).thenReturn(stub); 125 | when(stub.getPrivateData(ASSET_COLLECTION_NAME, testAsset1ID)) 126 | .thenReturn(dataAsset1Bytes); 127 | 128 | Asset asset = contract.ReadAsset(ctx, testAsset1ID); 129 | 130 | assertThat(asset).isEqualTo(testAsset1); 131 | } 132 | 133 | @Test 134 | public void whenAssetDoesNotExist() { 135 | AssetTransfer contract = new AssetTransfer(); 136 | Context ctx = mock(Context.class); 137 | ChaincodeStub stub = mock(ChaincodeStub.class); 138 | when(ctx.getStub()).thenReturn(stub); 139 | when(stub.getStringState(testAsset1ID)).thenReturn(null); 140 | 141 | Asset asset = contract.ReadAsset(ctx, testAsset1ID); 142 | assertThat(asset).isNull(); 143 | } 144 | 145 | @Test 146 | public void invokeUnknownTransaction() { 147 | AssetTransfer contract = new AssetTransfer(); 148 | Context ctx = mock(Context.class); 149 | 150 | Throwable thrown = catchThrowable(() -> { 151 | contract.unknownTransaction(ctx); 152 | }); 153 | 154 | assertThat(thrown).isInstanceOf(ChaincodeException.class).hasNoCause() 155 | .hasMessage("Undefined contract method called"); 156 | assertThat(((ChaincodeException) thrown).getPayload()).isEqualTo(null); 157 | 158 | verifyZeroInteractions(ctx); 159 | } 160 | 161 | } 162 | 163 | private static String testOrgOneMSP = "TestOrg1"; 164 | private static String testOrg1Client = "testOrg1User"; 165 | 166 | private static String testAsset1ID = "asset1"; 167 | private static Asset testAsset1 = new Asset("testasset", "asset1", "blue", 5, testOrg1Client); 168 | private static byte[] dataAsset1Bytes = "{ \"objectType\": \"testasset\", \"assetID\": \"asset1\", \"color\": \"blue\", \"size\": 5, \"owner\": \"testOrg1User\", \"appraisedValue\": 300 }".getBytes(); 169 | 170 | } 171 | -------------------------------------------------------------------------------- /asset-transfer-typescript/src/assetTransfer.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | import { X509Certificate } from 'crypto'; 6 | import { Context, Contract, Info, Param, Returns, Transaction } from 'fabric-contract-api'; 7 | import { KeyEndorsementPolicy } from 'fabric-shim'; 8 | import stringify from 'json-stringify-deterministic'; // Deterministic JSON.stringify() 9 | import sortKeysRecursive from 'sort-keys-recursive'; 10 | import { TextDecoder } from 'util'; 11 | import { Asset } from './asset'; 12 | 13 | const utf8Decoder = new TextDecoder(); 14 | 15 | @Info({title: 'AssetTransfer', description: 'Smart contract for trading assets'}) 16 | export class AssetTransferContract extends Contract { 17 | /** 18 | * CreateAsset issues a new asset to the world state with given details. 19 | */ 20 | @Transaction() 21 | @Param('assetObj', 'Asset', 'Part formed JSON of Asset') 22 | async CreateAsset(ctx: Context, state: Asset): Promise { 23 | state.Owner = toJSON(clientIdentifier(ctx, state.Owner)); 24 | const asset = Asset.newInstance(state); 25 | 26 | const exists = await this.AssetExists(ctx, asset.ID); 27 | if (exists) { 28 | throw new Error(`The asset ${asset.ID} already exists`); 29 | } 30 | 31 | const assetBytes = marshal(asset); 32 | await ctx.stub.putState(asset.ID, assetBytes); 33 | await ctx.stub.putState(asset.ID, assetBytes); 34 | 35 | await setEndorsingOrgs(ctx, asset.ID, ctx.clientIdentity.getMSPID()); 36 | 37 | ctx.stub.setEvent('CreateAsset', assetBytes); 38 | } 39 | 40 | /** 41 | * ReadAsset returns an existing asset stored in the world state. 42 | */ 43 | @Transaction(false) 44 | @Returns('Asset') 45 | async ReadAsset(ctx: Context, id: string): Promise { 46 | const existingAssetBytes = await this.#readAsset(ctx, id); 47 | const existingAsset = Asset.newInstance(unmarshal(existingAssetBytes)); 48 | 49 | return existingAsset; 50 | } 51 | 52 | async #readAsset(ctx: Context, id: string): Promise { 53 | const assetBytes = await ctx.stub.getState(id); // get the asset from chaincode state 54 | if (!assetBytes || assetBytes.length === 0) { 55 | throw new Error(`Sorry, asset ${id} has not been created`); 56 | } 57 | 58 | return assetBytes; 59 | } 60 | 61 | /** 62 | * UpdateAsset updates an existing asset in the world state with provided partial asset data, which must include 63 | * the asset ID. 64 | */ 65 | @Transaction() 66 | @Param('assetObj', 'Asset', 'Part formed JSON of Asset') 67 | async UpdateAsset(ctx: Context, assetUpdate: Asset): Promise { 68 | if (assetUpdate.ID === undefined) { 69 | throw new Error('No asset ID specified'); 70 | } 71 | 72 | const existingAssetBytes = await this.#readAsset(ctx, assetUpdate.ID); 73 | const existingAsset = Asset.newInstance(unmarshal(existingAssetBytes)); 74 | 75 | if (!hasWritePermission(ctx, existingAsset)) { 76 | throw new Error('Only owner can update assets'); 77 | } 78 | 79 | const updatedState = Object.assign({}, existingAsset, assetUpdate, { 80 | Owner: existingAsset.Owner, // Must transfer to change owner 81 | }); 82 | const updatedAsset = Asset.newInstance(updatedState); 83 | 84 | // overwriting original asset with new asset 85 | const updatedAssetBytes = marshal(updatedAsset); 86 | await ctx.stub.putState(updatedAsset.ID, updatedAssetBytes); 87 | 88 | await setEndorsingOrgs(ctx, updatedAsset.ID, ctx.clientIdentity.getMSPID()); 89 | 90 | ctx.stub.setEvent('UpdateAsset', updatedAssetBytes); 91 | } 92 | 93 | /** 94 | * DeleteAsset deletes an asset from the world state. 95 | */ 96 | @Transaction() 97 | async DeleteAsset(ctx: Context, id: string): Promise { 98 | const assetBytes = await this.#readAsset(ctx, id); // Throws if asset does not exist 99 | const asset = Asset.newInstance(unmarshal(assetBytes)); 100 | 101 | if (!hasWritePermission(ctx, asset)) { 102 | throw new Error('Only owner can delete assets'); 103 | } 104 | 105 | await ctx.stub.deleteState(id); 106 | 107 | ctx.stub.setEvent('DeletaAsset', assetBytes); 108 | } 109 | 110 | /** 111 | * AssetExists returns true when asset with the specified ID exists in world state; otherwise false. 112 | */ 113 | @Transaction(false) 114 | @Returns('boolean') 115 | async AssetExists(ctx: Context, id: string): Promise { 116 | const assetJson = await ctx.stub.getState(id); 117 | return assetJson?.length > 0; 118 | } 119 | 120 | /** 121 | * TransferAsset updates the owner field of asset with the specified ID in the world state. 122 | */ 123 | @Transaction() 124 | async TransferAsset(ctx: Context, id: string, newOwner: string, newOwnerOrg: string): Promise { 125 | const assetString = await this.#readAsset(ctx, id); 126 | const asset = Asset.newInstance(unmarshal(assetString)); 127 | 128 | if (!hasWritePermission(ctx, asset)) { 129 | throw new Error('Only owner can transfer assets'); 130 | } 131 | 132 | asset.Owner = toJSON(ownerIdentifier(newOwner, newOwnerOrg)); 133 | 134 | const assetBytes = marshal(asset); 135 | await ctx.stub.putState(id, assetBytes); 136 | 137 | await setEndorsingOrgs(ctx, id, newOwnerOrg); // Subsequent updates must be endorsed by the new owning org 138 | 139 | ctx.stub.setEvent('TransferAsset', assetBytes); 140 | } 141 | 142 | 143 | @Transaction(false) 144 | @Returns('string') 145 | async GetAssetHistory(ctx: Context, id: string): Promise { 146 | const promiseOfIterator = ctx.stub.getHistoryForKey(id); 147 | console.log('Got iterator back from getHistory for key'); 148 | const results = []; 149 | for await (const keyMod of promiseOfIterator) { 150 | const resp = { 151 | timestamp: keyMod.timestamp, 152 | txid: keyMod.txId, 153 | data: '' 154 | }; 155 | console.log(`CC- keymod is ${JSON.stringify(keyMod)}`); 156 | if (keyMod.isDelete) { 157 | resp.data = 'KEY DELETED'; 158 | } else { 159 | resp.data = utf8Decoder.decode(keyMod.value); 160 | } 161 | results.push(resp); 162 | } 163 | console.log(results); 164 | return JSON.stringify(results); 165 | } 166 | 167 | /** 168 | * GetAllAssets returns a list of all assets found in the world state. 169 | */ 170 | @Transaction(false) 171 | @Returns('string') 172 | async GetAllAssets(ctx: Context): Promise { 173 | // range query with empty string for startKey and endKey does an open-ended query of all assets in the chaincode namespace. 174 | const iterator = await ctx.stub.getStateByRange('', ''); 175 | 176 | const assets: Asset[] = []; 177 | for (let result = await iterator.next(); !result.done; result = await iterator.next()) { 178 | const assetBytes = result.value.value; 179 | try { 180 | const asset = Asset.newInstance(unmarshal(assetBytes)); 181 | assets.push(asset); 182 | } catch (err) { 183 | console.log(err); 184 | } 185 | } 186 | 187 | return marshal(assets).toString(); 188 | } 189 | } 190 | 191 | function unmarshal(bytes: Uint8Array | string): object { 192 | const json = typeof bytes === 'string' ? bytes : utf8Decoder.decode(bytes); 193 | const parsed: unknown = JSON.parse(json); 194 | if (parsed === null || typeof parsed !== 'object') { 195 | throw new Error(`Invalid JSON type (${typeof parsed}): ${json}`); 196 | } 197 | 198 | return parsed; 199 | } 200 | 201 | function marshal(o: object): Buffer { 202 | return Buffer.from(toJSON(o)); 203 | } 204 | 205 | function toJSON(o: object): string { 206 | // Insert data in alphabetic order using 'json-stringify-deterministic' and 'sort-keys-recursive' 207 | return stringify(sortKeysRecursive(o)); 208 | } 209 | 210 | interface OwnerIdentifier { 211 | org: string; 212 | user: string; 213 | } 214 | 215 | function hasWritePermission(ctx: Context, asset: Asset): boolean { 216 | const clientId = clientIdentifier(ctx); 217 | const ownerId = unmarshal(asset.Owner) as OwnerIdentifier; 218 | return clientId.org === ownerId.org; 219 | } 220 | 221 | function clientIdentifier(ctx: Context, user?: string): OwnerIdentifier { 222 | return { 223 | org: ctx.clientIdentity.getMSPID(), 224 | user: user ?? clientCommonName(ctx), 225 | }; 226 | } 227 | 228 | function clientCommonName(ctx: Context): string { 229 | const clientCert = new X509Certificate(ctx.clientIdentity.getIDBytes()); 230 | const matches = clientCert.subject.match(/^CN=(.*)$/m); // [0] Matching string; [1] capture group 231 | if (matches?.length !== 2) { 232 | throw new Error(`Unable to identify client identity common name: ${clientCert.subject}`); 233 | } 234 | 235 | return matches[1]; 236 | } 237 | 238 | function ownerIdentifier(user: string, org: string): OwnerIdentifier { 239 | return { org, user }; 240 | } 241 | 242 | async function setEndorsingOrgs(ctx: Context, ledgerKey: string, ...orgs: string[]): Promise { 243 | const policy = newMemberPolicy(...orgs); 244 | await ctx.stub.setStateValidationParameter(ledgerKey, policy.getPolicy()); 245 | } 246 | 247 | function newMemberPolicy(...orgs: string[]): KeyEndorsementPolicy { 248 | const policy = new KeyEndorsementPolicy(); 249 | policy.addOrgs('MEMBER', ...orgs); 250 | return policy; 251 | } 252 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /javascript/test/assetTransfer.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright IBM Corp. All Rights Reserved. 3 | * 4 | * SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | 'use strict'; 8 | const sinon = require('sinon'); 9 | const chai = require('chai'); 10 | const sinonChai = require('sinon-chai'); 11 | const expect = chai.expect; 12 | 13 | const { Context } = require('fabric-contract-api'); 14 | const { ChaincodeStub } = require('fabric-shim'); 15 | 16 | const AssetTransfer = require('../lib/assetTransfer.js'); 17 | 18 | let assert = sinon.assert; 19 | chai.use(sinonChai); 20 | 21 | describe('Asset Transfer Basic Tests', () => { 22 | let transactionContext, chaincodeStub, asset; 23 | beforeEach(() => { 24 | transactionContext = new Context(); 25 | 26 | chaincodeStub = sinon.createStubInstance(ChaincodeStub); 27 | transactionContext.setChaincodeStub(chaincodeStub); 28 | 29 | chaincodeStub.putState.callsFake((key, value) => { 30 | if (!chaincodeStub.states) { 31 | chaincodeStub.states = {}; 32 | } 33 | chaincodeStub.states[key] = value; 34 | }); 35 | 36 | chaincodeStub.getState.callsFake(async (key) => { 37 | let ret; 38 | if (chaincodeStub.states) { 39 | ret = chaincodeStub.states[key]; 40 | } 41 | return Promise.resolve(ret); 42 | }); 43 | 44 | chaincodeStub.deleteState.callsFake(async (key) => { 45 | if (chaincodeStub.states) { 46 | delete chaincodeStub.states[key]; 47 | } 48 | return Promise.resolve(key); 49 | }); 50 | 51 | chaincodeStub.getStateByRange.callsFake(async () => { 52 | function* internalGetStateByRange() { 53 | if (chaincodeStub.states) { 54 | // Shallow copy 55 | const copied = Object.assign({}, chaincodeStub.states); 56 | 57 | for (let key in copied) { 58 | yield {value: copied[key]}; 59 | } 60 | } 61 | } 62 | 63 | return Promise.resolve(internalGetStateByRange()); 64 | }); 65 | 66 | asset = { 67 | ID: 'asset1', 68 | Color: 'blue', 69 | Size: 5, 70 | Owner: 'Tomoko', 71 | AppraisedValue: 300, 72 | }; 73 | }); 74 | 75 | describe('Test InitLedger', () => { 76 | it('should return error on InitLedger', async () => { 77 | chaincodeStub.putState.rejects('failed inserting key'); 78 | let assetTransfer = new AssetTransfer(); 79 | try { 80 | await assetTransfer.InitLedger(transactionContext); 81 | assert.fail('InitLedger should have failed'); 82 | } catch (err) { 83 | expect(err.name).to.equal('failed inserting key'); 84 | } 85 | }); 86 | 87 | it('should return success on InitLedger', async () => { 88 | let assetTransfer = new AssetTransfer(); 89 | await assetTransfer.InitLedger(transactionContext); 90 | let ret = JSON.parse((await chaincodeStub.getState('asset1')).toString()); 91 | expect(ret).to.eql(Object.assign({docType: 'asset'}, asset)); 92 | }); 93 | }); 94 | 95 | describe('Test CreateAsset', () => { 96 | it('should return error on CreateAsset', async () => { 97 | chaincodeStub.putState.rejects('failed inserting key'); 98 | 99 | let assetTransfer = new AssetTransfer(); 100 | try { 101 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 102 | assert.fail('CreateAsset should have failed'); 103 | } catch(err) { 104 | expect(err.name).to.equal('failed inserting key'); 105 | } 106 | }); 107 | 108 | it('should return success on CreateAsset', async () => { 109 | let assetTransfer = new AssetTransfer(); 110 | 111 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 112 | 113 | let ret = JSON.parse((await chaincodeStub.getState(asset.ID)).toString()); 114 | expect(ret).to.eql(asset); 115 | }); 116 | }); 117 | 118 | describe('Test ReadAsset', () => { 119 | it('should return error on ReadAsset', async () => { 120 | let assetTransfer = new AssetTransfer(); 121 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 122 | 123 | try { 124 | await assetTransfer.ReadAsset(transactionContext, 'asset2'); 125 | assert.fail('ReadAsset should have failed'); 126 | } catch (err) { 127 | expect(err.message).to.equal('The asset asset2 does not exist'); 128 | } 129 | }); 130 | 131 | it('should return success on ReadAsset', async () => { 132 | let assetTransfer = new AssetTransfer(); 133 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 134 | 135 | let ret = JSON.parse(await chaincodeStub.getState(asset.ID)); 136 | expect(ret).to.eql(asset); 137 | }); 138 | }); 139 | 140 | describe('Test UpdateAsset', () => { 141 | it('should return error on UpdateAsset', async () => { 142 | let assetTransfer = new AssetTransfer(); 143 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 144 | 145 | try { 146 | await assetTransfer.UpdateAsset(transactionContext, 'asset2', 'orange', 10, 'Me', 500); 147 | assert.fail('UpdateAsset should have failed'); 148 | } catch (err) { 149 | expect(err.message).to.equal('The asset asset2 does not exist'); 150 | } 151 | }); 152 | 153 | it('should return success on UpdateAsset', async () => { 154 | let assetTransfer = new AssetTransfer(); 155 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 156 | 157 | await assetTransfer.UpdateAsset(transactionContext, 'asset1', 'orange', 10, 'Me', 500); 158 | let ret = JSON.parse(await chaincodeStub.getState(asset.ID)); 159 | let expected = { 160 | ID: 'asset1', 161 | Color: 'orange', 162 | Size: 10, 163 | Owner: 'Me', 164 | AppraisedValue: 500 165 | }; 166 | expect(ret).to.eql(expected); 167 | }); 168 | }); 169 | 170 | describe('Test DeleteAsset', () => { 171 | it('should return error on DeleteAsset', async () => { 172 | let assetTransfer = new AssetTransfer(); 173 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 174 | 175 | try { 176 | await assetTransfer.DeleteAsset(transactionContext, 'asset2'); 177 | assert.fail('DeleteAsset should have failed'); 178 | } catch (err) { 179 | expect(err.message).to.equal('The asset asset2 does not exist'); 180 | } 181 | }); 182 | 183 | it('should return success on DeleteAsset', async () => { 184 | let assetTransfer = new AssetTransfer(); 185 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 186 | 187 | await assetTransfer.DeleteAsset(transactionContext, asset.ID); 188 | let ret = await chaincodeStub.getState(asset.ID); 189 | expect(ret).to.equal(undefined); 190 | }); 191 | }); 192 | 193 | describe('Test TransferAsset', () => { 194 | it('should return error on TransferAsset', async () => { 195 | let assetTransfer = new AssetTransfer(); 196 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 197 | 198 | try { 199 | await assetTransfer.TransferAsset(transactionContext, 'asset2', 'Me'); 200 | assert.fail('DeleteAsset should have failed'); 201 | } catch (err) { 202 | expect(err.message).to.equal('The asset asset2 does not exist'); 203 | } 204 | }); 205 | 206 | it('should return success on TransferAsset', async () => { 207 | let assetTransfer = new AssetTransfer(); 208 | await assetTransfer.CreateAsset(transactionContext, asset.ID, asset.Color, asset.Size, asset.Owner, asset.AppraisedValue); 209 | 210 | await assetTransfer.TransferAsset(transactionContext, asset.ID, 'Me'); 211 | let ret = JSON.parse((await chaincodeStub.getState(asset.ID)).toString()); 212 | expect(ret).to.eql(Object.assign({}, asset, {Owner: 'Me'})); 213 | }); 214 | }); 215 | 216 | describe('Test GetAllAssets', () => { 217 | it('should return success on GetAllAssets', async () => { 218 | let assetTransfer = new AssetTransfer(); 219 | 220 | await assetTransfer.CreateAsset(transactionContext, 'asset1', 'blue', 5, 'Robert', 100); 221 | await assetTransfer.CreateAsset(transactionContext, 'asset2', 'orange', 10, 'Paul', 200); 222 | await assetTransfer.CreateAsset(transactionContext, 'asset3', 'red', 15, 'Troy', 300); 223 | await assetTransfer.CreateAsset(transactionContext, 'asset4', 'pink', 20, 'Van', 400); 224 | 225 | let ret = await assetTransfer.GetAllAssets(transactionContext); 226 | ret = JSON.parse(ret); 227 | expect(ret.length).to.equal(4); 228 | 229 | let expected = [ 230 | {Record: {ID: 'asset1', Color: 'blue', Size: 5, Owner: 'Robert', AppraisedValue: 100}}, 231 | {Record: {ID: 'asset2', Color: 'orange', Size: 10, Owner: 'Paul', AppraisedValue: 200}}, 232 | {Record: {ID: 'asset3', Color: 'red', Size: 15, Owner: 'Troy', AppraisedValue: 300}}, 233 | {Record: {ID: 'asset4', Color: 'pink', Size: 20, Owner: 'Van', AppraisedValue: 400}} 234 | ]; 235 | 236 | expect(ret).to.eql(expected); 237 | }); 238 | 239 | it('should return success on GetAllAssets for non JSON value', async () => { 240 | let assetTransfer = new AssetTransfer(); 241 | 242 | chaincodeStub.putState.onFirstCall().callsFake((key, value) => { 243 | if (!chaincodeStub.states) { 244 | chaincodeStub.states = {}; 245 | } 246 | chaincodeStub.states[key] = 'non-json-value'; 247 | }); 248 | 249 | await assetTransfer.CreateAsset(transactionContext, 'asset1', 'blue', 5, 'Robert', 100); 250 | await assetTransfer.CreateAsset(transactionContext, 'asset2', 'orange', 10, 'Paul', 200); 251 | await assetTransfer.CreateAsset(transactionContext, 'asset3', 'red', 15, 'Troy', 300); 252 | await assetTransfer.CreateAsset(transactionContext, 'asset4', 'pink', 20, 'Van', 400); 253 | 254 | let ret = await assetTransfer.GetAllAssets(transactionContext); 255 | ret = JSON.parse(ret); 256 | expect(ret.length).to.equal(4); 257 | 258 | let expected = [ 259 | {Record: 'non-json-value'}, 260 | {Record: {ID: 'asset2', Color: 'orange', Size: 10, Owner: 'Paul', AppraisedValue: 200}}, 261 | {Record: {ID: 'asset3', Color: 'red', Size: 15, Owner: 'Troy', AppraisedValue: 300}}, 262 | {Record: {ID: 'asset4', Color: 'pink', Size: 20, Owner: 'Van', AppraisedValue: 400}} 263 | ]; 264 | 265 | expect(ret).to.eql(expected); 266 | }); 267 | }); 268 | }); 269 | -------------------------------------------------------------------------------- /javascript/lib/chaincode.js: -------------------------------------------------------------------------------- 1 | /* 2 | # Copyright IBM Corp. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 'use strict'; 7 | 8 | const {Contract} = require('fabric-contract-api'); 9 | 10 | async function getAllResults(iterator, getKeys) { 11 | const allResults = []; 12 | let loop = true; 13 | while (loop) { 14 | const res = await iterator.next(); 15 | if (!res.value && res.done) { 16 | await iterator.close(); 17 | return allResults; 18 | } else if (!res.value) { 19 | throw new Error('no value and not done (internal error?)'); 20 | } 21 | const theVal = (getKeys) ? res.value.key : res.value.value.toString('utf8'); 22 | allResults.push(theVal); 23 | if (res.done) { 24 | await iterator.close(); 25 | loop = false; 26 | return allResults; 27 | } 28 | } 29 | } 30 | 31 | async function getAllResultsUsingAsyncIterator(promiseOfIterator, getKeys) { 32 | const allResults = []; 33 | for await (const res of promiseOfIterator) { 34 | const theVal = (getKeys) ? res.key : res.value.toString('utf8'); 35 | allResults.push(theVal); 36 | } 37 | 38 | // iterator will be automatically closed on exit from the loop 39 | // either by reaching the end, or a break or throw terminated the loop 40 | return allResults; 41 | } 42 | 43 | class CrudChaincode extends Contract { 44 | 45 | constructor() { 46 | super('org.mynamespace.crud'); 47 | this.logBuffer = {output: []}; 48 | } 49 | 50 | async instantiate(ctx) { 51 | const stub = ctx.stub; 52 | 53 | await stub.putState('string', Buffer.from('string')); 54 | const names = ['ann', 'beth', 'cory']; 55 | const colors = ['black', 'red', 'yellow']; 56 | for (const n in names) { 57 | for (const c in colors) { 58 | const compositeKey = stub.createCompositeKey('name~color', [names[n], colors[c]]); 59 | await stub.putState(compositeKey, names[n] + colors[c]); 60 | } 61 | } 62 | for (let i = 0; i < 5; i++) { 63 | await stub.putState(`key${i}`, Buffer.from(`value${i}`)); 64 | await stub.putState(`jsonkey${i}`, Buffer.from(JSON.stringify({key: `k${i}`, value: `value${i}`}))); 65 | } 66 | 67 | // add a large set of keys for testing pagination and larger data sets 68 | const DATA_SET_SIZE=229; 69 | for (let i = 0; i < DATA_SET_SIZE;i++){ 70 | const compositeKey = stub.createCompositeKey('bulk-data',['bulk',i.toString().padStart(3,'0')]); 71 | await stub.putState(compositeKey, Buffer.from(i.toString().padStart(3,'0'))); 72 | } 73 | } 74 | 75 | async getKey({stub}) { 76 | const {params} = stub.getFunctionAndParameters(); 77 | const key = params[0]; 78 | return (await stub.getState(key)).toString(); 79 | } 80 | 81 | async getKeysConcurrently({stub}) { 82 | const p1 = stub.getState('key1') 83 | .then((res) => { 84 | return res.toString('utf8'); 85 | }); 86 | 87 | const p2 = stub.getState('key2') 88 | .then((res) => { 89 | return res.toString('utf8'); 90 | }); 91 | 92 | const p3 = stub.getState('key3') 93 | .then((res) => { 94 | return res.toString('utf8'); 95 | }); 96 | 97 | return Promise.all([p1, p2, p3]) 98 | .then((resArray) => { 99 | return resArray; 100 | }); 101 | } 102 | 103 | async getCompositeKey({stub}) { 104 | const {params} = stub.getFunctionAndParameters(); 105 | const composite = stub.createCompositeKey('name~color', params); 106 | return (await stub.getState(composite)).toString(); 107 | } 108 | 109 | async getPartialCompositeKey({stub}) { 110 | const {params} = stub.getFunctionAndParameters(); 111 | const result = await stub.getStateByPartialCompositeKey('name~color', params); 112 | return (await getAllResults(result)).toString().split(','); 113 | } 114 | 115 | async getPartialCompositeKeyUsingAsyncIterator({stub}) { 116 | const {params} = stub.getFunctionAndParameters(); 117 | const promiseOfIterator = stub.getStateByPartialCompositeKey('name~color', params); 118 | return (await getAllResultsUsingAsyncIterator(promiseOfIterator)).toString().split(','); 119 | } 120 | 121 | async getKeysByRange({stub}) { 122 | const {params} = stub.getFunctionAndParameters(); 123 | const result = await stub.getStateByRange(params[0], params[1]); 124 | return (await getAllResults(result)).toString().split(','); 125 | } 126 | 127 | async getKeysByRangeUsingAsyncIterator({stub}) { 128 | const {params} = stub.getFunctionAndParameters(); 129 | const promiseOfIterator = stub.getStateByRange(params[0], params[1]); 130 | return (await getAllResultsUsingAsyncIterator(promiseOfIterator)).toString().split(','); 131 | } 132 | 133 | async getHistoryForKey({stub}) { 134 | const {params} = stub.getFunctionAndParameters(); 135 | const iterator = await stub.getHistoryForKey(params[0]); 136 | return (await getAllResults(iterator)).toString().split(','); 137 | } 138 | 139 | async getHistoryForKeyUsingAsyncIterator({stub}) { 140 | const {params} = stub.getFunctionAndParameters(); 141 | const promiseOfIterator = stub.getHistoryForKey(params[0]); 142 | return (await getAllResultsUsingAsyncIterator(promiseOfIterator)).toString().split(','); 143 | } 144 | 145 | async getQueryResultWithPagination({stub}) { 146 | const query = { 147 | selector: { 148 | key: { 149 | $regex: 'k[0-4]' 150 | } 151 | } 152 | }; 153 | 154 | let response = await stub.getQueryResultWithPagination(JSON.stringify(query), 2); 155 | const {iterator, metadata} = response; 156 | 157 | let results = await getAllResults(iterator, true /* get keys instead of values */); 158 | const results1 = results; 159 | const metadata1 = metadata; 160 | 161 | response = await stub.getQueryResultWithPagination(JSON.stringify(query), 1, metadata.bookmark); 162 | results = await getAllResults(response.iterator, true /* get keys instead of values */); 163 | const results2 = results; 164 | const metadata2 = response.metadata; 165 | return {results1, metadata1, results2, metadata2}; 166 | } 167 | 168 | async getQueryResultWithPaginationUsingAsyncIterator({stub}) { 169 | const query = { 170 | selector: { 171 | key: { 172 | $regex: 'k[0-4]' 173 | } 174 | } 175 | }; 176 | 177 | let promiseOfIterator = stub.getQueryResultWithPagination(JSON.stringify(query), 2); 178 | let results = await getAllResultsUsingAsyncIterator(promiseOfIterator, true /* get keys instead of values */); 179 | const results1 = results; 180 | const metadata1 = (await promiseOfIterator).metadata; 181 | 182 | promiseOfIterator = stub.getQueryResultWithPagination(JSON.stringify(query), 1, metadata1.bookmark); 183 | results = await getAllResultsUsingAsyncIterator(promiseOfIterator, true /* get keys instead of values */); 184 | const results2 = results; 185 | const metadata2 = (await promiseOfIterator).metadata; 186 | return {results1, metadata1, results2, metadata2}; 187 | } 188 | 189 | async getStateByRangeWithPagination({stub}) { 190 | let {params} = stub.getFunctionAndParameters(); 191 | params = params.map((p) => { 192 | if (p === parseInt(p).toString()) { 193 | return parseInt(p); 194 | } else { 195 | return p; 196 | } 197 | }); 198 | const {iterator} = await stub.getStateByRangeWithPagination(...params); 199 | return (await getAllResults(iterator)).toString().split(','); 200 | } 201 | 202 | async getStateByRangeWithPaginationUsingAsyncIterator({stub}) { 203 | let {params} = stub.getFunctionAndParameters(); 204 | params = params.map((p) => { 205 | if (p === parseInt(p).toString()) { 206 | return parseInt(p); 207 | } else { 208 | return p; 209 | } 210 | }); 211 | const promiseOfIterator = stub.getStateByRangeWithPagination(...params); 212 | return (await getAllResultsUsingAsyncIterator(promiseOfIterator)).toString().split(','); 213 | } 214 | 215 | async getStateByPartialCompositeKey({stub}) { 216 | const {params} = stub.getFunctionAndParameters(); 217 | const iterator = await stub.getStateByPartialCompositeKey(params[0], params.slice(1)); 218 | return await getAllResults(iterator); 219 | } 220 | 221 | async getStateByPartialCompositeKeyUsingAsyncIterator({stub}) { 222 | const {params} = stub.getFunctionAndParameters(); 223 | const promiseOfIterator = stub.getStateByPartialCompositeKey(params[0], params.slice(1)); 224 | return await getAllResultsUsingAsyncIterator(promiseOfIterator); 225 | } 226 | 227 | async getStateByPartialCompositeKeyWithPagination({stub}) { 228 | const {params} = stub.getFunctionAndParameters(); 229 | const {iterator} = await stub.getStateByPartialCompositeKeyWithPagination(params[0], [], parseInt(params[1]), ''); 230 | return await getAllResults(iterator); 231 | } 232 | 233 | async getStateByPartialCompositeKeyWithPaginationUsingAsyncIterator({stub}) { 234 | const {params} = stub.getFunctionAndParameters(); 235 | const promiseOfIterator = stub.getStateByPartialCompositeKeyWithPagination(params[0], [], parseInt(params[1]), ''); 236 | return await getAllResultsUsingAsyncIterator(promiseOfIterator); 237 | } 238 | 239 | /* 240 | * This chaincode is to be implemented when the new basic network has been created, 241 | * as key level endorsement is not enabled with this current basic_network 242 | */ 243 | 244 | // async getStateValidationParameter({stub}) { 245 | // const {params} = stub.getFunctionAndParameters(); 246 | // // should exists validation parameter ['Org1MSP'] for key1 247 | // const epBuffer = await stub.getStateValidationParameter(params[0]); 248 | // const ep = new KeyEndorsementPolicy(epBuffer); 249 | 250 | // // should not exists validation parameter for key2 251 | // const epBuffer2 = await stub.getStateValidationParameter(params[1]); 252 | // return {ep, epBuffer2}; 253 | // } 254 | 255 | async putKey({stub}) { 256 | const {params} = stub.getFunctionAndParameters(); 257 | await stub.putState(...params); 258 | } 259 | 260 | async putCompositeKey({stub}) { 261 | const {params} = stub.getFunctionAndParameters(); 262 | const compositeKey = stub.createCompositeKey('name~color', [params[0], params[1]]); 263 | await stub.putState(compositeKey, params[2]); 264 | } 265 | 266 | async deleteKey({stub}) { 267 | const {params} = stub.getFunctionAndParameters(); 268 | await stub.deleteState(params[0]); 269 | } 270 | 271 | async deleteCompositeKey({stub}) { 272 | const {params} = stub.getFunctionAndParameters(); 273 | const compositeKey = stub.createCompositeKey('name~color', params); 274 | await stub.deleteState(compositeKey); 275 | } 276 | 277 | /* 278 | * This chaincode is to be implemented when the new basic network has been created, 279 | * as key level endorsement is not enabled with this current basic_network 280 | */ 281 | 282 | // async setStateValidationParameter({stub}) { 283 | // const {params} = stub.getFunctionAndParameters(); 284 | // const ep = new KeyEndorsementPolicy(); 285 | // ep.addOrgs('MEMBER', 'Org1MSP'); 286 | // await stub.setStateValidationParameter(params[0], ep.getPolicy()); 287 | // } 288 | 289 | async splitCompositeKey({stub}) { 290 | const {params} = stub.getFunctionAndParameters(); 291 | 292 | const iterator = await stub.getStateByPartialCompositeKey('name~color', [params[0]]); 293 | const results = await getAllResults(iterator, true /* get keys instead of values */); 294 | 295 | const key1 = stub.splitCompositeKey(results[0]); 296 | const key2 = stub.splitCompositeKey(results[1]); 297 | const key3 = stub.splitCompositeKey(results[2]); 298 | return {results, key1, key2, key3}; 299 | } 300 | 301 | } 302 | module.exports = CrudChaincode; 303 | -------------------------------------------------------------------------------- /asset-tx-private-java/src/main/java/org/hyperledger/fabric/samples/privatedata/AssetTransfer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-License-Identifier: Apache-2.0 3 | */ 4 | 5 | package org.hyperledger.fabric.samples.privatedata; 6 | 7 | import static java.nio.charset.StandardCharsets.UTF_8; 8 | 9 | import org.hyperledger.fabric.contract.Context; 10 | import org.hyperledger.fabric.contract.ContractInterface; 11 | import org.hyperledger.fabric.contract.annotation.Contact; 12 | import org.hyperledger.fabric.contract.annotation.Contract; 13 | import org.hyperledger.fabric.contract.annotation.Default; 14 | import org.hyperledger.fabric.contract.annotation.Info; 15 | import org.hyperledger.fabric.contract.annotation.License; 16 | import org.hyperledger.fabric.contract.annotation.Transaction; 17 | import org.hyperledger.fabric.shim.ChaincodeException; 18 | import org.hyperledger.fabric.shim.ChaincodeStub; 19 | import org.hyperledger.fabric.shim.ledger.CompositeKey; 20 | 21 | import org.hyperledger.fabric.shim.ledger.KeyValue; 22 | import org.hyperledger.fabric.shim.ledger.QueryResultsIterator; 23 | import org.json.JSONObject; 24 | 25 | import java.util.ArrayList; 26 | import java.util.Arrays; 27 | import java.util.List; 28 | import java.util.Map; 29 | 30 | /** 31 | * Main Chaincode class. A ContractInterface gets converted to Chaincode internally. 32 | * @see org.hyperledger.fabric.shim.Chaincode 33 | * 34 | * Each chaincode transaction function must take, Context as first parameter. 35 | * Unless specified otherwise via annotation (@Contract or @Transaction), the contract name 36 | * is the class name (without package) 37 | * and the transaction name is the method name. 38 | * 39 | * To create fabric test-network 40 | * cd fabric-samples/test-network 41 | * ./network.sh up createChannel -ca -s couchdb 42 | * To deploy this chaincode to test-network, use the collection config as described in 43 | * See queryResults = new ArrayList<>(); 160 | // retrieve asset with keys between startKey (inclusive) and endKey(exclusive) in lexical order. 161 | try (QueryResultsIterator results = stub.getPrivateDataByRange(ASSET_COLLECTION_NAME, startKey, endKey)) { 162 | for (KeyValue result : results) { 163 | if (result.getStringValue() == null || result.getStringValue().length() == 0) { 164 | System.err.printf("Invalid Asset json: %s\n", result.getStringValue()); 165 | continue; 166 | } 167 | Asset asset = Asset.deserialize(result.getStringValue()); 168 | queryResults.add(asset); 169 | System.out.println("QueryResult: " + asset.toString()); 170 | } 171 | } 172 | return queryResults.toArray(new Asset[0]); 173 | } 174 | 175 | // =======Rich queries ========================================================================= 176 | // Two examples of rich queries are provided below (parameterized query and ad hoc query). 177 | // Rich queries pass a query string to the state database. 178 | // Rich queries are only supported by state database implementations 179 | // that support rich query (e.g. CouchDB). 180 | // The query string is in the syntax of the underlying state database. 181 | // With rich queries there is no guarantee that the result set hasn't changed between 182 | // endorsement time and commit time, aka 'phantom reads'. 183 | // Therefore, rich queries should not be used in update transactions, unless the 184 | // application handles the possibility of result set changes between endorsement and commit time. 185 | // Rich queries can be used for point-in-time queries against a peer. 186 | // ============================================================================================ 187 | 188 | /** 189 | * QueryAssetByOwner queries for assets based on assetType, owner. 190 | * This is an example of a parameterized query where the query logic is baked into the chaincode, 191 | * and accepting a single query parameter (owner). 192 | * 193 | * @param ctx the transaction context 194 | * @param assetType type to query for 195 | * @param owner asset owner to query for 196 | * @return the asset found on the ledger if there was one 197 | */ 198 | @Transaction(intent = Transaction.TYPE.EVALUATE) 199 | public Asset[] QueryAssetByOwner(final Context ctx, final String assetType, final String owner) throws Exception { 200 | String queryString = String.format("{\"selector\":{\"objectType\":\"%s\",\"owner\":\"%s\"}}", assetType, owner); 201 | return getQueryResult(ctx, queryString); 202 | } 203 | 204 | /** 205 | * QueryAssets uses a query string to perform a query for assets. 206 | * Query string matching state database syntax is passed in and executed as is. 207 | * Supports ad hoc queries that can be defined at runtime by the client. 208 | * 209 | * @param ctx the transaction context 210 | * @param queryString query string matching state database syntax 211 | * @return the asset found on the ledger if there was one 212 | */ 213 | @Transaction(intent = Transaction.TYPE.EVALUATE) 214 | public Asset[] QueryAssets(final Context ctx, final String queryString) throws Exception { 215 | return getQueryResult(ctx, queryString); 216 | } 217 | 218 | private Asset[] getQueryResult(final Context ctx, final String queryString) throws Exception { 219 | ChaincodeStub stub = ctx.getStub(); 220 | System.out.printf("QueryAssets: %s\n", queryString); 221 | 222 | List queryResults = new ArrayList(); 223 | // retrieve asset with keys between startKey (inclusive) and endKey(exclusive) in lexical order. 224 | try (QueryResultsIterator results = stub.getPrivateDataQueryResult(ASSET_COLLECTION_NAME, queryString)) { 225 | for (KeyValue result : results) { 226 | if (result.getStringValue() == null || result.getStringValue().length() == 0) { 227 | System.err.printf("Invalid Asset json: %s\n", result.getStringValue()); 228 | continue; 229 | } 230 | Asset asset = Asset.deserialize(result.getStringValue()); 231 | queryResults.add(asset); 232 | System.out.println("QueryResult: " + asset.toString()); 233 | } 234 | } 235 | return queryResults.toArray(new Asset[0]); 236 | } 237 | 238 | 239 | /** 240 | * Creates a new asset on the ledger from asset properties passed in as transient map. 241 | * Asset owner will be inferred from the ClientId via stub api 242 | * 243 | * @param ctx the transaction context 244 | * Transient map with asset_properties key with asset json as value 245 | * @return the created asset 246 | */ 247 | @Transaction(intent = Transaction.TYPE.SUBMIT) 248 | public Asset CreateAsset(final Context ctx) { 249 | ChaincodeStub stub = ctx.getStub(); 250 | Map transientMap = ctx.getStub().getTransient(); 251 | if (!transientMap.containsKey("asset_properties")) { 252 | String errorMessage = String.format("CreateAsset call must specify asset_properties in Transient map input"); 253 | System.err.println(errorMessage); 254 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 255 | } 256 | 257 | byte[] transientAssetJSON = transientMap.get("asset_properties"); 258 | final String assetID; 259 | final String type; 260 | final String color; 261 | int appraisedValue = 0; 262 | int size = 0; 263 | try { 264 | JSONObject json = new JSONObject(new String(transientAssetJSON, UTF_8)); 265 | Map tMap = json.toMap(); 266 | 267 | type = (String) tMap.get("objectType"); 268 | assetID = (String) tMap.get("assetID"); 269 | color = (String) tMap.get("color"); 270 | if (tMap.containsKey("size")) { 271 | size = (Integer) tMap.get("size"); 272 | } 273 | if (tMap.containsKey("appraisedValue")) { 274 | appraisedValue = (Integer) tMap.get("appraisedValue"); 275 | } 276 | } catch (Exception err) { 277 | String errorMessage = String.format("TransientMap deserialized error: %s ", err); 278 | System.err.println(errorMessage); 279 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 280 | } 281 | 282 | //input validations 283 | String errorMessage = null; 284 | if (assetID.equals("")) { 285 | errorMessage = String.format("Empty input in Transient map: assetID"); 286 | } 287 | if (type.equals("")) { 288 | errorMessage = String.format("Empty input in Transient map: objectType"); 289 | } 290 | if (color.equals("")) { 291 | errorMessage = String.format("Empty input in Transient map: color"); 292 | } 293 | if (size <= 0) { 294 | errorMessage = String.format("Empty input in Transient map: size"); 295 | } 296 | if (appraisedValue <= 0) { 297 | errorMessage = String.format("Empty input in Transient map: appraisedValue"); 298 | } 299 | 300 | if (errorMessage != null) { 301 | System.err.println(errorMessage); 302 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 303 | } 304 | 305 | Asset asset = new Asset(type, assetID, color, size, ""); 306 | // Check if asset already exists 307 | byte[] assetJSON = ctx.getStub().getPrivateData(ASSET_COLLECTION_NAME, assetID); 308 | if (assetJSON != null && assetJSON.length > 0) { 309 | errorMessage = String.format("Asset %s already exists", assetID); 310 | System.err.println(errorMessage); 311 | throw new ChaincodeException(errorMessage, AssetTransferErrors.ASSET_ALREADY_EXISTS.toString()); 312 | } 313 | 314 | // Get ID of submitting client identity 315 | String clientID = ctx.getClientIdentity().getId(); 316 | 317 | // Verify that the client is submitting request to peer in their organization 318 | // This is to ensure that a client from another org doesn't attempt to read or 319 | // write private data from this peer. 320 | verifyClientOrgMatchesPeerOrg(ctx); 321 | 322 | // Make submitting client the owner 323 | asset.setOwner(clientID); 324 | System.out.printf("CreateAsset Put: collection %s, ID %s\n", ASSET_COLLECTION_NAME, assetID); 325 | System.out.printf("Put: collection %s, ID %s\n", ASSET_COLLECTION_NAME, new String(asset.serialize())); 326 | stub.putPrivateData(ASSET_COLLECTION_NAME, assetID, asset.serialize()); 327 | 328 | // Get collection name for this organization. 329 | String orgCollectionName = getCollectionName(ctx); 330 | 331 | // Save AssetPrivateDetails to org collection 332 | AssetPrivateDetails assetPriv = new AssetPrivateDetails(assetID, appraisedValue); 333 | System.out.printf("Put AssetPrivateDetails: collection %s, ID %s\n", orgCollectionName, assetID); 334 | stub.putPrivateData(orgCollectionName, assetID, assetPriv.serialize()); 335 | 336 | return asset; 337 | } 338 | 339 | /** 340 | * AgreeToTransfer is used by the potential buyer of the asset to agree to the 341 | * asset value. The agreed to appraisal value is stored in the buying orgs 342 | * org specifc collection, while the the buyer client ID is stored in the asset collection 343 | * using a composite key 344 | * Uses transient map with key asset_value 345 | * 346 | * @param ctx the transaction context 347 | */ 348 | @Transaction(intent = Transaction.TYPE.SUBMIT) 349 | public void AgreeToTransfer(final Context ctx) { 350 | ChaincodeStub stub = ctx.getStub(); 351 | Map transientMap = ctx.getStub().getTransient(); 352 | if (!transientMap.containsKey("asset_value")) { 353 | String errorMessage = String.format("AgreeToTransfer call must specify \"asset_value\" in Transient map input"); 354 | System.err.println(errorMessage); 355 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 356 | } 357 | 358 | byte[] transientAssetJSON = transientMap.get("asset_value"); 359 | AssetPrivateDetails assetPriv; 360 | String assetID; 361 | try { 362 | JSONObject json = new JSONObject(new String(transientAssetJSON, UTF_8)); 363 | assetID = json.getString("assetID"); 364 | final int appraisedValue = json.getInt("appraisedValue"); 365 | 366 | assetPriv = new AssetPrivateDetails(assetID, appraisedValue); 367 | } catch (Exception err) { 368 | String errorMessage = String.format("TransientMap deserialized error %s ", err); 369 | System.err.println(errorMessage); 370 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 371 | } 372 | 373 | if (assetID.equals("")) { 374 | String errorMessage = String.format("Invalid input in Transient map: assetID"); 375 | System.err.println(errorMessage); 376 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 377 | } 378 | if (assetPriv.getAppraisedValue() <= 0) { // appraisedValue field must be a positive integer 379 | String errorMessage = String.format("Input must be positive integer: appraisedValue"); 380 | System.err.println(errorMessage); 381 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 382 | } 383 | System.out.printf("AgreeToTransfer: verify asset %s exists\n", assetID); 384 | Asset existing = ReadAsset(ctx, assetID); 385 | if (existing == null) { 386 | String errorMessage = String.format("Asset does not exist in the collection: ", assetID); 387 | System.err.println(errorMessage); 388 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 389 | } 390 | // Get collection name for this organization. 391 | String orgCollectionName = getCollectionName(ctx); 392 | 393 | verifyClientOrgMatchesPeerOrg(ctx); 394 | 395 | // Save AssetPrivateDetails to org collection 396 | System.out.printf("Put AssetPrivateDetails: collection %s, ID %s\n", orgCollectionName, assetID); 397 | stub.putPrivateData(orgCollectionName, assetID, assetPriv.serialize()); 398 | 399 | String clientID = ctx.getClientIdentity().getId(); 400 | // Write the AgreeToTransfer key in assetCollection 401 | CompositeKey aggKey = stub.createCompositeKey(AGREEMENT_KEYPREFIX, assetID); 402 | System.out.printf("AgreeToTransfer Put: collection %s, ID %s, Key %s\n", ASSET_COLLECTION_NAME, assetID, aggKey); 403 | stub.putPrivateData(ASSET_COLLECTION_NAME, aggKey.toString(), clientID); 404 | } 405 | 406 | /** 407 | * TransferAsset transfers the asset to the new owner by setting a new owner ID based on 408 | * AgreeToTransfer data 409 | * 410 | * @param ctx the transaction context 411 | * @return none 412 | */ 413 | @Transaction(intent = Transaction.TYPE.SUBMIT) 414 | public void TransferAsset(final Context ctx) { 415 | ChaincodeStub stub = ctx.getStub(); 416 | Map transientMap = ctx.getStub().getTransient(); 417 | if (!transientMap.containsKey("asset_owner")) { 418 | String errorMessage = "TransferAsset call must specify \"asset_owner\" in Transient map input"; 419 | System.err.println(errorMessage); 420 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 421 | } 422 | 423 | byte[] transientAssetJSON = transientMap.get("asset_owner"); 424 | final String assetID; 425 | final String buyerMSP; 426 | try { 427 | JSONObject json = new JSONObject(new String(transientAssetJSON, UTF_8)); 428 | assetID = json.getString("assetID"); 429 | buyerMSP = json.getString("buyerMSP"); 430 | 431 | } catch (Exception err) { 432 | String errorMessage = String.format("TransientMap deserialized error %s ", err); 433 | System.err.println(errorMessage); 434 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 435 | } 436 | 437 | if (assetID.equals("")) { 438 | String errorMessage = String.format("Invalid input in Transient map: " + "assetID"); 439 | System.err.println(errorMessage); 440 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 441 | } 442 | if (buyerMSP.equals("")) { 443 | String errorMessage = String.format("Invalid input in Transient map: " + "buyerMSP"); 444 | System.err.println(errorMessage); 445 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 446 | } 447 | 448 | System.out.printf("TransferAsset: verify asset %s exists\n", assetID); 449 | byte[] assetJSON = stub.getPrivateData(ASSET_COLLECTION_NAME, assetID); 450 | 451 | if (assetJSON == null || assetJSON.length == 0) { 452 | String errorMessage = String.format("Asset %s does not exist in the collection", assetID); 453 | System.err.println(errorMessage); 454 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 455 | } 456 | 457 | verifyClientOrgMatchesPeerOrg(ctx); 458 | Asset thisAsset = Asset.deserialize(assetJSON); 459 | // Verify transfer details and transfer owner 460 | verifyAgreement(ctx, assetID, thisAsset.getOwner(), buyerMSP); 461 | 462 | TransferAgreement transferAgreement = ReadTransferAgreement(ctx, assetID); 463 | if (transferAgreement == null) { 464 | String errorMessage = String.format("TransferAgreement does not exist for asset: %s", assetID); 465 | System.err.println(errorMessage); 466 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 467 | } 468 | 469 | // Transfer asset in private data collection to new owner 470 | String newOwner = transferAgreement.getBuyerID(); 471 | thisAsset.setOwner(newOwner); 472 | 473 | // Save updated Asset to collection 474 | System.out.printf("Transfer Asset: collection %s, ID %s to owner %s\n", ASSET_COLLECTION_NAME, assetID, newOwner); 475 | stub.putPrivateData(ASSET_COLLECTION_NAME, assetID, thisAsset.serialize()); 476 | 477 | // Delete the key from owners collection 478 | String ownersCollectionName = getCollectionName(ctx); 479 | stub.delPrivateData(ownersCollectionName, assetID); 480 | 481 | // Delete the transfer agreement from the asset collection 482 | CompositeKey aggKey = stub.createCompositeKey(AGREEMENT_KEYPREFIX, assetID); 483 | System.out.printf("AgreeToTransfer deleteKey: collection %s, ID %s, Key %s\n", ASSET_COLLECTION_NAME, assetID, aggKey); 484 | stub.delPrivateData(ASSET_COLLECTION_NAME, aggKey.toString()); 485 | } 486 | 487 | /** 488 | * Deletes a asset & related details from the ledger. 489 | * Input in transient map: asset_delete 490 | * 491 | * This deletes the private data, but does not trigger an immediate cleanup 492 | * of the history. To specifically force removal right now use purge 493 | * 494 | * @param ctx the transaction context 495 | */ 496 | @Transaction(intent = Transaction.TYPE.SUBMIT) 497 | public void DeleteAsset(final Context ctx) { 498 | ChaincodeStub stub = ctx.getStub(); 499 | Map transientMap = ctx.getStub().getTransient(); 500 | if (!transientMap.containsKey("asset_delete")) { 501 | String errorMessage = String.format("DeleteAsset call must specify 'asset_delete' in Transient map input"); 502 | System.err.println(errorMessage); 503 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 504 | } 505 | 506 | byte[] transientAssetJSON = transientMap.get("asset_delete"); 507 | final String assetID; 508 | 509 | try { 510 | JSONObject json = new JSONObject(new String(transientAssetJSON, UTF_8)); 511 | assetID = json.getString("assetID"); 512 | 513 | } catch (Exception err) { 514 | String errorMessage = String.format("TransientMap deserialized error: %s ", err); 515 | System.err.println(errorMessage); 516 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 517 | } 518 | 519 | System.out.printf("DeleteAsset: verify asset %s exists\n", assetID); 520 | byte[] assetJSON = stub.getPrivateData(ASSET_COLLECTION_NAME, assetID); 521 | 522 | if (assetJSON == null || assetJSON.length == 0) { 523 | String errorMessage = String.format("Asset %s does not exist", assetID); 524 | System.err.println(errorMessage); 525 | throw new ChaincodeException(errorMessage, AssetTransferErrors.ASSET_NOT_FOUND.toString()); 526 | } 527 | String ownersCollectionName = getCollectionName(ctx); 528 | byte[] apdJSON = stub.getPrivateData(ownersCollectionName, assetID); 529 | 530 | if (apdJSON == null || apdJSON.length == 0) { 531 | String errorMessage = String.format("Failed to read asset from owner's Collection %s", ownersCollectionName); 532 | System.err.println(errorMessage); 533 | throw new ChaincodeException(errorMessage, AssetTransferErrors.ASSET_NOT_FOUND.toString()); 534 | } 535 | verifyClientOrgMatchesPeerOrg(ctx); 536 | 537 | // delete the key from asset collection 538 | System.out.printf("DeleteAsset: collection %s, ID %s\n", ASSET_COLLECTION_NAME, assetID); 539 | stub.delPrivateData(ASSET_COLLECTION_NAME, assetID); 540 | 541 | // Finally, delete private details of asset 542 | stub.delPrivateData(ownersCollectionName, assetID); 543 | } 544 | 545 | /** 546 | * Purges the history of the asset from Private Data 547 | * (delete does not need to be called as well) 548 | * Input in transient map: asset_delete 549 | * 550 | * @param ctx the transaction context 551 | */ 552 | @Transaction(intent = Transaction.TYPE.SUBMIT) 553 | public void PurgeAsset(final Context ctx) { 554 | ChaincodeStub stub = ctx.getStub(); 555 | Map transientMap = ctx.getStub().getTransient(); 556 | if (!transientMap.containsKey("asset_purge")) { 557 | String errorMessage = String.format("PurgeAsset call must specify 'asset_purge' in Transient map input"); 558 | System.err.println(errorMessage); 559 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 560 | } 561 | 562 | byte[] transientAssetJSON = transientMap.get("asset_purge"); 563 | final String assetID; 564 | 565 | try { 566 | JSONObject json = new JSONObject(new String(transientAssetJSON, UTF_8)); 567 | assetID = json.getString("assetID"); 568 | 569 | } catch (Exception err) { 570 | String errorMessage = String.format("TransientMap deserialized error: %s ", err); 571 | System.err.println(errorMessage); 572 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString()); 573 | } 574 | 575 | // Note that there is no check here to see if the id exist; it might have been 'deleted' already 576 | // so a check here is pointless. We would need to call purge irrespective of the result 577 | // A delete can be called before purge, but is not essential 578 | 579 | String ownersCollectionName = getCollectionName(ctx); 580 | verifyClientOrgMatchesPeerOrg(ctx); 581 | 582 | // delete the key from asset collection 583 | System.out.printf("PurgeAsset: collection %s, ID %s\n", ASSET_COLLECTION_NAME, assetID); 584 | stub.purgePrivateData(ASSET_COLLECTION_NAME, assetID); 585 | 586 | // Finally, delete private details of asset 587 | System.out.printf("PurgeAsset: collection %s, ID %s\n", ownersCollectionName, assetID); 588 | stub.purgePrivateData(ownersCollectionName, assetID); 589 | } 590 | 591 | 592 | // Used by TransferAsset to verify that the transfer is being initiated by the owner and that 593 | // the buyer has agreed to the same appraisal value as the owner 594 | private void verifyAgreement(final Context ctx, final String assetID, final String owner, final String buyerMSP) { 595 | String clienID = ctx.getClientIdentity().getId(); 596 | 597 | // Check 1: verify that the transfer is being initiatied by the owner 598 | if (!clienID.equals(owner)) { 599 | throw new ChaincodeException("Submitting client identity does not own the asset", AssetTransferErrors.INVALID_ACCESS.toString()); 600 | } 601 | 602 | // Check 2: verify that the buyer has agreed to the appraised value 603 | String collectionOwner = getCollectionName(ctx); // get owner collection from caller identity 604 | String collectionBuyer = buyerMSP + "PrivateCollection"; 605 | 606 | // Get hash of owners agreed to value 607 | byte[] ownerAppraisedValueHash = ctx.getStub().getPrivateDataHash(collectionOwner, assetID); 608 | if (ownerAppraisedValueHash == null) { 609 | throw new ChaincodeException(String.format("Hash of appraised value for %s does not exist in collection %s", assetID, collectionOwner)); 610 | } 611 | 612 | // Get hash of buyers agreed to value 613 | byte[] buyerAppraisedValueHash = ctx.getStub().getPrivateDataHash(collectionBuyer, assetID); 614 | if (buyerAppraisedValueHash == null) { 615 | throw new ChaincodeException(String.format("Hash of appraised value for %s does not exist in collection %s. AgreeToTransfer must be called by the buyer first.", assetID, collectionBuyer)); 616 | } 617 | 618 | // Verify that the two hashes match 619 | if (!Arrays.equals(ownerAppraisedValueHash, buyerAppraisedValueHash)) { 620 | throw new ChaincodeException(String.format("Hash for appraised value for owner %x does not match value for seller %x", ownerAppraisedValueHash, buyerAppraisedValueHash)); 621 | } 622 | } 623 | 624 | private void verifyClientOrgMatchesPeerOrg(final Context ctx) { 625 | String clientMSPID = ctx.getClientIdentity().getMSPID(); 626 | String peerMSPID = ctx.getStub().getMspId(); 627 | 628 | if (!peerMSPID.equals(clientMSPID)) { 629 | String errorMessage = String.format("Client from org %s is not authorized to read or write private data from an org %s peer", clientMSPID, peerMSPID); 630 | System.err.println(errorMessage); 631 | throw new ChaincodeException(errorMessage, AssetTransferErrors.INVALID_ACCESS.toString()); 632 | } 633 | } 634 | 635 | private String getCollectionName(final Context ctx) { 636 | 637 | // Get the MSP ID of submitting client identity 638 | String clientMSPID = ctx.getClientIdentity().getMSPID(); 639 | // Create the collection name 640 | return clientMSPID + "PrivateCollection"; 641 | } 642 | 643 | } 644 | --------------------------------------------------------------------------------