mirror of
https://github.com/hyperledger/fabric-samples.git
synced 2026-06-17 15:35:09 +00:00
Java erc721 token standard chaincode implementation. (#709)
* Java ERC721 token standard chaincode implementation Signed-off-by: renjithpta <renjithkn@gmail.com> Signed-off-by: renjithpta <renjithkn@gmail.com> * Java erc20 nft token standard chaincode implementation. Signed-off-by: renjithpta <renjithkn@gmail.com> Signed-off-by: renjithpta <renjithkn@gmail.com>
This commit is contained in:
parent
40bfa49a80
commit
1617406795
19 changed files with 1980 additions and 0 deletions
30
token-erc-721/chaincode-java/Dockerfile
Executable file
30
token-erc-721/chaincode-java/Dockerfile
Executable file
|
|
@ -0,0 +1,30 @@
|
|||
# the first stage
|
||||
FROM gradle:jdk11 AS GRADLE_BUILD
|
||||
|
||||
# copy the build.gradle and src code to the container
|
||||
COPY src/ src/
|
||||
COPY build.gradle ./
|
||||
|
||||
# Build and package our code
|
||||
RUN gradle --no-daemon build shadowJar -x checkstyleMain -x checkstyleTest
|
||||
|
||||
# the second stage of our build just needs the compiled files
|
||||
FROM openjdk:11-jre
|
||||
ARG CC_SERVER_PORT=9999
|
||||
|
||||
# Setup tini to work better handle signals
|
||||
ENV TINI_VERSION v0.19.0
|
||||
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini
|
||||
RUN chmod +x /tini
|
||||
|
||||
RUN addgroup --system javauser && useradd -g javauser javauser
|
||||
|
||||
# copy only the artifacts we need from the first stage and discard the rest
|
||||
COPY --chown=javauser:javauser --from=GRADLE_BUILD /home/gradle/build/libs/chaincode.jar /chaincode.jar
|
||||
COPY --chown=javauser:javauser docker/docker-entrypoint.sh /docker-entrypoint.sh
|
||||
RUN chmod +x /docker-entrypoint.sh
|
||||
ENV PORT $CC_SERVER_PORT
|
||||
EXPOSE $CC_SERVER_PORT
|
||||
|
||||
USER javauser
|
||||
ENTRYPOINT [ "/tini", "--", "/docker-entrypoint.sh" ]
|
||||
91
token-erc-721/chaincode-java/build.gradle
Executable file
91
token-erc-721/chaincode-java/build.gradle
Executable file
|
|
@ -0,0 +1,91 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id 'com.github.johnrengelman.shadow' version '5.1.0'
|
||||
id 'application'
|
||||
id 'checkstyle'
|
||||
id 'jacoco'
|
||||
}
|
||||
|
||||
group 'org.hyperledger.fabric.samples'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.4.1'
|
||||
implementation 'org.json:json:+'
|
||||
implementation 'com.owlike:genson:1.5'
|
||||
testImplementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.4.1'
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter:5.4.2'
|
||||
testImplementation 'org.assertj:assertj-core:3.11.1'
|
||||
testImplementation 'org.mockito:mockito-core:2.23.4'
|
||||
testRuntimeOnly("net.bytebuddy:byte-buddy:1.10.6")
|
||||
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven {
|
||||
url 'https://jitpack.io'
|
||||
}
|
||||
}
|
||||
|
||||
application {
|
||||
mainClass = 'org.hyperledger.fabric.contract.ContractRouter'
|
||||
}
|
||||
|
||||
checkstyle {
|
||||
toolVersion '8.21'
|
||||
configFile file("config/checkstyle/checkstyle.xml")
|
||||
}
|
||||
|
||||
checkstyleMain {
|
||||
source ='src/main/java'
|
||||
}
|
||||
|
||||
checkstyleTest {
|
||||
source ='src/test/java'
|
||||
}
|
||||
|
||||
jacocoTestReport {
|
||||
dependsOn test
|
||||
}
|
||||
|
||||
jacocoTestCoverageVerification {
|
||||
violationRules {
|
||||
rule {
|
||||
limit {
|
||||
minimum = 0.8
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
finalizedBy jacocoTestReport
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
testLogging {
|
||||
showStandardStreams = true
|
||||
}
|
||||
testLogging {
|
||||
events "passed", "skipped", "failed"
|
||||
}
|
||||
}
|
||||
|
||||
mainClassName = 'org.hyperledger.fabric.contract.ContractRouter'
|
||||
|
||||
shadowJar {
|
||||
baseName = 'chaincode'
|
||||
version = null
|
||||
classifier = null
|
||||
|
||||
manifest {
|
||||
attributes 'Main-Class': 'org.hyperledger.fabric.contract.ContractRouter'
|
||||
}
|
||||
}
|
||||
|
||||
check.dependsOn jacocoTestCoverageVerification
|
||||
installDist.dependsOn check
|
||||
174
token-erc-721/chaincode-java/config/checkstyle/checkstyle.xml
Normal file
174
token-erc-721/chaincode-java/config/checkstyle/checkstyle.xml
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
<?xml version="1.0"?>
|
||||
<!DOCTYPE module PUBLIC
|
||||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
|
||||
<!--
|
||||
|
||||
Checkstyle configuration that matches the Eclipse formatter
|
||||
|
||||
Checkstyle is very configurable. Be sure to read the documentation at
|
||||
http://checkstyle.sourceforge.net (or in your downloaded distribution).
|
||||
|
||||
Most Checks are configurable, be sure to consult the documentation.
|
||||
|
||||
To completely disable a check, just comment it out or delete it from the file.
|
||||
|
||||
Finally, it is worth reading the documentation.
|
||||
|
||||
-->
|
||||
|
||||
<module name="Checker">
|
||||
<!--
|
||||
If you set the basedir property below, then all reported file
|
||||
names will be relative to the specified directory. See
|
||||
https://checkstyle.org/5.x/config.html#Checker
|
||||
|
||||
<property name="basedir" value="${basedir}"/>
|
||||
-->
|
||||
|
||||
<property name="fileExtensions" value="java, properties, xml"/>
|
||||
|
||||
<module name="SuppressionFilter">
|
||||
<property name="file" value="${config_loc}/suppressions.xml"/>
|
||||
<property name="optional" value="false"/>
|
||||
</module>
|
||||
|
||||
<!-- Excludes all 'module-info.java' files -->
|
||||
<!-- See https://checkstyle.org/config_filefilters.html -->
|
||||
<module name="BeforeExecutionExclusionFileFilter">
|
||||
<property name="fileNamePattern" value="module\-info\.java$"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks that a package-info.java file exists for each package. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_javadoc.html#JavadocPackage -->
|
||||
<!-- <module name="JavadocPackage"/> -->
|
||||
|
||||
<!-- Checks whether files end with a new line. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_misc.html#NewlineAtEndOfFile -->
|
||||
<module name="NewlineAtEndOfFile"/>
|
||||
|
||||
<!-- Checks that property files contain the same keys. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_misc.html#Translation -->
|
||||
<module name="Translation"/>
|
||||
|
||||
<!-- Checks for Size Violations. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_sizes.html -->
|
||||
<module name="FileLength"/>
|
||||
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_whitespace.html -->
|
||||
<module name="FileTabCharacter"/>
|
||||
|
||||
<!-- Miscellaneous other checks. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_misc.html -->
|
||||
<module name="RegexpSingleline">
|
||||
<property name="format" value="\s+$"/>
|
||||
<property name="minimum" value="0"/>
|
||||
<property name="maximum" value="0"/>
|
||||
<property name="message" value="Line has trailing spaces."/>
|
||||
</module>
|
||||
|
||||
|
||||
|
||||
<!-- Checks for Headers -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_header.html -->
|
||||
<!-- <module name="Header"> -->
|
||||
<!-- <property name="headerFile" value="${checkstyle.header.file}"/> -->
|
||||
<!-- <property name="fileExtensions" value="java"/> -->
|
||||
<!-- </module> -->
|
||||
|
||||
<module name="TreeWalker">
|
||||
|
||||
<!-- Checks for Javadoc comments. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_javadoc.html -->
|
||||
<!-- <module name="JavadocMethod"/> -->
|
||||
<!-- <module name="JavadocType"/> -->
|
||||
<!-- <module name="JavadocVariable"/> -->
|
||||
<!-- <module name="JavadocStyle"/> -->
|
||||
<!-- <module name="MissingJavadocMethod"/> -->
|
||||
|
||||
<!-- Checks for Naming Conventions. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_naming.html -->
|
||||
<module name="ConstantName"/>
|
||||
<module name="LocalFinalVariableName"/>
|
||||
<module name="LocalVariableName"/>
|
||||
<module name="PackageName"/>
|
||||
<module name="StaticVariableName"/>
|
||||
<module name="TypeName"/>
|
||||
|
||||
<!-- Checks for imports -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_import.html -->
|
||||
<module name="AvoidStarImport"/>
|
||||
<module name="IllegalImport"/> <!-- defaults to sun.* packages -->
|
||||
<module name="RedundantImport"/>
|
||||
<module name="UnusedImports">
|
||||
<property name="processJavadoc" value="false"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for Size Violations. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_sizes.html -->
|
||||
<module name="MethodLength"/>
|
||||
<module name="ParameterNumber"/>
|
||||
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_whitespace.html -->
|
||||
<module name="EmptyForIteratorPad"/>
|
||||
<module name="GenericWhitespace"/>
|
||||
<module name="MethodParamPad"/>
|
||||
<module name="NoWhitespaceAfter"/>
|
||||
<module name="NoWhitespaceBefore"/>
|
||||
<module name="OperatorWrap"/>
|
||||
<module name="ParenPad"/>
|
||||
<module name="TypecastParenPad"/>
|
||||
<module name="WhitespaceAfter"/>
|
||||
<module name="WhitespaceAround"/>
|
||||
|
||||
<!-- Modifier Checks -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_modifiers.html -->
|
||||
<module name="ModifierOrder"/>
|
||||
<module name="RedundantModifier"/>
|
||||
|
||||
<!-- Checks for blocks. You know, those {}'s -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_blocks.html -->
|
||||
<module name="AvoidNestedBlocks"/>
|
||||
<module name="EmptyBlock"/>
|
||||
<module name="LeftCurly"/>
|
||||
<module name="NeedBraces"/>
|
||||
<module name="RightCurly"/>
|
||||
|
||||
<!-- Checks for common coding problems -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_coding.html -->
|
||||
<module name="EmptyStatement"/>
|
||||
<module name="EqualsHashCode"/>
|
||||
<module name="HiddenField">
|
||||
<property name="ignoreSetter" value="true" />
|
||||
<property name="ignoreConstructorParameter" value="true"/>
|
||||
</module>
|
||||
<module name="IllegalInstantiation"/>
|
||||
<module name="InnerAssignment"/>
|
||||
<module name="MissingSwitchDefault"/>
|
||||
<module name="MultipleVariableDeclarations"/>
|
||||
<module name="SimplifyBooleanExpression"/>
|
||||
<module name="SimplifyBooleanReturn"/>
|
||||
|
||||
<!-- Checks for class design -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_design.html -->
|
||||
<module name="DesignForExtension"/>
|
||||
<module name="FinalClass"/>
|
||||
<module name="HideUtilityClassConstructor"/>
|
||||
<module name="InterfaceIsType"/>
|
||||
<module name="VisibilityModifier">
|
||||
<property name="allowPublicFinalFields" value="true"/>
|
||||
</module>
|
||||
|
||||
<!-- Miscellaneous other checks. -->
|
||||
<!-- See http://checkstyle.sourceforge.net/config_misc.html -->
|
||||
<module name="ArrayTypeStyle"/>
|
||||
<module name="FinalParameters"/>
|
||||
<module name="TodoComment"/>
|
||||
<module name="UpperEll"/>
|
||||
|
||||
</module>
|
||||
|
||||
</module>
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0"?>
|
||||
|
||||
<!DOCTYPE suppressions PUBLIC
|
||||
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
|
||||
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
|
||||
|
||||
<suppressions>
|
||||
<suppress files="ERC721TokenContract.java"
|
||||
checks="ParameterNumber" />
|
||||
<suppress files="NFT.java" checks="HiddenFiled" />
|
||||
<suppress files="Transfer.java" checks="HiddenFiled" />
|
||||
<suppress files="Approval.java" checks="HiddenFiled" />
|
||||
</suppressions>
|
||||
16
token-erc-721/chaincode-java/docker/docker-entrypoint.sh
Executable file
16
token-erc-721/chaincode-java/docker/docker-entrypoint.sh
Executable file
|
|
@ -0,0 +1,16 @@
|
|||
#!/usr/bin/env bash
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
set -euo pipefail
|
||||
: ${CORE_PEER_TLS_ENABLED:="false"}
|
||||
: ${DEBUG:="false"}
|
||||
|
||||
if [ "${DEBUG,,}" = "true" ]; then
|
||||
exec java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0.0.0.0:8000 -jar /chaincode.jar
|
||||
elif [ "${CORE_PEER_TLS_ENABLED,,}" = "true" ]; then
|
||||
exec java -jar /chaincode.jar # todo
|
||||
else
|
||||
exec java -jar /chaincode.jar
|
||||
fi
|
||||
|
||||
BIN
token-erc-721/chaincode-java/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
token-erc-721/chaincode-java/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
token-erc-721/chaincode-java/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
token-erc-721/chaincode-java/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
token-erc-721/chaincode-java/gradlew
vendored
Executable file
234
token-erc-721/chaincode-java/gradlew
vendored
Executable file
|
|
@ -0,0 +1,234 @@
|
|||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
100
token-erc-721/chaincode-java/gradlew.bat
vendored
Executable file
100
token-erc-721/chaincode-java/gradlew.bat
vendored
Executable file
|
|
@ -0,0 +1,100 @@
|
|||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
5
token-erc-721/chaincode-java/settings.gradle
Executable file
5
token-erc-721/chaincode-java/settings.gradle
Executable file
|
|
@ -0,0 +1,5 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
rootProject.name = 'erc721'
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
package org.hyperledger.fabric.samples.erc721;
|
||||
|
||||
public enum ContractConstants {
|
||||
BALANCE("balance"),
|
||||
NFT("nft"),
|
||||
APPROVAL("approval"),
|
||||
NAMEKEY("nameKey"),
|
||||
SYMBOLKEY("symbolKey"),
|
||||
APPROVE_FOR_ALL("ApproveForAll"),
|
||||
TRANSFER("Transfer"),
|
||||
MINTER_ORG_MSP("Org1MSP");
|
||||
private final String prefix;
|
||||
|
||||
ContractConstants(final String value) {
|
||||
this.prefix = value;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return prefix;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
package org.hyperledger.fabric.samples.erc721;
|
||||
|
||||
public enum ContractErrors {
|
||||
TOKEN_NOT_FOUND,
|
||||
TOKEN_ALREADY_EXITS,
|
||||
NO_OWNER_ASSIGNED,
|
||||
UNAUTHORIZED_SENDER,
|
||||
TOKEN_NONOWNER,
|
||||
INVALID_TOKEN_OWNER
|
||||
}
|
||||
|
|
@ -0,0 +1,440 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
package org.hyperledger.fabric.samples.erc721;
|
||||
|
||||
import org.hyperledger.fabric.contract.Context;
|
||||
import org.hyperledger.fabric.contract.ContractInterface;
|
||||
import org.hyperledger.fabric.contract.annotation.Transaction;
|
||||
import org.hyperledger.fabric.contract.annotation.Default;
|
||||
import org.hyperledger.fabric.contract.annotation.Info;
|
||||
import org.hyperledger.fabric.contract.annotation.License;
|
||||
import org.hyperledger.fabric.contract.annotation.Contact;
|
||||
import org.hyperledger.fabric.contract.annotation.Contract;
|
||||
import org.hyperledger.fabric.samples.erc721.models.Approval;
|
||||
import org.hyperledger.fabric.samples.erc721.models.NFT;
|
||||
import org.hyperledger.fabric.samples.erc721.models.Transfer;
|
||||
import org.hyperledger.fabric.shim.ChaincodeException;
|
||||
import org.hyperledger.fabric.shim.ChaincodeStub;
|
||||
import org.hyperledger.fabric.shim.ledger.CompositeKey;
|
||||
import org.hyperledger.fabric.shim.ledger.KeyValue;
|
||||
import org.hyperledger.fabric.shim.ledger.QueryResultsIterator;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static org.hyperledger.fabric.samples.erc721.utils.ContractUtility.stringIsNullOrEmpty;
|
||||
|
||||
@Contract(
|
||||
name = "erc721token",
|
||||
info =
|
||||
@Info(
|
||||
title = "ERC721Token Contract",
|
||||
description = "The erc721 NFT implementation",
|
||||
version = "0.0.1-SNAPSHOT",
|
||||
license =
|
||||
@License(
|
||||
name = "Apache 2.0 License",
|
||||
url = "http://www.apache.org/licenses/LICENSE-2.0.html"),
|
||||
contact =
|
||||
@Contact(
|
||||
email = "renjith.narayanan@gmail.com",
|
||||
name = "Renjith Narayanan",
|
||||
url = "https://hyperledger.example.com")))
|
||||
@Default
|
||||
public class ERC721TokenContract implements ContractInterface {
|
||||
|
||||
/**
|
||||
* BalanceOf counts all non-fungible tokens assigned to an owner.There is a key record for every
|
||||
* non-fungible token in the format of balancePrefix.owner.tokenId. balanceOf() queries for and
|
||||
* counts all records matching balancePrefix.owner.*
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param owner An owner for whom to query the balance
|
||||
* @return The number of non-fungible tokens owned by the owner, possibly zero
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public long BalanceOf(final Context ctx, final String owner) {
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
final CompositeKey balanceKey =
|
||||
stub.createCompositeKey(ContractConstants.BALANCE.getValue(), owner);
|
||||
final QueryResultsIterator<KeyValue> results = stub.getStateByPartialCompositeKey(balanceKey);
|
||||
long balance = 0;
|
||||
for (KeyValue result : results) {
|
||||
if (!stringIsNullOrEmpty(result.getStringValue())) {
|
||||
balance++;
|
||||
}
|
||||
}
|
||||
return balance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the owner of a non-fungible token.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param tokenId the identifier for a non-fungible token.
|
||||
* @return return the owner of the non-fungible token.
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public String OwnerOf(final Context ctx, final String tokenId) {
|
||||
final NFT nft = this._readNft(ctx, tokenId);
|
||||
if (stringIsNullOrEmpty(nft.getOwner())) {
|
||||
final String errorMessage = String.format("No owner is assigned o the token %s", tokenId);
|
||||
throw new ChaincodeException(errorMessage, ContractErrors.NO_OWNER_ASSIGNED.toString());
|
||||
}
|
||||
return nft.getOwner();
|
||||
}
|
||||
|
||||
/**
|
||||
* It returns if a client is an authorized operator for another client.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param owner The client that owns the non-fungible tokens
|
||||
* @param operator The client that acts on behalf of the owner
|
||||
* @return Return true if the operator is an approved operator for the owner, false otherwise
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public boolean IsApprovedForAll(final Context ctx, final String owner, final String operator) {
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
final CompositeKey approvalKey =
|
||||
stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), owner, operator);
|
||||
final String approvalJson = stub.getStringState(approvalKey.toString());
|
||||
if (stringIsNullOrEmpty(approvalJson)) {
|
||||
return false;
|
||||
} else {
|
||||
final Approval approval = Approval.fromJSONString(approvalJson);
|
||||
return approval.isApproved();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Approve changes or reaffirms the approved client for a non-fungible token. The function update
|
||||
* the approved operator of the non-fungible token.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param operator: operator The new approved client
|
||||
* @param tokenId: tokenId the non-fungible token to approve
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.SUBMIT)
|
||||
public void Approve(final Context ctx, final String operator, final String tokenId) {
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
final String sender = ctx.getClientIdentity().getId();
|
||||
NFT nft = this._readNft(ctx, tokenId);
|
||||
final String owner = nft.getOwner();
|
||||
final boolean operatorApproval = this.IsApprovedForAll(ctx, owner, sender);
|
||||
if ((!owner.equalsIgnoreCase(sender)) && (!operatorApproval)) {
|
||||
final String errorMessage =
|
||||
String.format(
|
||||
"The sender %s is not the current owner nor an authorized operator of the token %s.",
|
||||
sender, tokenId);
|
||||
throw new ChaincodeException(errorMessage, ContractErrors.UNAUTHORIZED_SENDER.toString());
|
||||
}
|
||||
|
||||
nft.setApproved(operator);
|
||||
final CompositeKey nftKey = stub.createCompositeKey(ContractConstants.NFT.getValue(), tokenId);
|
||||
stub.putStringState(nftKey.toString(), nft.toJSONString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables or disables approval for a third party ("operator") to manage all the message sender's
|
||||
* assets.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param operator A client to add to the set of authorized operators
|
||||
* @param approved: True if the operator is approved, false to revoke approval
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.SUBMIT)
|
||||
public void SetApprovalForAll(final Context ctx, final String operator, final boolean approved) {
|
||||
final String sender = ctx.getClientIdentity().getId();
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
final Approval nftApproval = new Approval(sender, operator, approved);
|
||||
final CompositeKey approvalKey =
|
||||
stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), sender, operator);
|
||||
stub.putStringState(approvalKey.toString(), nftApproval.toJSONString());
|
||||
stub.setEvent(
|
||||
ContractConstants.APPROVE_FOR_ALL.getValue(), nftApproval.toJSONString().getBytes(UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the approved client for a single non-fungible token.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param tokenId The non-fungible token to find the approved client for
|
||||
* @return Return The approved client for this non-fungible token, or null if there is none
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public String GetApproved(final Context ctx, final String tokenId) {
|
||||
final NFT nft = this._readNft(ctx, tokenId);
|
||||
return nft.getApproved();
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfers the ownership of a non-fungible token from one owner to another owner.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param from the current owner of the non-fungible token
|
||||
* @param to the new token owner
|
||||
* @param tokenId The non-fungible token to transfer
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.SUBMIT)
|
||||
public void TransferFrom(
|
||||
final Context ctx, final String from, final String to, final String tokenId) {
|
||||
final String sender = ctx.getClientIdentity().getId();
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
NFT nft = this._readNft(ctx, tokenId);
|
||||
final String owner = nft.getOwner();
|
||||
final String operator = nft.getApproved();
|
||||
final boolean operatorApproval = this.IsApprovedForAll(ctx, owner, sender);
|
||||
if ((!owner.equalsIgnoreCase(sender))
|
||||
&& !operator.equalsIgnoreCase(sender)
|
||||
&& !operatorApproval) {
|
||||
final String errorMessage =
|
||||
String.format(
|
||||
"The sender %s is not the current owner nor an authorized operator of the token %s.",
|
||||
sender, tokenId);
|
||||
throw new ChaincodeException(errorMessage, ContractErrors.UNAUTHORIZED_SENDER.toString());
|
||||
}
|
||||
|
||||
// Check if `from` is the current owner
|
||||
if (!owner.equalsIgnoreCase(from)) {
|
||||
throw new ChaincodeException(
|
||||
String.format("The from %s is not the current owner of the token %s.", from, tokenId),
|
||||
ContractErrors.INVALID_TOKEN_OWNER.toString());
|
||||
}
|
||||
|
||||
// Clear the approved client for this non-fungible token
|
||||
nft.setApproved("");
|
||||
|
||||
// Overwrite a non-fungible token to assign a new owner.
|
||||
nft.setOwner(to);
|
||||
final CompositeKey nftKey = stub.createCompositeKey(ContractConstants.NFT.getValue(), tokenId);
|
||||
stub.putStringState(nftKey.toString(), nft.toJSONString());
|
||||
|
||||
// Remove a composite key from the balance of the current owner
|
||||
final CompositeKey balanceKeyFrom =
|
||||
stub.createCompositeKey(ContractConstants.BALANCE.getValue(), from, tokenId);
|
||||
stub.delState(balanceKeyFrom.toString());
|
||||
|
||||
// Save a composite key to count the balance of a new owner
|
||||
final CompositeKey balanceKeyTo =
|
||||
stub.createCompositeKey(ContractConstants.BALANCE.getValue(), to, tokenId);
|
||||
stub.putState(balanceKeyTo.toString(), Character.toString(Character.MIN_VALUE).getBytes(UTF_8));
|
||||
|
||||
// Emit the Transfer event
|
||||
final Transfer transferEvent = new Transfer(from, to, tokenId);
|
||||
stub.setEvent(
|
||||
ContractConstants.TRANSFER.getValue(), transferEvent.toJSONString().getBytes(UTF_8));
|
||||
}
|
||||
|
||||
// ============== ERC721 metadata extension ===============
|
||||
|
||||
/**
|
||||
* Returns a descriptive name for a collection of non-fungible tokens in this contract
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @return name of the token.
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public String Name(final Context ctx) {
|
||||
return ctx.getStub().getStringState(ContractConstants.NAMEKEY.getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an abbreviated name for non-fungible tokens in this contract.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @return token symbol.
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public String Symbol(final Context ctx) {
|
||||
return ctx.getStub().getStringState(ContractConstants.SYMBOLKEY.getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a distinct Uniform Resource Identifier (URI) for a given token.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param tokenId the identifier for a non-fungible token
|
||||
* @return : Returns the URI of the token
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public String TokenURI(final Context ctx, final String tokenId) {
|
||||
final NFT nft = this._readNft(ctx, tokenId);
|
||||
return nft.getTokenURI();
|
||||
}
|
||||
|
||||
/** ============= ERC721 enumeration extension =============== * */
|
||||
|
||||
/**
|
||||
* Counts non-fungible tokens tracked by this contract. There is a key record for every
|
||||
* non-fungible token in the format of nftPrefix.tokenId. The function queries for and counts all
|
||||
* records matching nftPrefix.*
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @return count of valid non-fungible tokens tracked by this contract,where each one of them has
|
||||
* an assigned and queryable owner.
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public long TotalSupply(final Context ctx) {
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
final CompositeKey nftKey = stub.createCompositeKey(ContractConstants.NFT.getValue());
|
||||
final QueryResultsIterator<KeyValue> iterator = stub.getStateByPartialCompositeKey(nftKey);
|
||||
long totalSupply = 0;
|
||||
for (KeyValue result : iterator) {
|
||||
if (!stringIsNullOrEmpty(result.getStringValue())) {
|
||||
totalSupply++;
|
||||
}
|
||||
}
|
||||
return totalSupply;
|
||||
}
|
||||
|
||||
/** ============== Extended Functions for this sample =============== * */
|
||||
|
||||
/**
|
||||
* Set optional information for a token.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param name The name of the token
|
||||
* @param symbol The symbol of the token
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.SUBMIT)
|
||||
public void SetOption(final Context ctx, final String name, final String symbol) {
|
||||
|
||||
final String clientMSPID = ctx.getClientIdentity().getMSPID();
|
||||
// Check minter authorization - this sample assumes Org1 is the issuer with privilege to set the
|
||||
// name and symbol
|
||||
if (!clientMSPID.equalsIgnoreCase(ContractConstants.MINTER_ORG_MSP.getValue())) {
|
||||
throw new ChaincodeException(
|
||||
"Client is not authorized to set the name and symbol of the token");
|
||||
}
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
stub.putStringState(ContractConstants.NAMEKEY.getValue(), name);
|
||||
stub.putStringState(ContractConstants.SYMBOLKEY.getValue(), symbol);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mint a new non-fungible token
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param tokenId Unique ID of the non-fungible token to be minted
|
||||
* @param tokenURI URI containing metadata of the minted non-fungible token
|
||||
* @return Return the non-fungible token object
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.SUBMIT)
|
||||
public NFT MintWithTokenURI(final Context ctx, final String tokenId, final String tokenURI) {
|
||||
final String clientMSPID = ctx.getClientIdentity().getMSPID();
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
// Check minter authorization this sample assumes Org1 is the issuer with privilege to mint a
|
||||
// new token
|
||||
if (!clientMSPID.equalsIgnoreCase(ContractConstants.MINTER_ORG_MSP.getValue())) {
|
||||
throw new ChaincodeException(
|
||||
"Client is not authorized to set the name and symbol of the token",
|
||||
ContractErrors.UNAUTHORIZED_SENDER.toString());
|
||||
}
|
||||
final String minter = ctx.getClientIdentity().getId();
|
||||
final boolean exists = this._nftExists(ctx, tokenId);
|
||||
if (exists) {
|
||||
throw new ChaincodeException(
|
||||
String.format("The token %s is already minted.", tokenId),
|
||||
ContractErrors.TOKEN_ALREADY_EXITS.toString());
|
||||
}
|
||||
final NFT nft = new NFT(tokenId, minter, tokenURI, "");
|
||||
final CompositeKey nftKey = stub.createCompositeKey(ContractConstants.NFT.getValue(), tokenId);
|
||||
stub.putStringState(nftKey.toString(), nft.toJSONString());
|
||||
// A composite key would be balancePrefix.owner.tokenId, which enables partial
|
||||
// composite key query to find and count all records matching balance.owner.*
|
||||
// An empty value would represent a delete, so we simply insert the null character.
|
||||
final CompositeKey balanceKey =
|
||||
stub.createCompositeKey(ContractConstants.BALANCE.getValue(), minter, tokenId);
|
||||
stub.putStringState(balanceKey.toString(), Character.toString(Character.MIN_VALUE));
|
||||
final Transfer transferEvent = new Transfer("0x0", minter, tokenId);
|
||||
stub.setEvent(
|
||||
ContractConstants.TRANSFER.getValue(), transferEvent.toJSONString().getBytes(UTF_8));
|
||||
return nft;
|
||||
}
|
||||
|
||||
/**
|
||||
* Burn a non-fungible token
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param tokenId Unique ID of a non-fungible token
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.SUBMIT)
|
||||
public void Burn(final Context ctx, final String tokenId) {
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
final String owner = ctx.getClientIdentity().getId();
|
||||
// Check if a caller is the owner of the non-fungible token
|
||||
final NFT nft = this._readNft(ctx, tokenId);
|
||||
if (!nft.getOwner().equalsIgnoreCase(owner)) {
|
||||
throw new ChaincodeException(
|
||||
String.format("Non-fungible token %s is not owned by %s", tokenId, owner),
|
||||
ContractErrors.TOKEN_NONOWNER.toString());
|
||||
}
|
||||
// Delete the token
|
||||
final CompositeKey nftKey = stub.createCompositeKey(ContractConstants.NFT.getValue(), tokenId);
|
||||
stub.delState(nftKey.toString());
|
||||
|
||||
// Remove a composite key from the balance of the owner
|
||||
final CompositeKey balanceKey =
|
||||
stub.createCompositeKey(ContractConstants.BALANCE.getValue(), owner, tokenId);
|
||||
stub.delState(balanceKey.toString());
|
||||
final Transfer transferEvent = new Transfer(owner, "0x0", tokenId);
|
||||
stub.setEvent(
|
||||
ContractConstants.TRANSFER.getValue(), transferEvent.toJSONString().getBytes(UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the balance of the requesting client's account.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @return the account balance
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public long ClientAccountBalance(final Context ctx) {
|
||||
return this.BalanceOf(ctx, ctx.getClientIdentity().getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the id of the requesting client's account.In this implementation, the client account ID
|
||||
* is the clientId itself. Users can use this function to get their own account id, which they can
|
||||
* then give to others as the payment address.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @return sender account id .
|
||||
*/
|
||||
@Transaction(intent = Transaction.TYPE.EVALUATE)
|
||||
public String ClientAccountID(final Context ctx) {
|
||||
return ctx.getClientIdentity().getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the the NFT details by token id.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param tokenId Unique ID of a non-fungible token
|
||||
* @return token details.
|
||||
*/
|
||||
private NFT _readNft(final Context ctx, final String tokenId) {
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
final CompositeKey nftKey = stub.createCompositeKey(ContractConstants.NFT.getValue(), tokenId);
|
||||
final String nft = stub.getStringState(nftKey.toString());
|
||||
if (stringIsNullOrEmpty(nft)) {
|
||||
final String errorMessage = String.format("Token with id %s not found!.", tokenId);
|
||||
throw new ChaincodeException(errorMessage, ContractErrors.TOKEN_NOT_FOUND.toString());
|
||||
}
|
||||
return NFT.fromJSONString(nft);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check NFT exits.
|
||||
*
|
||||
* @param ctx the transaction context
|
||||
* @param tokenId Unique ID of a non-fungible token
|
||||
* @return true if token exits else false.
|
||||
*/
|
||||
private boolean _nftExists(final Context ctx, final String tokenId) {
|
||||
final ChaincodeStub stub = ctx.getStub();
|
||||
final CompositeKey nftKey = stub.createCompositeKey(ContractConstants.NFT.getValue(), tokenId);
|
||||
final String nft = stub.getStringState(nftKey.toString());
|
||||
return ((stringIsNullOrEmpty(nft)) ? false : true);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
package org.hyperledger.fabric.samples.erc721.models;
|
||||
|
||||
import com.owlike.genson.Genson;
|
||||
import com.owlike.genson.annotation.JsonProperty;
|
||||
import org.hyperledger.fabric.contract.annotation.DataType;
|
||||
import org.hyperledger.fabric.contract.annotation.Property;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
@DataType()
|
||||
public final class Approval {
|
||||
|
||||
@Property()
|
||||
@JsonProperty("owner")
|
||||
private String owner;
|
||||
|
||||
@Property()
|
||||
@JsonProperty("operator")
|
||||
private String operator;
|
||||
|
||||
@Property()
|
||||
@JsonProperty("approved")
|
||||
private boolean approved;
|
||||
|
||||
/** Default constructor */
|
||||
public Approval() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor of the class
|
||||
*
|
||||
* @param owner
|
||||
* @param operator
|
||||
* @param approved
|
||||
*/
|
||||
public Approval(
|
||||
@JsonProperty("owner") final String owner,
|
||||
@JsonProperty("operator") final String operator,
|
||||
@JsonProperty("approved") final boolean approved) {
|
||||
super();
|
||||
this.owner = owner;
|
||||
this.operator = operator;
|
||||
this.approved = approved;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param data
|
||||
* @return
|
||||
*/
|
||||
public static Approval fromJSONString(final String data) {
|
||||
final JSONObject json = new JSONObject(data);
|
||||
final Approval approver =
|
||||
new Approval(
|
||||
json.getString("owner"),
|
||||
json.getString("operator"),
|
||||
Boolean.valueOf(json.getBoolean("approved")));
|
||||
return approver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs new Approval from JSON String.
|
||||
*
|
||||
* @param json Approval format.
|
||||
* @return
|
||||
*/
|
||||
public static Approval fromBytes(final byte[] bytes) {
|
||||
return new Genson().deserialize(new String(bytes, UTF_8), Approval.class);
|
||||
}
|
||||
|
||||
/** @return */
|
||||
public String getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void setOwner(final String owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
/** @return */
|
||||
public String getOperator() {
|
||||
return operator;
|
||||
}
|
||||
|
||||
/** @param operator */
|
||||
public void setOperator(final String operator) {
|
||||
this.operator = operator;
|
||||
}
|
||||
|
||||
/** @return */
|
||||
public boolean isApproved() {
|
||||
return approved;
|
||||
}
|
||||
|
||||
/** @param approved */
|
||||
public void setApproved(final boolean approved) {
|
||||
this.approved = approved;
|
||||
}
|
||||
|
||||
/** @return JSON String of the Approval object. */
|
||||
public String toJSONString() {
|
||||
return new Genson().serialize(this).toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
package org.hyperledger.fabric.samples.erc721.models;
|
||||
|
||||
import com.owlike.genson.Genson;
|
||||
import com.owlike.genson.annotation.JsonProperty;
|
||||
import org.hyperledger.fabric.contract.annotation.DataType;
|
||||
import org.hyperledger.fabric.contract.annotation.Property;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@DataType()
|
||||
public final class NFT implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -29439695319757532L;
|
||||
|
||||
@Property()
|
||||
@JsonProperty("tokenId")
|
||||
private String tokenId;
|
||||
|
||||
@Property()
|
||||
@JsonProperty("owner")
|
||||
private String owner;
|
||||
|
||||
@Property()
|
||||
@JsonProperty("tokenURI")
|
||||
private String tokenURI;
|
||||
|
||||
@Property()
|
||||
@JsonProperty("approved")
|
||||
private String approved;
|
||||
|
||||
/** Default constructor */
|
||||
public NFT() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor of the class
|
||||
*
|
||||
* @param tokenId
|
||||
* @param owner
|
||||
* @param tokenURI
|
||||
* @param approved
|
||||
*/
|
||||
public NFT(
|
||||
@JsonProperty("tokenId") final String tokenId,
|
||||
@JsonProperty("owner") final String owner,
|
||||
@JsonProperty("tokenURI") final String tokenURI,
|
||||
@JsonProperty("approved") final String approved) {
|
||||
super();
|
||||
this.tokenId = tokenId;
|
||||
this.owner = owner;
|
||||
this.tokenURI = tokenURI;
|
||||
this.approved = approved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert JSON string to NFT object.
|
||||
*
|
||||
* @param data JSON string.
|
||||
* @return NFT object
|
||||
*/
|
||||
public static NFT fromJSONString(final String data) {
|
||||
final JSONObject json = new JSONObject(data);
|
||||
final NFT nft =
|
||||
new NFT(
|
||||
json.getString("tokenId"),
|
||||
json.getString("owner"),
|
||||
json.getString("tokenURI"),
|
||||
json.getString("approved"));
|
||||
|
||||
return nft;
|
||||
}
|
||||
|
||||
/** @return */
|
||||
public String getTokenId() {
|
||||
return tokenId;
|
||||
}
|
||||
|
||||
/** @param tokenId */
|
||||
public void setTokenId(final String tokenId) {
|
||||
this.tokenId = tokenId;
|
||||
}
|
||||
|
||||
/** @return */
|
||||
public String getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
/** @param owner */
|
||||
public void setOwner(final String owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
/** @return */
|
||||
public String getTokenURI() {
|
||||
return tokenURI;
|
||||
}
|
||||
|
||||
/** @param tokenURI */
|
||||
public void setTokenURI(final String tokenURI) {
|
||||
this.tokenURI = tokenURI;
|
||||
}
|
||||
|
||||
/** @return */
|
||||
public String getApproved() {
|
||||
return approved;
|
||||
}
|
||||
|
||||
/** @param approved */
|
||||
public void setApproved(final String approved) {
|
||||
this.approved = approved;
|
||||
}
|
||||
|
||||
/** @return String JSON */
|
||||
public String toJSONString() {
|
||||
return new Genson().serialize(this).toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
package org.hyperledger.fabric.samples.erc721.models;
|
||||
|
||||
import com.owlike.genson.Genson;
|
||||
import com.owlike.genson.annotation.JsonProperty;
|
||||
import org.hyperledger.fabric.contract.annotation.DataType;
|
||||
import org.hyperledger.fabric.contract.annotation.Property;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
@DataType()
|
||||
public final class Transfer {
|
||||
|
||||
@Property()
|
||||
@JsonProperty("from")
|
||||
private String from;
|
||||
|
||||
@Property()
|
||||
@JsonProperty("to")
|
||||
private String to;
|
||||
|
||||
@Property()
|
||||
@JsonProperty("tokenId")
|
||||
private String tokenId;
|
||||
|
||||
/**
|
||||
* Constructor of the class
|
||||
*
|
||||
* @param owner
|
||||
* @param operator
|
||||
* @param approved
|
||||
*/
|
||||
public Transfer(
|
||||
@JsonProperty("from") final String from,
|
||||
@JsonProperty("to") final String to,
|
||||
@JsonProperty("tokenId") final String tokenId) {
|
||||
super();
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
this.tokenId = tokenId;
|
||||
}
|
||||
|
||||
/** Default Constructor of the class. */
|
||||
public Transfer() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs new Approval from JSON String.
|
||||
*
|
||||
* @param json Approval format.
|
||||
* @return
|
||||
*/
|
||||
public static Transfer fromBytes(final byte[] bytes) {
|
||||
return new Genson().deserialize(new String(bytes, UTF_8), Transfer.class);
|
||||
}
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
|
||||
public void setFrom(final String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
/** @param to */
|
||||
public void setTo(final String to) {
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
/** @return */
|
||||
public String getTokenId() {
|
||||
return tokenId;
|
||||
}
|
||||
|
||||
/** @param tokenId */
|
||||
public void setTokenId(final String tokenId) {
|
||||
this.tokenId = tokenId;
|
||||
}
|
||||
|
||||
/** @return String JSON */
|
||||
public String toJSONString() {
|
||||
return new Genson().serialize(this).toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
package org.hyperledger.fabric.samples.erc721.utils;
|
||||
|
||||
public final class ContractUtility {
|
||||
|
||||
private ContractUtility() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string
|
||||
* @return
|
||||
*/
|
||||
public static boolean stringIsNullOrEmpty(final String string) {
|
||||
return string == null || string.isEmpty();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,494 @@
|
|||
package org.hyperledger.fabric.samples.erc721;
|
||||
|
||||
import org.hyperledger.fabric.contract.ClientIdentity;
|
||||
import org.hyperledger.fabric.contract.Context;
|
||||
import org.hyperledger.fabric.samples.erc721.models.Approval;
|
||||
import org.hyperledger.fabric.samples.erc721.models.NFT;
|
||||
import org.hyperledger.fabric.shim.ChaincodeException;
|
||||
import org.hyperledger.fabric.shim.ChaincodeStub;
|
||||
import org.hyperledger.fabric.shim.ledger.CompositeKey;
|
||||
import org.hyperledger.fabric.shim.ledger.KeyValue;
|
||||
import org.hyperledger.fabric.shim.ledger.QueryResultsIterator;
|
||||
import org.json.JSONException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ERC721TokenContractTest {
|
||||
|
||||
private final class MockKeyValue implements KeyValue {
|
||||
|
||||
private final String key;
|
||||
private final String value;
|
||||
|
||||
MockKeyValue(final String key, final String value) {
|
||||
super();
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getKey() {
|
||||
return this.key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getStringValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getValue() {
|
||||
return this.value.getBytes();
|
||||
}
|
||||
}
|
||||
|
||||
private final class MockAssetResultsIterator implements QueryResultsIterator<KeyValue> {
|
||||
|
||||
private final List<KeyValue> assetList;
|
||||
|
||||
MockAssetResultsIterator(final List<KeyValue> list) {
|
||||
super();
|
||||
this.assetList = list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<KeyValue> iterator() {
|
||||
return assetList.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class InvokeERC721TokenBalanceOf {
|
||||
|
||||
@Test
|
||||
public void invokeToGetTokenBalance() {
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
List<KeyValue> list = new ArrayList<>();
|
||||
list.add(new MockKeyValue("balance_Alice_101", "\u0000"));
|
||||
list.add(new MockKeyValue("balance_Alice_101", "\u0000"));
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
CompositeKey balanceKey =
|
||||
stub.createCompositeKey(ContractConstants.BALANCE.getValue(), "Alice");
|
||||
when(stub.getStateByPartialCompositeKey(balanceKey))
|
||||
.thenReturn(new MockAssetResultsIterator(list));
|
||||
long balance = contract.BalanceOf(ctx, "Alice");
|
||||
assertThat(balance).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokeToGetOwnerOf() {
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
NFT nft = new NFT("101", "Alicd", "http://test.com", "");
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(nft.toJSONString());
|
||||
String owner = contract.OwnerOf(ctx, "101");
|
||||
assertThat(owner).isEqualTo(nft.getOwner());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ERC721TransferFromFunctionTest {
|
||||
|
||||
private Context ctx = null;
|
||||
private ChaincodeStub stub = null;
|
||||
private ERC721TokenContract contract = null;
|
||||
private NFT currentNFT = null;
|
||||
private NFT updatedNFT = null;
|
||||
|
||||
@BeforeEach
|
||||
public void initialize() {
|
||||
|
||||
this.currentNFT = new NFT("101", "Alice", "http://test.com", "Charlie");
|
||||
this.updatedNFT = new NFT("101", "Bob", "http://test.com", "");
|
||||
this.ctx = mock(Context.class);
|
||||
this.stub = mock(ChaincodeStub.class);
|
||||
when(this.ctx.getStub()).thenReturn(stub);
|
||||
contract = new ERC721TokenContract();
|
||||
CompositeKey ck1 = mock(CompositeKey.class);
|
||||
when(ck1.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(this.stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck1);
|
||||
when(stub.getStringState(ck1.toString())).thenReturn(currentNFT.toJSONString());
|
||||
CompositeKey ck2 = mock(CompositeKey.class);
|
||||
when(ck2.toString()).thenReturn(ContractConstants.BALANCE.getValue() + "Alice" + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.BALANCE.getValue(), "Alice", "101"))
|
||||
.thenReturn(ck2);
|
||||
|
||||
CompositeKey ck3 = mock(CompositeKey.class);
|
||||
when(ck3.toString()).thenReturn(ContractConstants.BALANCE.getValue() + "Bob" + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.BALANCE.getValue(), "Bob", "101"))
|
||||
.thenReturn(ck3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSenderIsCurrentTokenOwner()
|
||||
throws CertificateException, JSONException, IOException {
|
||||
Approval approval = new Approval("Alice", "Alice", false);
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.APPROVAL.getValue() + "Alice" + "Alice");
|
||||
when(this.stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), "Alice", "Alice"))
|
||||
.thenReturn(ck);
|
||||
when(this.stub.getStringState(ck.toString())).thenReturn(approval.toJSONString());
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
when(this.ctx.getClientIdentity()).thenReturn(ci);
|
||||
contract.TransferFrom(this.ctx, "Alice", "Bob", "101");
|
||||
verify(stub)
|
||||
.putStringState(ContractConstants.NFT.getValue() + "101", this.updatedNFT.toJSONString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSenderisApprovedClientOfToken()
|
||||
throws CertificateException, JSONException, IOException {
|
||||
Approval approval = new Approval("Alice", "Charlie", false);
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.APPROVAL.getValue() + "Alice" + "Charlie");
|
||||
when(this.stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), "Alice", "Charlie"))
|
||||
.thenReturn(ck);
|
||||
when(this.stub.getStringState(ck.toString())).thenReturn(approval.toJSONString());
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ci.getId()).thenReturn("Charlie");
|
||||
when(this.ctx.getClientIdentity()).thenReturn(ci);
|
||||
contract.TransferFrom(this.ctx, "Alice", "Bob", "101");
|
||||
verify(stub)
|
||||
.putStringState(ContractConstants.NFT.getValue() + "101", this.updatedNFT.toJSONString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSenderisAuthorizedOperatorOfToken()
|
||||
throws CertificateException, JSONException, IOException {
|
||||
Approval approval = new Approval("Alice", "Dave", true);
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.APPROVAL.getValue() + "Alice" + "Dave");
|
||||
when(this.stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), "Alice", "Dave"))
|
||||
.thenReturn(ck);
|
||||
when(this.stub.getStringState(ck.toString())).thenReturn(approval.toJSONString());
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ci.getId()).thenReturn("Dave");
|
||||
when(this.ctx.getClientIdentity()).thenReturn(ci);
|
||||
contract.TransferFrom(this.ctx, "Alice", "Bob", "101");
|
||||
verify(stub)
|
||||
.putStringState(ContractConstants.NFT.getValue() + "101", this.updatedNFT.toJSONString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSenderIsInvalid() throws CertificateException, JSONException, IOException {
|
||||
Approval approval = new Approval("Alice", "Alice", false);
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.APPROVAL.getValue() + "Alice" + "Dev");
|
||||
when(this.stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), "Alice", "Dev"))
|
||||
.thenReturn(ck);
|
||||
when(this.stub.getStringState(ck.toString())).thenReturn(approval.toJSONString());
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ci.getId()).thenReturn("Dev");
|
||||
when(this.ctx.getClientIdentity()).thenReturn(ci);
|
||||
Throwable thrown =
|
||||
catchThrowable(
|
||||
() -> {
|
||||
contract.TransferFrom(this.ctx, "Alice", "Bob", "101");
|
||||
});
|
||||
String message =
|
||||
String.format(
|
||||
"The sender %s is not the current owner nor an authorized operator of the token %s.",
|
||||
"Dev", "101");
|
||||
assertThat(thrown).isInstanceOf(ChaincodeException.class).hasMessage(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCurrentOwnerDoesNotMatch()
|
||||
throws CertificateException, JSONException, IOException {
|
||||
Approval approval = new Approval("Alice", "Alice", false);
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.APPROVAL.getValue() + "Alice" + "Alice");
|
||||
when(this.stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), "Alice", "Alice"))
|
||||
.thenReturn(ck);
|
||||
when(this.stub.getStringState(ck.toString())).thenReturn(approval.toJSONString());
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
when(this.ctx.getClientIdentity()).thenReturn(ci);
|
||||
Throwable thrown =
|
||||
catchThrowable(
|
||||
() -> {
|
||||
contract.TransferFrom(this.ctx, "Charlie", "Bob", "101");
|
||||
});
|
||||
System.out.println(thrown);
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(ChaincodeException.class)
|
||||
.hasMessage("The from Charlie is not the current owner of the token 101.");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ERC721ApproveFunctionalitiesTest {
|
||||
|
||||
@Test
|
||||
public void invokeAprrove() throws CertificateException, JSONException, IOException {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
NFT nft = new NFT("101", "Alice", "http://test.com", "");
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(nft.toJSONString());
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
when(ctx.getClientIdentity()).thenReturn(ci);
|
||||
CompositeKey ck1 = mock(CompositeKey.class);
|
||||
when(ck1.toString()).thenReturn(ContractConstants.APPROVAL.getValue() + "Alice" + "Alice");
|
||||
when(stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), "Alice", "Alice"))
|
||||
.thenReturn(ck1);
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
contract.Approve(ctx, "Bob", "101");
|
||||
verify(stub)
|
||||
.putStringState(
|
||||
ContractConstants.NFT.getValue() + "101",
|
||||
new NFT("101", "Alice", "http://test.com", "Bob").toJSONString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokeSetApproveForAll() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ctx.getClientIdentity()).thenReturn(ci);
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
CompositeKey ck1 = mock(CompositeKey.class);
|
||||
when(stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), "Alice", "Bob"))
|
||||
.thenReturn(ck1);
|
||||
when(ck1.toString()).thenReturn(ContractConstants.APPROVAL.getValue() + "Alice" + "Bob");
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
NFT nft = new NFT("101", "Alice", "http://test.com", "");
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(nft.toJSONString());
|
||||
contract.SetApprovalForAll(ctx, "Bob", true);
|
||||
|
||||
verify(stub)
|
||||
.putStringState(ck1.toString(), new Approval("Alice", "Bob", true).toJSONString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokeGetApproved() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ctx.getClientIdentity()).thenReturn(ci);
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
NFT nft = new NFT("101", "Alice", "http://test.com", "Bob");
|
||||
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(nft.toJSONString());
|
||||
String approved = contract.GetApproved(ctx, "101");
|
||||
assertThat(approved).isEqualTo("Bob");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokeIsApprovedForAll() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ctx.getClientIdentity()).thenReturn(ci);
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
Approval approval = new Approval("Alice", "Bob", true);
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.APPROVAL.getValue() + "Alice" + "Bob");
|
||||
when(stub.createCompositeKey(ContractConstants.APPROVAL.getValue(), "Alice", "Bob"))
|
||||
.thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(approval.toJSONString());
|
||||
boolean response = contract.IsApprovedForAll(ctx, "Alice", "Bob");
|
||||
assertThat(response).isEqualTo(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ERC721OptionsTest {
|
||||
|
||||
@Test
|
||||
public void invokeGetName() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
when(stub.getStringState(ContractConstants.NAMEKEY.getValue())).thenReturn("AmadoueNFT");
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
String name = contract.Name(ctx);
|
||||
assertThat(name).isEqualTo("AmadoueNFT");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokeGetSysmbol() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
when(stub.getStringState(ContractConstants.NAMEKEY.getValue())).thenReturn("ANFT");
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
final String name = contract.Name(ctx);
|
||||
assertThat(name).isEqualTo("ANFT");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokeTokenURI() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
final NFT nft = new NFT("101", "Alice", "http://test.com", "Bob");
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(nft.toJSONString());
|
||||
String response = contract.TokenURI(ctx, "101");
|
||||
assertThat(response).isEqualTo("http://test.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTokenTotalSupply() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
List<KeyValue> list = new ArrayList<>();
|
||||
list.add(
|
||||
new MockKeyValue(
|
||||
"101", new NFT("101", "Alice", "http://test.com", "Bob").toJSONString()));
|
||||
list.add(
|
||||
new MockKeyValue(
|
||||
"balance_Alice_101",
|
||||
new NFT("102", "Alice", "http://test.com", "Bob").toJSONString()));
|
||||
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue());
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue())).thenReturn(ck);
|
||||
|
||||
when(stub.getStateByPartialCompositeKey(ck)).thenReturn(new MockAssetResultsIterator(list));
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
|
||||
final long total = contract.TotalSupply(ctx);
|
||||
assertThat(total).isEqualTo(2L);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ERC721MintFunctionTest {
|
||||
|
||||
@Test
|
||||
public void whenInvokeMintForNewToken() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
final NFT nft = new NFT("101", "Alice", "DummyURI", "");
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(null);
|
||||
|
||||
CompositeKey ck2 = mock(CompositeKey.class);
|
||||
when(ck2.toString()).thenReturn(ContractConstants.BALANCE.getValue() + "Alice" + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.BALANCE.getValue(), "Alice", "101"))
|
||||
.thenReturn(ck2);
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ctx.getClientIdentity()).thenReturn(ci);
|
||||
when(ci.getMSPID()).thenReturn("Org1MSP");
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
final NFT response = contract.MintWithTokenURI(ctx, "101", "DummyURI");
|
||||
|
||||
verify(stub).putStringState(ck.toString(), nft.toJSONString());
|
||||
verify(stub).putStringState(ck2.toString(), "\u0000");
|
||||
assertThat(response.toJSONString()).isEqualTo(nft.toJSONString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvokeMintForAlreadyExistingToken() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
final NFT nft = new NFT("101", "Alice", "DummyURI", "");
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(nft.toJSONString());
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ctx.getClientIdentity()).thenReturn(ci);
|
||||
when(ci.getMSPID()).thenReturn("Org1MSP");
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
Throwable thrown =
|
||||
catchThrowable(
|
||||
() -> {
|
||||
contract.MintWithTokenURI(ctx, "101", "DummyURI");
|
||||
});
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(ChaincodeException.class)
|
||||
.hasMessage("The token 101 is already minted.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvokeBurnToken() {
|
||||
Context ctx = mock(Context.class);
|
||||
ChaincodeStub stub = mock(ChaincodeStub.class);
|
||||
when(ctx.getStub()).thenReturn(stub);
|
||||
final NFT nft = new NFT("101", "Alice", "DummyURI", "");
|
||||
CompositeKey ck = mock(CompositeKey.class);
|
||||
when(ck.toString()).thenReturn(ContractConstants.NFT.getValue() + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.NFT.getValue(), "101")).thenReturn(ck);
|
||||
when(stub.getStringState(ck.toString())).thenReturn(nft.toJSONString());
|
||||
CompositeKey ck2 = mock(CompositeKey.class);
|
||||
when(ck2.toString()).thenReturn(ContractConstants.BALANCE.getValue() + "Alice" + "101");
|
||||
when(stub.createCompositeKey(ContractConstants.BALANCE.getValue(), "Alice", "101"))
|
||||
.thenReturn(ck2);
|
||||
ClientIdentity ci = null;
|
||||
ci = mock(ClientIdentity.class);
|
||||
when(ctx.getClientIdentity()).thenReturn(ci);
|
||||
when(ci.getMSPID()).thenReturn("Org1MSP");
|
||||
when(ci.getId()).thenReturn("Alice");
|
||||
ERC721TokenContract contract = new ERC721TokenContract();
|
||||
contract.Burn(ctx, "101");
|
||||
verify(stub).delState(ck.toString());
|
||||
verify(stub).delState(ck2.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
mock-maker-inline
|
||||
Loading…
Reference in a new issue