orgEnv = FabricState.getState().orgEnv(org);
26 | PeerBuilder coreBuilder = Peer.newBuilder().ccname(ccname).channel(channel);
27 |
28 | Result r = coreBuilder.argsTx(args).build(orgEnv).run();
29 | System.out.println(r.stdout);
30 | String text = r.stdout.stream()
31 | .filter(line -> line.matches(".*chaincodeInvokeOrQuery.*"))
32 | .collect(Collectors.joining(System.lineSeparator()))
33 | .trim();
34 |
35 | if (!text.contains("result: status:200")) {
36 | Command logsCommand = new Command(Arrays.asList("docker", "logs", "microfab"), orgEnv);
37 | logsCommand.run();
38 | throw new RuntimeException(text);
39 | }
40 |
41 | int payloadIndex = text.indexOf("payload:");
42 | if (payloadIndex > 1) {
43 | return text.substring(payloadIndex + 9, text.length() - 1);
44 | }
45 | return "success";
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/fabric-chaincode-integration-test/src/test/resources/docker-compose-microfab.yaml:
--------------------------------------------------------------------------------
1 | # Copyright IBM Corp. All Rights Reserved.
2 | #
3 | # SPDX-License-Identifier: Apache-2.0
4 | #
5 |
6 | version: '2'
7 |
8 | services:
9 |
10 | microfab:
11 | container_name: microfab
12 | image: ghcr.io/hyperledger-labs/microfab
13 | tty: true
14 | environment:
15 | - MICROFAB_CONFIG={"couchdb":false,"endorsing_organizations":[{"name":"org1"},{"name":"org2"}],"channels":[{"name":"sachannel","endorsing_organizations":["org1","org2"]}],"capability_level":"V2_5"}
16 | - FABRIC_LOGGING_SPEC=info
17 | ports:
18 | - 8080:8080
19 |
--------------------------------------------------------------------------------
/fabric-chaincode-integration-test/src/test/resources/scripts/collection_config.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "col",
4 | "policy": "OR( OR('org1MSP.member','org1MSP.admin') , OR('org2MSP.member','org2MSP.admin') )",
5 | "blockToLive": 100000,
6 | "maxPeerCount": 1,
7 | "requiredPeerCount": 1
8 | }
9 | ]
10 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/javabuild.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #
4 | #Copyright DTCC 2016 All Rights Reserved.
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 | # http://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 | set -e
20 | PARENTDIR=$(pwd)
21 | ARCH=`uname -m`
22 |
23 | pattern='(https?://)?((([^:\/]+)(:([^\/]*))?@)?([^:\/?]+)(:([0-9]+))?)'
24 |
25 | [ -n "$http_proxy" ] && HTTPPROXY=$http_proxy
26 | [ -n "$HTTP_PROXY" ] && HTTPPROXY=$HTTP_PROXY
27 | [ -n "$https_proxy" ] && HTTPSPROXY=$https_proxy
28 | [ -n "$HTTPS_PROXY" ] && HTTPSPROXY=$HTTPS_PROXY
29 |
30 | if [ -n "$HTTPPROXY" ]; then
31 | if [[ "$HTTPPROXY" =~ $pattern ]]; then
32 | [ -n "${BASH_REMATCH[4]}" ] && JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyUser=${BASH_REMATCH[4]}"
33 | [ -n "${BASH_REMATCH[6]}" ] && JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyPassword=${BASH_REMATCH[6]}"
34 | [ -n "${BASH_REMATCH[7]}" ] && JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyHost=${BASH_REMATCH[7]}"
35 | [ -n "${BASH_REMATCH[9]}" ] && JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyPort=${BASH_REMATCH[9]}"
36 | fi
37 | fi
38 | if [ -n "$HTTPSPROXY" ]; then
39 | if [[ "$HTTPSPROXY" =~ $pattern ]]; then
40 | [ -n "${BASH_REMATCH[4]}" ] && JAVA_OPTS="$JAVA_OPTS -Dhttps.proxyUser=${BASH_REMATCH[4]}"
41 | [ -n "${BASH_REMATCH[6]}" ] && JAVA_OPTS="$JAVA_OPTS -Dhttps.proxyPassword=${BASH_REMATCH[6]}"
42 | [ -n "${BASH_REMATCH[7]}" ] && JAVA_OPTS="$JAVA_OPTS -Dhttps.proxyHost=${BASH_REMATCH[7]}"
43 | [ -n "${BASH_REMATCH[9]}" ] && JAVA_OPTS="$JAVA_OPTS -Dhttps.proxyPort=${BASH_REMATCH[9]}"
44 | fi
45 | fi
46 |
47 | export JAVA_OPTS
48 |
49 | if [ x$ARCH == xx86_64 ]
50 | then
51 | gradle -q -b ${PARENTDIR}/core/chaincode/shim/java/build.gradle clean
52 | gradle -q -b ${PARENTDIR}/core/chaincode/shim/java/build.gradle build
53 | cp -r ${PARENTDIR}/core/chaincode/shim/java/build/libs /root/
54 | else
55 | echo "FIXME: Java Shim code needs work on ppc64le and s390x."
56 | echo "Commenting it for now."
57 | fi
58 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/Context.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM DTCC All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract;
8 |
9 | import java.io.IOException;
10 | import java.security.cert.CertificateException;
11 | import org.hyperledger.fabric.shim.ChaincodeStub;
12 | import org.json.JSONException;
13 |
14 | /**
15 | * This context is available to all 'transaction functions' and provides the transaction context. It also provides
16 | * access to the APIs for the world state using {@link #getStub()}
17 | *
18 | * Applications can implement their own versions if they wish to add functionality. All subclasses MUST implement a
19 | * constructor, for example
20 | *
21 | *
{@code
22 | * public MyContext extends Context {
23 | *
24 | * public MyContext(ChaincodeStub stub) {
25 | * super(stub);
26 | * }
27 | * }
28 | *
29 | * }
30 | */
31 | public class Context {
32 | /** */
33 | protected ChaincodeStub stub;
34 |
35 | /** */
36 | protected ClientIdentity clientIdentity;
37 |
38 | /**
39 | * Creates new client identity and sets it as a property of the stub.
40 | *
41 | * @param stub Instance of the {@link ChaincodeStub} to use
42 | */
43 | public Context(final ChaincodeStub stub) {
44 | this.stub = stub;
45 | try {
46 | this.clientIdentity = new ClientIdentity(stub);
47 | } catch (CertificateException | JSONException | IOException e) {
48 | throw new ContractRuntimeException("Could not create new client identity", e);
49 | }
50 | }
51 |
52 | /** @return ChaincodeStub instance to use */
53 | public ChaincodeStub getStub() {
54 | return this.stub;
55 | }
56 |
57 | /** @return ClientIdentity object to use */
58 | public ClientIdentity getClientIdentity() {
59 | return this.clientIdentity;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContextFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract;
8 |
9 | import org.hyperledger.fabric.shim.ChaincodeStub;
10 |
11 | /** Factory to create {@link Context} from {@link ChaincodeStub} by wrapping stub with dynamic proxy. */
12 | public final class ContextFactory {
13 | private static final ContextFactory INSTANCE = new ContextFactory();
14 |
15 | /** @return ContextFactory */
16 | public static ContextFactory getInstance() {
17 | return INSTANCE;
18 | }
19 |
20 | /**
21 | * @param stub
22 | * @return Context
23 | */
24 | public Context createContext(final ChaincodeStub stub) {
25 | return new Context(stub);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRuntimeException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract;
7 |
8 | import org.hyperledger.fabric.shim.ChaincodeException;
9 |
10 | /**
11 | * Specific RuntimeException for events that occur in the calling and handling of the Contracts, NOT within the contract
12 | * logic itself.
13 | *
14 | * FUTURE At some future point we wish to add more diagnostic information into this, for example current tx id
15 | */
16 | public class ContractRuntimeException extends ChaincodeException {
17 | /** Generated serial version id. */
18 | private static final long serialVersionUID = -884373036398750450L;
19 |
20 | /** @param string */
21 | public ContractRuntimeException(final String string) {
22 | super(string);
23 | }
24 |
25 | /**
26 | * @param string
27 | * @param cause
28 | */
29 | public ContractRuntimeException(final String string, final Throwable cause) {
30 | super(string, cause);
31 | }
32 |
33 | /** @param cause */
34 | public ContractRuntimeException(final Throwable cause) {
35 | super(cause);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contact.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.annotation;
7 |
8 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
9 |
10 | import java.lang.annotation.ElementType;
11 | import java.lang.annotation.Retention;
12 | import java.lang.annotation.Target;
13 |
14 | /**
15 | * Class level annotation that identifies this class as being a contact. Can be populated with email, name and url
16 | * fields.
17 | */
18 | @Retention(RUNTIME)
19 | @Target(ElementType.TYPE)
20 | public @interface Contact {
21 |
22 | /** @return String */
23 | String email() default "";
24 |
25 | /** @return String */
26 | String name() default "";
27 |
28 | /** @return String */
29 | String url() default "";
30 | }
31 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contract.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.annotation;
7 |
8 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
9 |
10 | import java.lang.annotation.ElementType;
11 | import java.lang.annotation.Retention;
12 | import java.lang.annotation.Target;
13 |
14 | /**
15 | * Class level annotation that identifies this class as being a contract. Can supply information and an alternative name
16 | * for the contract rather than the classname
17 | */
18 | @Retention(RUNTIME)
19 | @Target(ElementType.TYPE)
20 | public @interface Contract {
21 |
22 | /**
23 | * The Info object can be supplied to provide additional information about the contract.
24 | *
25 | *
Including title, description, version and license
26 | *
27 | * @return Info object
28 | */
29 | Info info() default @Info();
30 |
31 | /**
32 | * Contract name.
33 | *
34 | *
Normally the name of the class is used to refer to the contract (name without package). This can be altered if
35 | * wished.
36 | *
37 | * @return Name of the contract to be used instead of the Classname
38 | */
39 | String name() default "";
40 |
41 | /**
42 | * Transaction Serializer Classname.
43 | *
44 | *
Fully Qualified Classname of the TRANSACTION serializer that should be used with this contract.
45 | *
46 | *
This is the serializer that is used to parse incoming transaction request parameters and convert the return
47 | * type
48 | *
49 | * @return Default serializer classname
50 | */
51 | String transactionSerializer() default "org.hyperledger.fabric.contract.execution.JSONTransactionSerializer";
52 | }
53 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/DataType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.annotation;
7 |
8 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
9 |
10 | import java.lang.annotation.ElementType;
11 | import java.lang.annotation.Retention;
12 | import java.lang.annotation.Target;
13 |
14 | /**
15 | * Class level annotation indicating this class represents one of the complex types that can be returned or passed to
16 | * the transaction functions.
17 | *
18 | *
These datatypes are used (within the current implementation) for determining the data flow protocol from the
19 | * Contracts to the SDK and for permitting a fully formed Interface Definition to be created for the contract.
20 | *
21 | *
Complex types can appear within this definition, and these are identified using this annotation.
22 | *
23 | *
FUTURE To take these annotations are also utilize them for leverage storage
24 | */
25 | @Retention(RUNTIME)
26 | @Target(ElementType.TYPE)
27 | public @interface DataType {
28 | /**
29 | * Namespace of the type.
30 | *
31 | * @return String
32 | */
33 | String namespace() default "";
34 | }
35 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Default.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.annotation;
7 |
8 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
9 |
10 | import java.lang.annotation.ElementType;
11 | import java.lang.annotation.Retention;
12 | import java.lang.annotation.Target;
13 |
14 | /**
15 | * Default Contract.
16 | *
17 | *
Class level annotation that defines the contract that is the default contract, and as such invoke of the
18 | * transaction functions does not need to be qualified by the contract name
19 | */
20 | @Retention(RUNTIME)
21 | @Target(ElementType.TYPE)
22 | public @interface Default {}
23 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract.annotation;
8 |
9 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
10 |
11 | import java.lang.annotation.ElementType;
12 | import java.lang.annotation.Retention;
13 | import java.lang.annotation.Target;
14 |
15 | /**
16 | * Info Details
17 | *
18 | *
Class level annotation that identifies this class as being an info object. Can supply additional information about
19 | * the contract, including title, description, version, license and contact information.
20 | */
21 | @Retention(RUNTIME)
22 | @Target(ElementType.TYPE)
23 | public @interface Info {
24 |
25 | /** @return String */
26 | String title() default "";
27 |
28 | /** @return String */
29 | String description() default "";
30 |
31 | /** @return String */
32 | String version() default "";
33 |
34 | /** @return String */
35 | String termsOfService() default "";
36 |
37 | /**
38 | * License object that can be populated to include name and url.
39 | *
40 | * @return License object
41 | */
42 | License license() default @License();
43 |
44 | /**
45 | * Contact object that can be populated with email, name and url fields.
46 | *
47 | * @return Contact object
48 | */
49 | Contact contact() default @Contact();
50 | }
51 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/License.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.annotation;
7 |
8 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
9 |
10 | import java.lang.annotation.ElementType;
11 | import java.lang.annotation.Retention;
12 | import java.lang.annotation.Target;
13 |
14 | /**
15 | * Class level annotation that identifies this class as being a license object. Can be populated to include name and
16 | * url.
17 | */
18 | @Retention(RUNTIME)
19 | @Target(ElementType.TYPE)
20 | public @interface License {
21 |
22 | /** @return String */
23 | String name() default "";
24 |
25 | /** @return String */
26 | String url() default "";
27 | }
28 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Property.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.annotation;
7 |
8 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
9 |
10 | import java.lang.annotation.ElementType;
11 | import java.lang.annotation.Retention;
12 | import java.lang.annotation.Target;
13 |
14 | /**
15 | * Field and parameter level annotation defining a property of the class.
16 | *
17 | *
(identified by {@link DataType}) Can also be used on the parameters of transaction functions
18 | *
19 | *
Example of using this annotation
20 | *
21 | *
22 | *
23 | * // max 15 character string, a-z with spaces
24 | * @Property(schema = {"pattern", "^[a-zA-Z\\s]{0,15}$"})
25 | * private String text;
26 | *
27 | * // How friendly is this on a scale of 1-5, 1 being formal, 5 being familiar
28 | * @Property(schema = {"minimum", "1", "maximum", "5"})
29 | * private int friendliness = 1;
30 | *
31 | *
32 | */
33 | @Retention(RUNTIME)
34 | @Target({ElementType.FIELD, ElementType.PARAMETER})
35 | public @interface Property {
36 |
37 | /**
38 | * Allows each property to be defined a detail set of rules to determine the valid types of this data. The format
39 | * follows the syntax of the OpenAPI Schema object.
40 | *
41 | * @return String array of the key-value pairs of the schema
42 | */
43 | String[] schema() default {};
44 | }
45 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Serializer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.annotation;
7 |
8 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
9 |
10 | import java.lang.annotation.ElementType;
11 | import java.lang.annotation.Retention;
12 | import java.lang.annotation.Target;
13 |
14 | /**
15 | * Class level annotation that defines the serializer that should be used to convert objects to and from the wire
16 | * format.
17 | *
18 | * This should annotate a class that implements the Serializer interface
19 | */
20 | @Retention(RUNTIME)
21 | @Target({ElementType.TYPE, ElementType.TYPE_USE})
22 | public @interface Serializer {
23 | /** What is this serializer able to target? */
24 | enum TARGET {
25 | /** Target transaction functions. */
26 | TRANSACTION,
27 | /** Target all elements. */
28 | ALL
29 | }
30 |
31 | /** @return Target of the serializer */
32 | TARGET target() default Serializer.TARGET.ALL;
33 | }
34 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Transaction.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.annotation;
7 |
8 | import static java.lang.annotation.ElementType.METHOD;
9 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
10 |
11 | import java.lang.annotation.Retention;
12 | import java.lang.annotation.Target;
13 |
14 | /**
15 | * Method level annotation indicating the method to be a callable transaction function.
16 | *
17 | *
These functions are called in client SDKs by the combination of
18 | *
19 | *
20 | * [contractname]:[transactioname]
21 | *
22 | *
23 | * Unless specified otherwise, the contract name is the class name (without package) and the transaction name is the
24 | * method name.
25 | */
26 | @Retention(RUNTIME)
27 | @Target(METHOD)
28 | public @interface Transaction {
29 |
30 | /** The intended invocation style for a transaction function. */
31 | enum TYPE {
32 | /** Transaction is used to submit updates to the ledger. */
33 | SUBMIT,
34 | /** Transaction is evaluated to query information from the ledger. */
35 | EVALUATE
36 | }
37 |
38 | /**
39 | * Submit semantics.
40 | *
41 | * TRUE indicates that this function is intended to be called with the 'submit' semantics
42 | *
43 | *
FALSE indicates that this is intended to be called with the evaluate semantics
44 | *
45 | * @return boolean, default is true
46 | * @deprecated Please use intent
47 | */
48 | @Deprecated
49 | boolean submit() default true;
50 |
51 | /**
52 | * What are submit semantics for this transaction.
53 | *
54 | *
55 | * - SUBMIT
56 | *
- indicates that this function is intended to be called with the 'submit' semantics
57 | *
- EVALUATE
58 | *
- indicates that this is intended to be called with the 'evaluate' semantics
59 | *
60 | *
61 | * @return submit semantics
62 | */
63 | TYPE intent() default Transaction.TYPE.SUBMIT;
64 |
65 | /**
66 | * The name of the callable transaction if it should be different to the method name.
67 | *
68 | * @return the transaction name
69 | */
70 | String name() default "";
71 | }
72 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /**
8 | * Provides annotations required for Contract implementations.
9 | *
10 | * @see org.hyperledger.fabric.contract.ContractInterface
11 | */
12 | package org.hyperledger.fabric.contract.annotation;
13 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract.execution;
8 |
9 | import org.hyperledger.fabric.contract.execution.impl.ContractExecutionService;
10 | import org.hyperledger.fabric.contract.execution.impl.ContractInvocationRequest;
11 | import org.hyperledger.fabric.contract.routing.impl.SerializerRegistryImpl;
12 | import org.hyperledger.fabric.shim.ChaincodeStub;
13 |
14 | public class ExecutionFactory {
15 | private static final ExecutionFactory INSTANCE = new ExecutionFactory();
16 |
17 | /** @return ExecutionFactory */
18 | public static ExecutionFactory getInstance() {
19 | return INSTANCE;
20 | }
21 |
22 | /**
23 | * @param context Chaincode Context
24 | * @return Invocation request
25 | */
26 | public InvocationRequest createRequest(final ChaincodeStub context) {
27 | return new ContractInvocationRequest(context);
28 | }
29 |
30 | /**
31 | * @param serializers Instance of the serializer
32 | * @return Execution Service
33 | */
34 | public ExecutionService createExecutionService(final SerializerRegistryImpl serializers) {
35 | return new ContractExecutionService(serializers);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM DTCC All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract.execution;
8 |
9 | import org.hyperledger.fabric.contract.routing.TxFunction;
10 | import org.hyperledger.fabric.shim.Chaincode;
11 | import org.hyperledger.fabric.shim.ChaincodeStub;
12 |
13 | /**
14 | * ExecutionService.
15 | *
16 | * Service that executes {@link InvocationRequest} (wrapped Init/Invoke + extra data) using routing information
17 | */
18 | @FunctionalInterface
19 | public interface ExecutionService {
20 |
21 | /**
22 | * @param txFn
23 | * @param req
24 | * @param stub
25 | * @return Chaincode response
26 | */
27 | Chaincode.Response executeRequest(TxFunction txFn, InvocationRequest req, ChaincodeStub stub);
28 | }
29 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/InvocationRequest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM DTCC All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract.execution;
8 |
9 | import java.util.List;
10 |
11 | /**
12 | * Invocation Request.
13 | *
14 | *
All information needed to find {@link org.hyperledger.fabric.contract.annotation.Contract} and invoke the request.
15 | */
16 | public interface InvocationRequest {
17 | /** */
18 | String DEFAULT_NAMESPACE = "default";
19 |
20 | /** @return Namespace */
21 | String getNamespace();
22 |
23 | /** @return Method */
24 | String getMethod();
25 |
26 | /** @return Args as byte array */
27 | List getArgs();
28 |
29 | /** @return Request */
30 | String getRequestName();
31 | }
32 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/SerializerInterface.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract.execution;
8 |
9 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
10 |
11 | /**
12 | * This interface allows contract developers to change the serialization mechanism. There are two scenarios where
13 | * instances of DataTypes are serialized.
14 | *
15 | * When the objects are (logically) transferred from the Client application to the Contract resulting in a
16 | * transaction function being invoked. Typically this is JSON, hence a default JSON parser is provided.
17 | *
18 | *
The JSONTransactionSerializer can be extended if needed
19 | */
20 | public interface SerializerInterface {
21 |
22 | /**
23 | * Convert the value supplied to a byte array, according to the TypeSchema.
24 | *
25 | * @param value
26 | * @param ts
27 | * @return buffer
28 | */
29 | byte[] toBuffer(Object value, TypeSchema ts);
30 |
31 | /**
32 | * Take the byte buffer and return the object as required.
33 | *
34 | * @param buffer Byte buffer from the wire
35 | * @param ts TypeSchema representing the type
36 | * @return Object created; relies on Java auto-boxing for primitives
37 | */
38 | Object fromBuffer(byte[] buffer, TypeSchema ts);
39 | }
40 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** */
8 | package org.hyperledger.fabric.contract.execution.impl;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** */
8 | package org.hyperledger.fabric.contract.execution;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** */
8 | package org.hyperledger.fabric.contract.metadata;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /**
8 | * Provides interfaces and classes to support the contract programming model.
9 | *
10 | *
The {@link org.hyperledger.fabric.contract} package implements the Fabric programming model as described in the Developing
12 | * Applications chapter of the Fabric documentation.
13 | *
14 | *
The main interface to implement is {@link org.hyperledger.fabric.contract.ContractInterface}
15 | */
16 | package org.hyperledger.fabric.contract;
17 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/DataTypeDefinition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import java.util.Map;
9 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
10 |
11 | public interface DataTypeDefinition {
12 |
13 | /** @return String */
14 | String getName();
15 |
16 | /** @return Map of String to PropertyDefinitions */
17 | Map getProperties();
18 |
19 | /** @return String */
20 | String getSimpleName();
21 |
22 | /** @return Class object of the type */
23 | Class> getTypeClass();
24 |
25 | /** @return TypeSchema */
26 | TypeSchema getSchema();
27 | }
28 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ParameterDefinition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import java.lang.reflect.Parameter;
9 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
10 |
11 | public interface ParameterDefinition {
12 |
13 | /** @return Class type of the parameter */
14 | Class> getTypeClass();
15 |
16 | /** @return TypeSchema of the parameter */
17 | TypeSchema getSchema();
18 |
19 | /** @return Parameter */
20 | Parameter getParameter();
21 |
22 | /** @return name of the parameter */
23 | String getName();
24 | }
25 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/PropertyDefinition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import java.lang.reflect.Field;
9 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
10 |
11 | public interface PropertyDefinition {
12 |
13 | /** @return Class of the Property */
14 | Class> getTypeClass();
15 |
16 | /** @return TypeSchema */
17 | TypeSchema getSchema();
18 |
19 | /** @return Field */
20 | Field getField();
21 |
22 | /** @return Name of the property */
23 | String getName();
24 | }
25 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/RoutingRegistry.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import java.util.Collection;
9 | import org.hyperledger.fabric.contract.ContractInterface;
10 | import org.hyperledger.fabric.contract.execution.InvocationRequest;
11 |
12 | public interface RoutingRegistry {
13 |
14 | /**
15 | * Add a new contract definition based on the class object located.
16 | *
17 | * @param clz Class Object to process into a ContractDefinition
18 | * @return ContractDefinition Instance
19 | */
20 | ContractDefinition addNewContract(Class clz);
21 |
22 | /**
23 | * Based on the Invocation Request, can we create a route for this?
24 | *
25 | * @param request
26 | * @return ture/false
27 | */
28 | boolean containsRoute(InvocationRequest request);
29 |
30 | /**
31 | * Get the route for invocation request.
32 | *
33 | * @param request
34 | * @return Routing obect
35 | */
36 | TxFunction.Routing getRoute(InvocationRequest request);
37 |
38 | /**
39 | * Get the txFunction that matches the routing request.
40 | *
41 | * @param request
42 | * @return Transaction Function
43 | */
44 | TxFunction getTxFn(InvocationRequest request);
45 |
46 | /**
47 | * Get the contract that matches the supplied name.
48 | *
49 | * @param name
50 | * @return Contract Definition
51 | */
52 | ContractDefinition getContract(String name);
53 |
54 | /**
55 | * Returns all the ContractDefinitions for this registry.
56 | *
57 | * @return Collection of all definitions
58 | */
59 | Collection getAllDefinitions();
60 |
61 | /**
62 | * Locate all the contracts in this chaincode.
63 | *
64 | * @param typeRegistry
65 | */
66 | void findAndSetContracts(TypeRegistry typeRegistry);
67 | }
68 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TransactionType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM DTCC All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | public enum TransactionType {
9 | /** */
10 | INVOKE, // deprecated
11 | /** */
12 | QUERY, // deprecated
13 | /** */
14 | DEFAULT, // deprecated
15 | /** */
16 | SUBMIT,
17 | /** */
18 | EVALUATE
19 | }
20 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TypeRegistry.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import java.util.Collection;
9 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
10 | import org.hyperledger.fabric.contract.routing.impl.TypeRegistryImpl;
11 |
12 | public interface TypeRegistry {
13 |
14 | /** @return TypeRegistry */
15 | static TypeRegistry getRegistry() {
16 | return TypeRegistryImpl.getInstance();
17 | }
18 |
19 | /** @param dtd */
20 | void addDataType(DataTypeDefinition dtd);
21 |
22 | /** @param cl */
23 | void addDataType(Class> cl);
24 |
25 | /**
26 | * @param name
27 | * @return DataTypeDefinition
28 | */
29 | DataTypeDefinition getDataType(String name);
30 |
31 | /**
32 | * @param schema
33 | * @return DataTypeDefinition
34 | */
35 | DataTypeDefinition getDataType(TypeSchema schema);
36 |
37 | /** @return All datatypes */
38 | Collection getAllDataTypes();
39 | }
40 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ParameterDefinitionImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract.routing.impl;
8 |
9 | import java.lang.reflect.Parameter;
10 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
11 | import org.hyperledger.fabric.contract.routing.ParameterDefinition;
12 |
13 | public final class ParameterDefinitionImpl implements ParameterDefinition {
14 |
15 | private final Class> typeClass;
16 | private final TypeSchema schema;
17 | private final Parameter parameter;
18 | private final String name;
19 |
20 | /**
21 | * @param name
22 | * @param typeClass
23 | * @param schema
24 | * @param p
25 | */
26 | public ParameterDefinitionImpl(
27 | final String name, final Class> typeClass, final TypeSchema schema, final Parameter p) {
28 | this.typeClass = typeClass;
29 | this.schema = schema;
30 | this.parameter = p;
31 | this.name = name;
32 | }
33 |
34 | @Override
35 | public Class> getTypeClass() {
36 | return this.typeClass;
37 | }
38 |
39 | @Override
40 | public TypeSchema getSchema() {
41 | return this.schema;
42 | }
43 |
44 | @Override
45 | public Parameter getParameter() {
46 | return this.parameter;
47 | }
48 |
49 | @Override
50 | public String getName() {
51 | return this.name;
52 | }
53 |
54 | @Override
55 | public String toString() {
56 | return this.name + "-" + this.typeClass + "-" + this.schema + "-" + this.parameter;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/PropertyDefinitionImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract.routing.impl;
8 |
9 | import java.lang.reflect.Field;
10 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
11 | import org.hyperledger.fabric.contract.routing.PropertyDefinition;
12 |
13 | public final class PropertyDefinitionImpl implements PropertyDefinition {
14 |
15 | private final Class> typeClass;
16 | private final TypeSchema schema;
17 | private final Field field;
18 | private final String name;
19 |
20 | /**
21 | * @param name
22 | * @param typeClass
23 | * @param schema
24 | * @param f
25 | */
26 | public PropertyDefinitionImpl(final String name, final Class> typeClass, final TypeSchema schema, final Field f) {
27 | this.typeClass = typeClass;
28 | this.schema = schema;
29 | this.field = f;
30 | this.name = name;
31 | }
32 |
33 | @Override
34 | public Class> getTypeClass() {
35 | return this.typeClass;
36 | }
37 |
38 | @Override
39 | public TypeSchema getSchema() {
40 | return this.schema;
41 | }
42 |
43 | @Override
44 | public Field getField() {
45 | return this.field;
46 | }
47 |
48 | @Override
49 | public String getName() {
50 | return this.name;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TypeRegistryImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing.impl;
7 |
8 | import java.util.Collection;
9 | import java.util.HashMap;
10 | import java.util.Map;
11 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
12 | import org.hyperledger.fabric.contract.routing.DataTypeDefinition;
13 | import org.hyperledger.fabric.contract.routing.TypeRegistry;
14 |
15 | /** Registry to hold the complex data types as defined in the contract. */
16 | public final class TypeRegistryImpl implements TypeRegistry {
17 | private static final TypeRegistryImpl INSTANCE = new TypeRegistryImpl();
18 |
19 | private final Map components = new HashMap<>();
20 |
21 | /**
22 | * Get the TypeRegistry singleton instance.
23 | *
24 | * @return TypeRegistry
25 | */
26 | public static TypeRegistry getInstance() {
27 | return INSTANCE;
28 | }
29 |
30 | /*
31 | * (non-Javadoc)
32 | *
33 | * @see
34 | * org.hyperledger.fabric.contract.routing.TypeRegistry#addDataType(java.lang.
35 | * Class)
36 | */
37 | @Override
38 | public void addDataType(final Class> cl) {
39 | final DataTypeDefinitionImpl type = new DataTypeDefinitionImpl(cl);
40 | components.put(type.getSimpleName(), type);
41 | }
42 |
43 | /*
44 | * (non-Javadoc)
45 | *
46 | * @see org.hyperledger.fabric.contract.routing.TypeRegistry#getAllDataTypes()
47 | */
48 | @Override
49 | public Collection getAllDataTypes() {
50 | return components.values();
51 | }
52 |
53 | @Override
54 | public void addDataType(final DataTypeDefinition type) {
55 | components.put(type.getName(), type);
56 | }
57 |
58 | @Override
59 | public DataTypeDefinition getDataType(final String name) {
60 | return this.components.get(name);
61 | }
62 |
63 | @Override
64 | public DataTypeDefinition getDataType(final TypeSchema schema) {
65 | final String ref = schema.getRef();
66 | final String format = ref.substring(ref.lastIndexOf('/') + 1);
67 | return getDataType(format);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** */
8 | package org.hyperledger.fabric.contract.routing.impl;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** */
8 | package org.hyperledger.fabric.contract.routing;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/SystemContract.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.systemcontract;
7 |
8 | import org.hyperledger.fabric.contract.Context;
9 | import org.hyperledger.fabric.contract.ContractInterface;
10 | import org.hyperledger.fabric.contract.annotation.Contract;
11 | import org.hyperledger.fabric.contract.annotation.Info;
12 | import org.hyperledger.fabric.contract.annotation.Transaction;
13 | import org.hyperledger.fabric.contract.metadata.MetadataBuilder;
14 |
15 | /** */
16 | @Contract(
17 | name = "org.hyperledger.fabric",
18 | info =
19 | @Info(
20 | title = "Fabric System Contract",
21 | description = "Provides information about the contracts within this container"))
22 | public final class SystemContract implements ContractInterface {
23 |
24 | /**
25 | * @param ctx
26 | * @return Metadata
27 | */
28 | @Transaction(intent = Transaction.TYPE.EVALUATE, name = "GetMetadata")
29 | public String getMetadata(final Context ctx) {
30 | return MetadataBuilder.getMetadata();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** */
8 | package org.hyperledger.fabric.contract.systemcontract;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Collection.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.ledger;
7 |
8 | /** Place holder. */
9 | @SuppressWarnings("PMD.ImplicitFunctionalInterface")
10 | public interface Collection {
11 |
12 | /** Constant that can be used to refer to the 'Worldstate' collection explicitly. */
13 | String WORLD = "worldstate";
14 |
15 | /**
16 | * Placeholder. Purely in place to prevent Checkstyle inferring this class is pointless. will be removed in the next
17 | * story
18 | */
19 | void placeholder();
20 | }
21 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/LedgerImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.ledger.impl;
7 |
8 | import org.hyperledger.fabric.contract.Context;
9 | import org.hyperledger.fabric.ledger.Collection;
10 | import org.hyperledger.fabric.ledger.Ledger;
11 |
12 | public final class LedgerImpl implements Ledger {
13 |
14 | /**
15 | * New Ledger Implementation.
16 | *
17 | * @param ctx Context transactional context to use
18 | */
19 | @SuppressWarnings("PMD.UnusedFormalParameter")
20 | public LedgerImpl(final Context ctx) {
21 | // Empty stub
22 | }
23 |
24 | @Override
25 | public Collection getCollection(final String name) {
26 | return new Collection() {
27 | @Override
28 | public void placeholder() {
29 | // Empty stub
30 | }
31 | };
32 | }
33 |
34 | @Override
35 | public Collection getDefaultCollection() {
36 | return this.getCollection(Collection.WORLD);
37 | }
38 |
39 | @Override
40 | public Collection getOrganizationCollection(final String mspid) {
41 | return this.getCollection("_implicit_org_" + mspid);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.ledger.impl;
7 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** Provides the API for contracts to access the shared ledger. */
8 | package org.hyperledger.fabric.ledger;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.metrics;
8 |
9 | import java.util.Properties;
10 |
11 | /**
12 | * Interface to be implemented to send metrics on the chaincode to the 'backend-of-choice'.
13 | *
14 | * An instance of this will be created, and provided with the resources from which chaincode specific metrics can be
15 | * collected. (via the no-argument constructor).
16 | *
17 | *
The choice of when, where and what to collect etc are within the remit of the provider.
18 | *
19 | *
This is the effective call sequence.
20 | *
21 | *
MyMetricsProvider mmp = new MyMetricsProvider() mmp.initialize(props_from_environment); // short while later....
22 | * mmp.setTaskMetricsCollector(taskService);
23 | */
24 | public interface MetricsProvider {
25 |
26 | /**
27 | * Initialize method that is called immediately after creation.
28 | *
29 | * @param props
30 | */
31 | default void initialize(final Properties props) {
32 | // Do nothing by default
33 | }
34 |
35 | /**
36 | * Pass a reference to this task service for information gathering. This is related specifically to the handling of
37 | * tasks within the chaincode. i.e. how individual transactions are dispatched for execution.
38 | *
39 | * @param taskService
40 | */
41 | default void setTaskMetricsCollector(final TaskMetricsCollector taskService) {
42 | // Do nothing by default
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.metrics;
7 |
8 | /**
9 | * Collect metrics relating to the task execution.
10 | *
11 | *
The task execution (of which each fabric transaction is one) is backed by a thread pool that implements this
12 | * interface. As that is an implementation class this interface abstracts the information available from it (as far as
13 | * metrics go).
14 | */
15 | public interface TaskMetricsCollector {
16 |
17 | /**
18 | * Currently executing tasks.
19 | *
20 | * @return int > 0
21 | */
22 | int getCurrentTaskCount();
23 |
24 | /**
25 | * Currently waiting tasks; should not be a higher number.
26 | *
27 | * @return int > 0
28 | */
29 | int getCurrentQueueCount();
30 |
31 | /**
32 | * Currently executing threads.
33 | *
34 | * @return int > 0
35 | */
36 | int getActiveCount();
37 |
38 | /**
39 | * Gets the current size of the pool.
40 | *
41 | * @return int > 0
42 | */
43 | int getPoolSize();
44 |
45 | /**
46 | * Gets the core (minimum) pool size.
47 | *
48 | * @return int > 0
49 | */
50 | int getCorePoolSize();
51 |
52 | /**
53 | * Gets the largest pool size so far.
54 | *
55 | * @return int > 0
56 | */
57 | int getLargestPoolSize();
58 |
59 | /**
60 | * Gets the upper limit pool size.
61 | *
62 | * @return int > 0
63 | */
64 | int getMaximumPoolSize();
65 | }
66 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.metrics.impl;
7 |
8 | import org.hyperledger.fabric.metrics.MetricsProvider;
9 |
10 | /** Very simple provider that does absolutely nothing. Used when metrics are disabled. */
11 | public class NullProvider implements MetricsProvider {}
12 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** */
8 | package org.hyperledger.fabric.metrics.impl;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /**
8 | * Provides interfaces and classes to support collection of metrics.
9 | *
10 | *
The main metrics that are available are the statistics around the number of tasks that are running, and how the
11 | * thread pool is handling these.
12 | *
13 | *
Note a 'task' is a message from the Peer to the Chaincode - this message is either a new transaction, or a
14 | * response from a stub API, eg getState(). Query apis may return more than one response.
15 | *
16 | *
To enable metrics, add a CHAINCODE_METRICS_ENABLED=true
setting to the config.props
17 | * chaincode configuration file. See the Overview for details of how to configure
18 | * chaincode.
19 | *
20 | *
Open Telemetry To use Open Telemetry, set the following properties:
21 | *
22 | *
23 | * CHAINCODE_METRICS_ENABLED=true
24 | * CHAINCODE_METRICS_PROVIDER=org.hyperledger.fabric.metrics.impl.OpenTelemetryMetricsProvider
25 | *
26 | *
27 | * Additionally, you can set properties after the specification:
28 | * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/sdk-environment-variables.md
29 | *
30 | * Example:
31 | *
32 | *
33 | * OTEL_EXPORTER_OTLP_ENDPOINT=otelcollector:4317
34 | * OTEL_EXPORTER_OTLP_INSECURE=true
35 | *
36 | */
37 | package org.hyperledger.fabric.metrics;
38 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** Provides logging classes. */
8 | package org.hyperledger.fabric;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim;
8 |
9 | import java.io.IOException;
10 |
11 | /** External chaincode server. */
12 | public interface ChaincodeServer {
13 |
14 | /**
15 | * run external chaincode server.
16 | *
17 | * @throws IOException problem while start grpc server
18 | * @throws InterruptedException thrown when block and awaiting shutdown gprc server
19 | */
20 | void start() throws IOException, InterruptedException;
21 |
22 | /** shutdown now grpc server. */
23 | void stop();
24 | }
25 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim;
7 |
8 | import io.grpc.stub.StreamObserver;
9 | import java.io.IOException;
10 | import java.util.logging.Logger;
11 | import org.hyperledger.fabric.Logging;
12 | import org.hyperledger.fabric.protos.peer.ChaincodeGrpc;
13 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
14 |
15 | public class ChatChaincodeWithPeer extends ChaincodeGrpc.ChaincodeImplBase {
16 | private static Logger logger = Logger.getLogger(ChatChaincodeWithPeer.class.getName());
17 |
18 | private final ChaincodeBase chaincodeBase;
19 |
20 | ChatChaincodeWithPeer(final ChaincodeBase chaincodeBase) throws IOException {
21 | super();
22 | if (chaincodeBase == null) {
23 | throw new IOException("chaincodeBase can't be null");
24 | }
25 | chaincodeBase.validateOptions();
26 |
27 | this.chaincodeBase = chaincodeBase;
28 | }
29 |
30 | /**
31 | * Chaincode as a server - peer establishes a connection to the chaincode as a client Currently only supports a
32 | * stream connection.
33 | *
34 | * @param responseObserver
35 | * @return
36 | */
37 | @Override
38 | @SuppressWarnings("PMD.AvoidCatchingGenericException")
39 | public StreamObserver connect(final StreamObserver responseObserver) {
40 | if (responseObserver == null) {
41 | return null;
42 | }
43 |
44 | try {
45 | return chaincodeBase.connectToPeer(responseObserver);
46 | } catch (Exception e) {
47 | logger.severe(() ->
48 | "catch exception while chaincodeBase.connectToPeer(responseObserver)." + Logging.formatError(e));
49 | return null;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim;
8 |
9 | import java.io.IOException;
10 |
11 | /** Common interface for grpc server. */
12 | public interface GrpcServer {
13 |
14 | /**
15 | * start grpc server.
16 | *
17 | * @throws IOException problem while start grpc server
18 | */
19 | void start() throws IOException;
20 |
21 | /** shutdown now grpc server. */
22 | void stop();
23 |
24 | /**
25 | * Await termination on the main thread since the grpc library uses daemon threads.
26 | *
27 | * @throws InterruptedException
28 | */
29 | void blockUntilShutdown() throws InterruptedException;
30 | }
31 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim;
8 |
9 | import java.io.IOException;
10 |
11 | public class NettyChaincodeServer implements ChaincodeServer {
12 |
13 | /** Server. */
14 | private final GrpcServer grpcServer;
15 |
16 | /**
17 | * configure and init server.
18 | *
19 | * @param chaincodeBase - chaincode implementation (invoke, init)
20 | * @param chaincodeServerProperties - setting for grpc server
21 | * @throws IOException
22 | */
23 | public NettyChaincodeServer(
24 | final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties)
25 | throws IOException {
26 | // create listener and grpc server
27 | grpcServer = new NettyGrpcServer(chaincodeBase, chaincodeServerProperties);
28 | }
29 |
30 | /**
31 | * run external chaincode server.
32 | *
33 | * @throws IOException problem while start grpc server
34 | * @throws InterruptedException thrown when block and awaiting shutdown gprc server
35 | */
36 | @Override
37 | public void start() throws IOException, InterruptedException {
38 | grpcServer.start();
39 | grpcServer.blockUntilShutdown();
40 | }
41 |
42 | /** shutdown now grpc server. */
43 | @Override
44 | public void stop() {
45 | grpcServer.stop();
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM DTCC All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.ext.sbe.impl;
7 |
8 | import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement;
9 |
10 | /** Factory for {@link StateBasedEndorsement} objects. */
11 | public class StateBasedEndorsementFactory {
12 | private static final StateBasedEndorsementFactory INSTANCE = new StateBasedEndorsementFactory();
13 |
14 | /** @return Endorsement Factory */
15 | public static StateBasedEndorsementFactory getInstance() {
16 | return INSTANCE;
17 | }
18 |
19 | /**
20 | * Constructs a state-based endorsement policy from a given serialized EP byte array. If the byte array is empty, a
21 | * new EP is created.
22 | *
23 | * @param ep serialized endorsement policy
24 | * @return New StateBasedEndorsement instance
25 | */
26 | public StateBasedEndorsement newStateBasedEndorsement(final byte[] ep) {
27 | return new StateBasedEndorsementImpl(ep);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.ext.sbe.impl;
7 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** Provides an interface for creating and modifying state-based endorsement policies. */
8 | package org.hyperledger.fabric.shim.ext.sbe;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM DTCC All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.impl;
7 |
8 | import java.util.concurrent.BlockingQueue;
9 | import java.util.concurrent.RejectedExecutionHandler;
10 | import java.util.concurrent.ThreadFactory;
11 | import java.util.concurrent.ThreadPoolExecutor;
12 | import java.util.concurrent.TimeUnit;
13 | import java.util.concurrent.atomic.AtomicInteger;
14 | import java.util.logging.Logger;
15 | import org.hyperledger.fabric.metrics.TaskMetricsCollector;
16 |
17 | /** */
18 | public final class InvocationTaskExecutor extends ThreadPoolExecutor implements TaskMetricsCollector {
19 | private static Logger logger = Logger.getLogger(InvocationTaskExecutor.class.getName());
20 |
21 | private final AtomicInteger count = new AtomicInteger();
22 |
23 | /**
24 | * @param corePoolSize
25 | * @param maximumPoolSize
26 | * @param keepAliveTime
27 | * @param unit
28 | * @param workQueue
29 | * @param factory
30 | * @param handler
31 | */
32 | public InvocationTaskExecutor(
33 | final int corePoolSize,
34 | final int maximumPoolSize,
35 | final long keepAliveTime,
36 | final TimeUnit unit,
37 | final BlockingQueue workQueue,
38 | final ThreadFactory factory,
39 | final RejectedExecutionHandler handler) {
40 | super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory, handler);
41 | prestartCoreThread();
42 | logger.info("Thread pool created");
43 | }
44 |
45 | @Override
46 | protected void beforeExecute(final Thread thread, final Runnable task) {
47 | super.beforeExecute(thread, task);
48 | count.incrementAndGet();
49 | }
50 |
51 | @Override
52 | protected void afterExecute(final Runnable task, final Throwable throwable) {
53 | count.decrementAndGet();
54 | super.afterExecute(task, throwable);
55 | }
56 |
57 | @Override
58 | public int getCurrentTaskCount() {
59 | return count.get();
60 | }
61 |
62 | @Override
63 | public int getCurrentQueueCount() {
64 | return this.getQueue().size();
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyValueImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.impl;
7 |
8 | import com.google.protobuf.ByteString;
9 | import org.hyperledger.fabric.protos.ledger.queryresult.KV;
10 | import org.hyperledger.fabric.shim.ledger.KeyValue;
11 |
12 | class KeyValueImpl implements KeyValue {
13 |
14 | private final String key;
15 | private final ByteString value;
16 |
17 | KeyValueImpl(final KV kv) {
18 | this.key = kv.getKey();
19 | this.value = kv.getValue();
20 | }
21 |
22 | @Override
23 | public String getKey() {
24 | return key;
25 | }
26 |
27 | @Override
28 | public byte[] getValue() {
29 | return value.toByteArray();
30 | }
31 |
32 | @Override
33 | public String getStringValue() {
34 | return value.toStringUtf8();
35 | }
36 |
37 | @Override
38 | public int hashCode() {
39 | final int prime = 31;
40 | int result = key.hashCode();
41 | result = prime * result + value.hashCode();
42 | return result;
43 | }
44 |
45 | @Override
46 | public boolean equals(final Object other) {
47 | if (this == other) {
48 | return true;
49 | }
50 | if (other == null) {
51 | return false;
52 | }
53 | if (getClass() != other.getClass()) {
54 | return false;
55 | }
56 |
57 | final KeyValueImpl that = (KeyValueImpl) other;
58 | return this.key.equals(that.key) && this.value.equals(that.value);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.impl;
8 |
9 | import com.google.protobuf.ByteString;
10 | import com.google.protobuf.InvalidProtocolBufferException;
11 | import java.io.UncheckedIOException;
12 | import java.util.function.Function;
13 | import java.util.logging.Logger;
14 | import org.hyperledger.fabric.protos.peer.QueryResponse;
15 | import org.hyperledger.fabric.protos.peer.QueryResponseMetadata;
16 | import org.hyperledger.fabric.protos.peer.QueryResultBytes;
17 | import org.hyperledger.fabric.shim.ledger.QueryResultsIteratorWithMetadata;
18 |
19 | /**
20 | * QueryResult Iterator.
21 | *
22 | * Implementation of {@link QueryResultsIteratorWithMetadata}, by extending
23 | * {@link org.hyperledger.fabric.shim.ledger.QueryResultsIterator} implementations, {@link QueryResultsIteratorImpl}
24 | *
25 | * @param
26 | */
27 | public final class QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl
28 | implements QueryResultsIteratorWithMetadata {
29 | private static final Logger LOGGER = Logger.getLogger(QueryResultsIteratorWithMetadataImpl.class.getName());
30 |
31 | private final QueryResponseMetadata metadata;
32 |
33 | /**
34 | * @param handler
35 | * @param channelId
36 | * @param txId
37 | * @param responseBuffer
38 | * @param mapper
39 | */
40 | public QueryResultsIteratorWithMetadataImpl(
41 | final ChaincodeInvocationTask handler,
42 | final String channelId,
43 | final String txId,
44 | final ByteString responseBuffer,
45 | final Function mapper) {
46 | super(handler, channelId, txId, responseBuffer, mapper);
47 | try {
48 | final QueryResponse queryResponse = QueryResponse.parseFrom(responseBuffer);
49 | metadata = QueryResponseMetadata.parseFrom(queryResponse.getMetadata());
50 | } catch (final InvalidProtocolBufferException e) {
51 | LOGGER.warning("can't parse response metadata");
52 | throw new UncheckedIOException(e);
53 | }
54 | }
55 |
56 | @Override
57 | public QueryResponseMetadata getMetadata() {
58 | return metadata;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /** */
8 | package org.hyperledger.fabric.shim.impl;
9 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/CompositeKeyFormatException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.ledger;
8 |
9 | final class CompositeKeyFormatException extends IllegalArgumentException {
10 | private static final long serialVersionUID = 1L;
11 |
12 | private CompositeKeyFormatException(final String s) {
13 | super(s);
14 | }
15 |
16 | static CompositeKeyFormatException forInputString(final String s, final String group, final int index) {
17 | return new CompositeKeyFormatException(
18 | String.format("For input string '%s', found 'U+%06X' at index %d.", s, group.codePointAt(0), index));
19 | }
20 |
21 | static CompositeKeyFormatException forSimpleKey(final String key) {
22 | return new CompositeKeyFormatException(String.format(
23 | "First character of the key [%s] contains a 'U+%06X' which is not allowed",
24 | key, CompositeKey.NAMESPACE.codePointAt(0)));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/KeyModification.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.ledger;
8 |
9 | /**
10 | * QueryResult for history query. Holds a transaction ID, value, timestamp, and delete marker which resulted from a
11 | * history query.
12 | */
13 | public interface KeyModification {
14 |
15 | /**
16 | * Returns the transaction id.
17 | *
18 | * @return tx id of modification
19 | */
20 | String getTxId();
21 |
22 | /**
23 | * Returns the key's value at the time returned by {@link #getTimestamp()}.
24 | *
25 | * @return value
26 | */
27 | byte[] getValue();
28 |
29 | /**
30 | * Returns the key's value at the time returned by {@link #getTimestamp()}, decoded as a UTF-8 string.
31 | *
32 | * @return value as string
33 | */
34 | String getStringValue();
35 |
36 | /**
37 | * Returns the timestamp of the key modification entry.
38 | *
39 | * @return timestamp
40 | */
41 | java.time.Instant getTimestamp();
42 |
43 | /**
44 | * Returns the deletion marker.
45 | *
46 | * @return is key was deleted
47 | */
48 | boolean isDeleted();
49 | }
50 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/KeyValue.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.ledger;
8 |
9 | /** Query Result associating a state key with a value. */
10 | public interface KeyValue {
11 |
12 | /**
13 | * Returns the state key.
14 | *
15 | * @return key as string
16 | */
17 | String getKey();
18 |
19 | /**
20 | * Returns the state value.
21 | *
22 | * @return value as byte array
23 | */
24 | byte[] getValue();
25 |
26 | /**
27 | * Returns the state value, decoded as a UTF-8 string.
28 | *
29 | * @return value as string
30 | */
31 | String getStringValue();
32 | }
33 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/QueryResultsIterator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.ledger;
8 |
9 | /**
10 | * QueryResultsIterator allows a chaincode to iterate over a set of key/value pairs returned by range, execute and
11 | * history queries.
12 | *
13 | * @param the type of elements returned by the iterator
14 | */
15 | public interface QueryResultsIterator extends Iterable, AutoCloseable {}
16 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/QueryResultsIteratorWithMetadata.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.ledger;
8 |
9 | import org.hyperledger.fabric.protos.peer.QueryResponseMetadata;
10 |
11 | /**
12 | * QueryResultsIteratorWithMetadata allows a chaincode to iterate over a set of key/value pairs returned by range,
13 | * execute and history queries. In addition, it store {@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata},
14 | * returned by pagination range queries
15 | *
16 | * @param the type of elements returned by the iterator
17 | */
18 | public interface QueryResultsIteratorWithMetadata extends Iterable, AutoCloseable {
19 | /** @return Query Metadata */
20 | QueryResponseMetadata getMetadata();
21 | }
22 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /**
8 | * Provides interfaces and classes for querying state variables.
9 | *
10 | * @see org.hyperledger.fabric.shim.ChaincodeStub
11 | */
12 | package org.hyperledger.fabric.shim.ledger;
13 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /**
8 | * Provides interfaces and classes required for chaincode development and state variable access.
9 | *
10 | * It is possible to implement Java chaincode by extending the {@link org.hyperledger.fabric.shim.ChaincodeBase}
11 | * class however new projects should should implement {@link org.hyperledger.fabric.contract.ContractInterface} and use
12 | * the contract programming model instead.
13 | *
14 | * @see org.hyperledger.fabric.contract
15 | * @see org.hyperledger.fabric.shim.ChaincodeBase
16 | */
17 | package org.hyperledger.fabric.shim;
18 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/TracesProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.traces;
8 |
9 | import io.grpc.ClientInterceptor;
10 | import io.opentelemetry.api.trace.Span;
11 | import java.util.Properties;
12 | import org.hyperledger.fabric.shim.ChaincodeStub;
13 |
14 | /**
15 | * Interface to be implemented to send traces on the chaincode to the 'backend-of-choice'.
16 | *
17 | *
An instance of this will be created, and provided with the resources from which chaincode specific metrics can be
18 | * collected. (via the no-argument constructor).
19 | *
20 | *
The choice of when, where and what to collect etc are within the remit of the provider.
21 | *
22 | *
This is the effective call sequence.
23 | *
24 | *
MyTracesProvider mmp = new MyTracesProvider() mmp.initialize(props_from_environment); // short while later....
25 | * mmp.setTaskTracesCollector(taskService);
26 | */
27 | public interface TracesProvider {
28 |
29 | /**
30 | * Initialize method that is called immediately after creation.
31 | *
32 | * @param props
33 | */
34 | default void initialize(final Properties props) {
35 | // Do nothing by default
36 | }
37 |
38 | /**
39 | * Creates a span with metadata of the current chaincode execution, possibly linked to the execution arguments.
40 | *
41 | * @param stub the context of the chaincode execution
42 | * @return a new span if traces are enabled, or null. The caller is responsible for closing explicitly the span.
43 | */
44 | default Span createSpan(ChaincodeStub stub) {
45 | return null;
46 | }
47 |
48 | /**
49 | * Creates an interceptor of gRPC messages that can be injected in processing incoming messages to extract trace
50 | * information.
51 | *
52 | * @return a new client interceptor, or null if no interceptor is set.
53 | */
54 | default ClientInterceptor createInterceptor() {
55 | return null;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/DefaultTracesProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.traces.impl;
7 |
8 | import org.hyperledger.fabric.traces.TracesProvider;
9 |
10 | public final class DefaultTracesProvider implements TracesProvider {}
11 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/NullProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.traces.impl;
7 |
8 | import org.hyperledger.fabric.traces.TracesProvider;
9 |
10 | public final class NullProvider implements TracesProvider {}
11 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.traces.impl;
7 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /**
8 | * Supports collection of traces
9 | *
10 | *
This creates traces at the root level of chaincode calls.
11 | *
12 | *
To enable traces ensure that there is a standard format Java properties file called `config.props` in the root of
13 | * your contract code. For example this path
14 | *
15 | *
16 | * myjava - contract - project / java / src / main / resources / config.props
17 | *
18 | *
19 | * This should contain the following
20 | *
21 | *
22 | * CHAINCODE_TRACES_ENABLED=true
23 | *
24 | *
25 | * The traces enabled flag will turn on default traces logging. (it's off by default).
26 | *
27 | * If no file is supplied traces are not enabled, the values shown for the thread pool are used.
28 | *
29 | *
Open Telemetry To use Open Telemetry, set the following properties:
30 | *
31 | *
32 | * CHAINCODE_TRACES_ENABLED=true
33 | * CHAINCODE_TRACES_PROVIDER=org.hyperledger.fabric.traces.impl.OpenTelemetryTracesProvider
34 | *
35 | *
36 | * Additionally, you can set properties after the specification:
37 | * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/sdk-environment-variables.md
38 | *
39 | * Example:
40 | *
41 | *
42 | * OTEL_EXPORTER_OTLP_ENDPOINT=otelcollector:4317
43 | * OTEL_EXPORTER_OTLP_INSECURE=true
44 | *
45 | */
46 | package org.hyperledger.fabric.traces;
47 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/ChaincodeWithoutPackageTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | import static org.assertj.core.api.Assertions.assertThat;
8 | import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.READY;
9 | import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER;
10 |
11 | import java.util.ArrayList;
12 | import java.util.List;
13 | import java.util.concurrent.TimeUnit;
14 | import org.hyperledger.fabric.shim.ChaincodeBase;
15 | import org.hyperledger.fabric.shim.mock.peer.ChaincodeMockPeer;
16 | import org.hyperledger.fabric.shim.mock.peer.RegisterStep;
17 | import org.hyperledger.fabric.shim.mock.peer.ScenarioStep;
18 | import org.junit.jupiter.api.AfterEach;
19 | import org.junit.jupiter.api.Test;
20 |
21 | final class ChaincodeWithoutPackageTest {
22 | private ChaincodeMockPeer server;
23 |
24 | @AfterEach
25 | void afterTest() throws Exception {
26 | if (server != null) {
27 | server.stop();
28 | server = null;
29 | }
30 | }
31 |
32 | @Test
33 | void testRegisterChaincodeWithoutPackage() throws Exception {
34 | final ChaincodeBase cb = new EmptyChaincodeWithoutPackage();
35 |
36 | final List scenario = new ArrayList<>();
37 | scenario.add(new RegisterStep());
38 |
39 | server = ChaincodeMockPeer.startServer(scenario);
40 |
41 | cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
42 |
43 | ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
44 |
45 | assertThat(server.getLastMessageSend().getType()).isEqualTo(READY);
46 | assertThat(server.getLastMessageRcvd().getType()).isEqualTo(REGISTER);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/EmptyChaincodeWithoutPackage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | import org.hyperledger.fabric.shim.ChaincodeBase;
8 | import org.hyperledger.fabric.shim.ChaincodeStub;
9 | import org.hyperledger.fabric.shim.ResponseUtils;
10 |
11 | public final class EmptyChaincodeWithoutPackage extends ChaincodeBase {
12 | @Override
13 | public Response init(final ChaincodeStub stub) {
14 | return ResponseUtils.newSuccessResponse();
15 | }
16 |
17 | @Override
18 | public Response invoke(final ChaincodeStub stub) {
19 | return ResponseUtils.newSuccessResponse();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/contract/Greeting.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package contract;
7 |
8 | import static org.assertj.core.api.Assertions.assertThat;
9 |
10 | import org.hyperledger.fabric.contract.annotation.DataType;
11 | import org.hyperledger.fabric.contract.annotation.Property;
12 | import org.json.JSONObject;
13 |
14 | @DataType()
15 | public final class Greeting {
16 |
17 | @Property()
18 | private String text;
19 |
20 | @Property()
21 | private int textLength;
22 |
23 | public String getText() {
24 | return text;
25 | }
26 |
27 | public void setText(final String text) {
28 | this.text = text;
29 | }
30 |
31 | public int getTextLength() {
32 | return textLength;
33 | }
34 |
35 | public void setTextLength(final int textLength) {
36 | this.textLength = textLength;
37 | }
38 |
39 | public int getWordCount() {
40 | return wordCount;
41 | }
42 |
43 | public void setWordCount(final int wordCount) {
44 | this.wordCount = wordCount;
45 | }
46 |
47 | private int wordCount;
48 |
49 | public Greeting(final String text) {
50 | this.text = text;
51 | this.textLength = text.length();
52 | this.wordCount = text.split(" ").length;
53 | }
54 |
55 | public static void validate(final Greeting greeting) {
56 | final String text = greeting.text;
57 |
58 | assertThat(text).as("greeting length").hasSize(greeting.textLength);
59 | assertThat(text.split(" ")).as("word count").hasSize(greeting.wordCount);
60 | }
61 |
62 | public String toJSONString() {
63 | return new JSONObject(this).toString();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggerTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric;
8 |
9 | import org.hyperledger.fabric.contract.ContractRuntimeException;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class LoggerTest {
13 | @Test
14 | void logger() {
15 | Logger.getLogger(LoggerTest.class);
16 | Logger.getLogger(LoggerTest.class.getName());
17 | }
18 |
19 | @Test
20 | void testContractException() {
21 | final Logger logger = Logger.getLogger(LoggerTest.class);
22 |
23 | final ContractRuntimeException cre1 = new ContractRuntimeException("");
24 | logger.formatError(cre1);
25 |
26 | final ContractRuntimeException cre2 = new ContractRuntimeException("", cre1);
27 | final ContractRuntimeException cre3 = new ContractRuntimeException("", cre2);
28 | logger.formatError(cre3);
29 |
30 | logger.error("all gone wrong");
31 | logger.error(() -> "all gone wrong");
32 | }
33 |
34 | @Test
35 | void testDebug() {
36 | Logger.getLogger(LoggerTest.class).debug("debug message");
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextFactoryTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract;
7 |
8 | import static org.hamcrest.MatcherAssert.assertThat;
9 | import static org.hamcrest.Matchers.equalTo;
10 | import static org.hamcrest.Matchers.is;
11 | import static org.hamcrest.Matchers.sameInstance;
12 |
13 | import java.util.Collections;
14 | import org.hyperledger.fabric.shim.ChaincodeStub;
15 | import org.junit.jupiter.api.Test;
16 |
17 | final class ContextFactoryTest {
18 |
19 | @Test
20 | void getInstance() {
21 | final ContextFactory f1 = ContextFactory.getInstance();
22 | final ContextFactory f2 = ContextFactory.getInstance();
23 | assertThat(f1, sameInstance(f2));
24 | }
25 |
26 | @Test
27 | void createContext() {
28 | final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
29 | final Context ctx = ContextFactory.getInstance().createContext(stub);
30 |
31 | assertThat(stub.getArgs(), is(equalTo(ctx.getStub().getArgs())));
32 | assertThat(stub.getStringArgs(), is(equalTo(ctx.getStub().getStringArgs())));
33 | assertThat(stub.getFunction(), is(equalTo(ctx.getStub().getFunction())));
34 | assertThat(stub.getParameters(), is(equalTo(ctx.getStub().getParameters())));
35 | assertThat(stub.getTxId(), is(equalTo(ctx.getStub().getTxId())));
36 | assertThat(stub.getChannelId(), is(equalTo(ctx.getStub().getChannelId())));
37 | assertThat(
38 | stub.invokeChaincode("cc", Collections.emptyList(), "ch0"),
39 | is(equalTo(ctx.getStub().invokeChaincode("cc", Collections.emptyList(), "ch0"))));
40 |
41 | assertThat(stub.getState("a"), is(equalTo(ctx.getStub().getState("a"))));
42 | ctx.getStub().putState("b", "sdfg".getBytes());
43 | assertThat(stub.getStringState("b"), is(equalTo(ctx.getStub().getStringState("b"))));
44 |
45 | assertThat(ctx.clientIdentity.getMSPID(), is(equalTo("testMSPID")));
46 | assertThat(
47 | ctx.clientIdentity.getId(),
48 | is(equalTo("x509::CN=admin, OU=Fabric, O=Hyperledger, ST=North Carolina,"
49 | + " C=US::CN=example.com, OU=WWW, O=Internet Widgets, L=San Francisco, ST=California, C=US")));
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract;
7 |
8 | import static org.hamcrest.MatcherAssert.assertThat;
9 | import static org.hamcrest.Matchers.sameInstance;
10 |
11 | import org.hyperledger.fabric.shim.ChaincodeStub;
12 | import org.junit.jupiter.api.Test;
13 |
14 | final class ContextTest {
15 |
16 | /** Test creating a new context returns what we expect */
17 | @Test
18 | void getInstance() {
19 | final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
20 | final Context context1 = new Context(stub);
21 | final Context context2 = new Context(stub);
22 | assertThat(context1.getStub(), sameInstance(context2.getStub()));
23 | }
24 |
25 | /** Test identity created in Context constructor matches getClientIdentity */
26 | @Test
27 | void getSetClientIdentity() {
28 | final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
29 | final Context context = ContextFactory.getInstance().createContext(stub);
30 | assertThat(context.getClientIdentity(), sameInstance(context.clientIdentity));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractInterfaceTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract;
7 |
8 | import static org.assertj.core.api.Assertions.assertThatThrownBy;
9 | import static org.hamcrest.MatcherAssert.assertThat;
10 | import static org.hamcrest.Matchers.instanceOf;
11 | import static org.hamcrest.Matchers.is;
12 |
13 | import org.hyperledger.fabric.shim.ChaincodeException;
14 | import org.junit.jupiter.api.Test;
15 |
16 | final class ContractInterfaceTest {
17 | @Test
18 | void createContext() {
19 | assertThat(
20 | new ContractInterface() {}.createContext(new ChaincodeStubNaiveImpl()), is(instanceOf(Context.class)));
21 | }
22 |
23 | @Test
24 | void unknownTransaction() {
25 | final ContractInterface c = new ContractInterface() {};
26 |
27 | assertThatThrownBy(() -> c.unknownTransaction(c.createContext(new ChaincodeStubNaiveImpl())))
28 | .isInstanceOf(ChaincodeException.class)
29 | .hasMessage("Undefined contract method called");
30 | }
31 |
32 | @Test
33 | void beforeTransaction() {
34 | final ContractInterface c = new ContractInterface() {};
35 |
36 | c.beforeTransaction(c.createContext(new ChaincodeStubNaiveImpl()));
37 | }
38 |
39 | @Test
40 | void afterTransaction() {
41 | final ContractInterface c = new ContractInterface() {};
42 | c.afterTransaction(c.createContext(new ChaincodeStubNaiveImpl()), "ReturnValue");
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract;
8 |
9 | import org.hyperledger.fabric.contract.annotation.DataType;
10 | import org.hyperledger.fabric.contract.annotation.Property;
11 | import org.json.JSONPropertyIgnore;
12 |
13 | @DataType
14 | public final class MyType {
15 |
16 | @Property()
17 | private String value;
18 |
19 | private String state = "";
20 |
21 | public static final String STARTED = "STARTED";
22 | public static final String STOPPED = "STOPPED";
23 |
24 | public void setState(final String state) {
25 | this.state = state;
26 | }
27 |
28 | @JSONPropertyIgnore()
29 | public boolean isStarted() {
30 | return STARTED.equals(state);
31 | }
32 |
33 | @JSONPropertyIgnore()
34 | public boolean isStopped() {
35 | return STOPPED.equals(state);
36 | }
37 |
38 | public MyType setValue(final String value) {
39 | this.value = value;
40 | return this;
41 | }
42 |
43 | public String getValue() {
44 | return this.value;
45 | }
46 |
47 | @Override
48 | public String toString() {
49 | return "++++ MyType: " + value;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType2.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.contract;
8 |
9 | import org.hyperledger.fabric.contract.annotation.DataType;
10 | import org.hyperledger.fabric.contract.annotation.Property;
11 |
12 | @DataType
13 | public final class MyType2 {
14 |
15 | @Property()
16 | private String value;
17 |
18 | @Property(
19 | schema = {
20 | "title",
21 | "MrProperty",
22 | "Pattern",
23 | "[a-z]",
24 | "uniqueItems",
25 | "false",
26 | "required",
27 | "true,false",
28 | "enum",
29 | "a,bee,cee,dee",
30 | "minimum",
31 | "42"
32 | })
33 | private String constrainedValue;
34 |
35 | public MyType2 setValue(final String value) {
36 | this.value = value;
37 | return this;
38 | }
39 |
40 | public String getValue() {
41 | return this.value;
42 | }
43 |
44 | @Override
45 | public String toString() {
46 | return "++++ MyType: " + value;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ContractDefinitionTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import static org.assertj.core.api.Assertions.assertThat;
9 | import static org.assertj.core.api.Assertions.assertThatThrownBy;
10 |
11 | import contract.SampleContract;
12 | import java.lang.reflect.Method;
13 | import org.hyperledger.fabric.contract.Context;
14 | import org.hyperledger.fabric.contract.ContractInterface;
15 | import org.hyperledger.fabric.contract.ContractRuntimeException;
16 | import org.hyperledger.fabric.contract.routing.impl.ContractDefinitionImpl;
17 | import org.junit.jupiter.api.Test;
18 |
19 | final class ContractDefinitionTest {
20 | @Test
21 | void constructor() throws SecurityException {
22 |
23 | final ContractDefinition cf = new ContractDefinitionImpl(SampleContract.class);
24 | assertThat(cf.toString()).startsWith("samplecontract:");
25 | }
26 |
27 | @Test
28 | void duplicateTransaction() throws NoSuchMethodException, SecurityException {
29 | final ContractDefinition cf = new ContractDefinitionImpl(SampleContract.class);
30 |
31 | final ContractInterface contract = new SampleContract();
32 | final Method m = contract.getClass().getMethod("t2", new Class>[] {Context.class});
33 |
34 | cf.addTxFunction(m);
35 | assertThatThrownBy(() -> cf.addTxFunction(m))
36 | .isInstanceOf(ContractRuntimeException.class)
37 | .hasMessage("Duplicate transaction method t2");
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/DataTypeDefinitionTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import static org.assertj.core.api.Assertions.assertThat;
9 | import static org.assertj.core.api.Assertions.entry;
10 |
11 | import java.util.Map;
12 | import org.hyperledger.fabric.contract.MyType2;
13 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
14 | import org.hyperledger.fabric.contract.routing.impl.DataTypeDefinitionImpl;
15 | import org.junit.jupiter.api.Test;
16 |
17 | final class DataTypeDefinitionTest {
18 | @Test
19 | void constructor() {
20 | final DataTypeDefinitionImpl dtd = new DataTypeDefinitionImpl(MyType2.class);
21 | assertThat(dtd.getTypeClass()).isEqualTo(MyType2.class);
22 | assertThat(dtd.getName()).isEqualTo("org.hyperledger.fabric.contract.MyType2");
23 | assertThat(dtd.getSimpleName()).isEqualTo("MyType2");
24 |
25 | final Map properties = dtd.getProperties();
26 | assertThat(properties.size()).isEqualTo(2);
27 | assertThat(properties).containsKey("value");
28 | assertThat(properties).containsKey("constrainedValue");
29 |
30 | final PropertyDefinition pd = properties.get("constrainedValue");
31 | final TypeSchema ts = pd.getSchema();
32 |
33 | assertThat(ts)
34 | .contains(
35 | entry("title", "MrProperty"),
36 | entry("Pattern", "[a-z]"),
37 | entry("uniqueItems", false),
38 | entry("required", new String[] {"true", "false"}),
39 | entry("enum", new String[] {"a", "bee", "cee", "dee"}),
40 | entry("minimum", 42));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ParameterDefinitionTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import static org.hamcrest.MatcherAssert.assertThat;
9 | import static org.hamcrest.Matchers.equalTo;
10 |
11 | import java.lang.reflect.Parameter;
12 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
13 | import org.hyperledger.fabric.contract.routing.impl.ParameterDefinitionImpl;
14 | import org.junit.jupiter.api.Test;
15 |
16 | final class ParameterDefinitionTest {
17 | @Test
18 | void constructor() throws NoSuchMethodException, SecurityException {
19 | final Parameter[] params =
20 | String.class.getMethod("concat", String.class).getParameters();
21 | final ParameterDefinition pd = new ParameterDefinitionImpl("test", String.class, new TypeSchema(), params[0]);
22 | assertThat(pd.toString(), equalTo("test-class java.lang.String-{}-java.lang.String arg0"));
23 | assertThat(pd.getTypeClass(), equalTo(String.class));
24 | assertThat(pd.getParameter(), equalTo(params[0]));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/PropertyDefinitionTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import static org.hamcrest.MatcherAssert.assertThat;
9 | import static org.hamcrest.Matchers.equalTo;
10 |
11 | import java.lang.reflect.Field;
12 | import org.hyperledger.fabric.contract.metadata.TypeSchema;
13 | import org.hyperledger.fabric.contract.routing.impl.PropertyDefinitionImpl;
14 | import org.junit.jupiter.api.Test;
15 |
16 | final class PropertyDefinitionTest {
17 | @Test
18 | void constructor() throws NoSuchMethodException, SecurityException {
19 | final Field[] props = String.class.getFields();
20 | final TypeSchema ts = new TypeSchema();
21 | final PropertyDefinition pd = new PropertyDefinitionImpl("test", String.class, ts, props[0]);
22 |
23 | assertThat(pd.getTypeClass(), equalTo(String.class));
24 | assertThat(pd.getField(), equalTo(props[0]));
25 | assertThat(pd.getSchema(), equalTo(ts));
26 | assertThat(pd.getName(), equalTo("test"));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TypeRegistryTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.contract.routing;
7 |
8 | import static org.hamcrest.MatcherAssert.assertThat;
9 | import static org.hamcrest.Matchers.equalTo;
10 |
11 | import java.util.Collection;
12 | import org.hyperledger.fabric.contract.routing.impl.DataTypeDefinitionImpl;
13 | import org.hyperledger.fabric.contract.routing.impl.TypeRegistryImpl;
14 | import org.junit.jupiter.api.Test;
15 |
16 | final class TypeRegistryTest {
17 | @Test
18 | void addDataType() {
19 | final TypeRegistryImpl tr = new TypeRegistryImpl();
20 | tr.addDataType(String.class);
21 |
22 | final DataTypeDefinition drt = tr.getDataType("String");
23 | assertThat(drt.getName(), equalTo("java.lang.String"));
24 | }
25 |
26 | @Test
27 | void addDataTypeDefinition() {
28 | final DataTypeDefinitionImpl dtd = new DataTypeDefinitionImpl(String.class);
29 | final TypeRegistryImpl tr = new TypeRegistryImpl();
30 | tr.addDataType(dtd);
31 |
32 | final DataTypeDefinition drt = tr.getDataType("java.lang.String");
33 | assertThat(drt.getName(), equalTo("java.lang.String"));
34 | }
35 |
36 | @Test
37 | void getAllDataTypes() {
38 |
39 | final TypeRegistryImpl tr = new TypeRegistryImpl();
40 | tr.addDataType(String.class);
41 | tr.addDataType(Integer.class);
42 | tr.addDataType(Float.class);
43 |
44 | final Collection c = tr.getAllDataTypes();
45 | assertThat(c.size(), equalTo(3));
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/chaincode/EmptyChaincode.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.chaincode;
7 |
8 | import org.hyperledger.fabric.shim.ChaincodeBase;
9 | import org.hyperledger.fabric.shim.ChaincodeStub;
10 | import org.hyperledger.fabric.shim.ResponseUtils;
11 |
12 | public final class EmptyChaincode extends ChaincodeBase {
13 | @Override
14 | public Response init(final ChaincodeStub stub) {
15 | return ResponseUtils.newSuccessResponse();
16 | }
17 |
18 | @Override
19 | public Response invoke(final ChaincodeStub stub) {
20 | return ResponseUtils.newSuccessResponse();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsementTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM DTCC All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.ext.sbe;
7 |
8 | import static org.assertj.core.api.Assertions.assertThat;
9 | import static org.assertj.core.api.Assertions.assertThatThrownBy;
10 |
11 | import org.junit.jupiter.api.Test;
12 |
13 | final class StateBasedEndorsementTest {
14 | @Test
15 | void testRoleType() {
16 | assertThat(StateBasedEndorsement.RoleType.forVal("MEMBER"))
17 | .isEqualTo(StateBasedEndorsement.RoleType.RoleTypeMember);
18 | assertThat(StateBasedEndorsement.RoleType.forVal("PEER"))
19 | .isEqualTo(StateBasedEndorsement.RoleType.RoleTypePeer);
20 |
21 | assertThatThrownBy(() -> StateBasedEndorsement.RoleType.forVal("NONEXIST"))
22 | .isInstanceOf(IllegalArgumentException.class);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactoryTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM DTCC All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.ext.sbe.impl;
7 |
8 | import static org.assertj.core.api.Assertions.assertThatThrownBy;
9 | import static org.junit.jupiter.api.Assertions.assertInstanceOf;
10 | import static org.junit.jupiter.api.Assertions.assertNotNull;
11 |
12 | import org.junit.jupiter.api.Test;
13 |
14 | final class StateBasedEndorsementFactoryTest {
15 | @Test
16 | void getInstance() {
17 | assertNotNull(StateBasedEndorsementFactory.getInstance());
18 | assertInstanceOf(StateBasedEndorsementFactory.class, StateBasedEndorsementFactory.getInstance());
19 | }
20 |
21 | @Test
22 | void newStateBasedEndorsement() {
23 | assertNotNull(StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(new byte[] {}));
24 | assertThatThrownBy(() -> StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(new byte[] {0}))
25 | .isInstanceOf(IllegalArgumentException.class);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImplTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.impl;
8 |
9 | import static org.assertj.core.api.Assertions.assertThat;
10 | import static org.assertj.core.api.Assertions.assertThatThrownBy;
11 |
12 | import com.google.protobuf.ByteString;
13 | import java.util.function.Function;
14 | import org.hyperledger.fabric.protos.peer.QueryResponse;
15 | import org.hyperledger.fabric.protos.peer.QueryResponseMetadata;
16 | import org.hyperledger.fabric.protos.peer.QueryResultBytes;
17 | import org.junit.jupiter.api.Test;
18 |
19 | final class QueryResultsIteratorWithMetadataImplTest {
20 | private static final Function QUERY_RESULT_BYTES_TO_KV = queryResultBytes -> 0;
21 |
22 | @Test
23 | void getMetadata() {
24 | final QueryResultsIteratorWithMetadataImpl testIter = new QueryResultsIteratorWithMetadataImpl<>(
25 | null, "", "", prepareQueryResponse().toByteString(), QUERY_RESULT_BYTES_TO_KV);
26 | assertThat(testIter.getMetadata().getBookmark()).isEqualTo("asdf");
27 | assertThat(testIter.getMetadata().getFetchedRecordsCount()).isEqualTo(2);
28 | }
29 |
30 | @Test
31 | void getInvalidMetadata() {
32 | assertThatThrownBy(() -> new QueryResultsIteratorWithMetadataImpl<>(
33 | null, "", "", prepareQueryResponseWrongMeta().toByteString(), QUERY_RESULT_BYTES_TO_KV))
34 | .isInstanceOf(RuntimeException.class);
35 | }
36 |
37 | private QueryResponse prepareQueryResponse() {
38 | final QueryResponseMetadata qrm = QueryResponseMetadata.newBuilder()
39 | .setBookmark("asdf")
40 | .setFetchedRecordsCount(2)
41 | .build();
42 |
43 | return QueryResponse.newBuilder()
44 | .setHasMore(false)
45 | .setMetadata(qrm.toByteString())
46 | .build();
47 | }
48 |
49 | private QueryResponse prepareQueryResponseWrongMeta() {
50 | final ByteString bs = ByteString.copyFrom(new byte[] {0, 0});
51 |
52 | return QueryResponse.newBuilder().setHasMore(false).setMetadata(bs).build();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/CompleteStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.mock.peer;
8 |
9 | import java.util.Collections;
10 | import java.util.List;
11 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
12 |
13 | /** Waits for COMPLETED message, sends nothing back */
14 | public final class CompleteStep implements ScenarioStep {
15 | @Override
16 | public boolean expected(final ChaincodeMessage msg) {
17 | return msg.getType() == ChaincodeMessage.Type.COMPLETED;
18 | }
19 |
20 | @Override
21 | public List next() {
22 | return Collections.emptyList();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/DelValueStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import java.util.ArrayList;
9 | import java.util.List;
10 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
11 |
12 | /**
13 | * Simulates delState() invocation in chaincode Waits for DEL_STATE message from chaincode and sends back response with
14 | * empty payload
15 | */
16 | public final class DelValueStep implements ScenarioStep {
17 | private ChaincodeMessage orgMsg;
18 |
19 | @Override
20 | public boolean expected(final ChaincodeMessage msg) {
21 | orgMsg = msg;
22 | return msg.getType() == ChaincodeMessage.Type.DEL_STATE;
23 | }
24 |
25 | @Override
26 | public List next() {
27 | final List list = new ArrayList<>();
28 | list.add(ChaincodeMessage.newBuilder()
29 | .setType(ChaincodeMessage.Type.RESPONSE)
30 | .setChannelId(orgMsg.getChannelId())
31 | .setTxid(orgMsg.getTxid())
32 | .build());
33 | return list;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ErrorResponseStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import java.util.Collections;
9 | import java.util.List;
10 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
11 |
12 | /** Error message from chaincode side, no response sent */
13 | public final class ErrorResponseStep implements ScenarioStep {
14 | @Override
15 | public boolean expected(final ChaincodeMessage msg) {
16 | return msg.getType() == ChaincodeMessage.Type.ERROR;
17 | }
18 |
19 | @Override
20 | public List next() {
21 | return Collections.emptyList();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetQueryResultStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
9 |
10 | /**
11 | * Simulates query invocation. Waits for GET_QUERY_RESULT Returns message that contains list of results in form ("key"
12 | * => "key Value")*
13 | */
14 | public final class GetQueryResultStep extends QueryResultStep {
15 |
16 | /**
17 | * Initiate step
18 | *
19 | * @param hasNext is response message QueryResponse hasMore field set
20 | * @param vals list of keys to generate ("key" => "key Value") pairs
21 | */
22 | public GetQueryResultStep(final boolean hasNext, final String... vals) {
23 | super(hasNext, vals);
24 | }
25 |
26 | @Override
27 | public boolean expected(final ChaincodeMessage msg) {
28 | super.orgMsg = msg;
29 | return msg.getType() == ChaincodeMessage.Type.GET_QUERY_RESULT;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateByRangeStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
9 |
10 | /**
11 | * Simulates getStateByRange Waits for GET_STATE_BY_RANGE message Returns message that contains list of results in form
12 | * ("key" => "key Value")*
13 | */
14 | public final class GetStateByRangeStep extends QueryResultStep {
15 |
16 | /**
17 | * Initiate step
18 | *
19 | * @param hasNext is response message QueryResponse hasMore field set
20 | * @param vals list of keys to generate ("key" => "key Value") pairs
21 | */
22 | public GetStateByRangeStep(final boolean hasNext, final String... vals) {
23 | super(hasNext, vals);
24 | }
25 |
26 | @Override
27 | public boolean expected(final ChaincodeMessage msg) {
28 | super.orgMsg = msg;
29 | return msg.getType() == ChaincodeMessage.Type.GET_STATE_BY_RANGE;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateMetadata.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import com.google.protobuf.ByteString;
9 | import java.util.ArrayList;
10 | import java.util.List;
11 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
12 | import org.hyperledger.fabric.protos.peer.MetaDataKeys;
13 | import org.hyperledger.fabric.protos.peer.StateMetadata;
14 | import org.hyperledger.fabric.protos.peer.StateMetadataResult;
15 | import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement;
16 |
17 | /**
18 | * simulates Handler.getStateMetadata Waits for GET_STATE_METADATA message Returns response message with stored metadata
19 | */
20 | public final class GetStateMetadata implements ScenarioStep {
21 | private ChaincodeMessage orgMsg;
22 | private final byte[] val;
23 |
24 | /** @param sbe StateBasedEndorsement to return as one and only one metadata entry */
25 | public GetStateMetadata(final StateBasedEndorsement sbe) {
26 | val = sbe.policy();
27 | }
28 |
29 | @Override
30 | public boolean expected(final ChaincodeMessage msg) {
31 | orgMsg = msg;
32 | return msg.getType() == ChaincodeMessage.Type.GET_STATE_METADATA;
33 | }
34 |
35 | @Override
36 | public List next() {
37 | final List entriesList = new ArrayList<>();
38 | final StateMetadata validationValue = StateMetadata.newBuilder()
39 | .setMetakey(MetaDataKeys.VALIDATION_PARAMETER.toString())
40 | .setValue(ByteString.copyFrom(val))
41 | .build();
42 | entriesList.add(validationValue);
43 | final StateMetadataResult stateMetadataResult =
44 | StateMetadataResult.newBuilder().addAllEntries(entriesList).build();
45 | final List list = new ArrayList<>();
46 | list.add(ChaincodeMessage.newBuilder()
47 | .setType(ChaincodeMessage.Type.RESPONSE)
48 | .setChannelId(orgMsg.getChannelId())
49 | .setTxid(orgMsg.getTxid())
50 | .setPayload(stateMetadataResult.toByteString())
51 | .build());
52 | return list;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetValueStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import com.google.protobuf.ByteString;
9 | import java.util.ArrayList;
10 | import java.util.List;
11 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
12 |
13 | /** Simulates getState Waits for GET_STATE message Returns response message with value as payload */
14 | public final class GetValueStep implements ScenarioStep {
15 | private ChaincodeMessage orgMsg;
16 | private final String val;
17 |
18 | /** @param val value to return */
19 | public GetValueStep(final String val) {
20 | this.val = val;
21 | }
22 |
23 | @Override
24 | public boolean expected(final ChaincodeMessage msg) {
25 | orgMsg = msg;
26 | return msg.getType() == ChaincodeMessage.Type.GET_STATE;
27 | }
28 |
29 | @Override
30 | public List next() {
31 | final ByteString getPayload = ByteString.copyFromUtf8(val);
32 | final List list = new ArrayList<>();
33 | list.add(ChaincodeMessage.newBuilder()
34 | .setType(ChaincodeMessage.Type.RESPONSE)
35 | .setChannelId(orgMsg.getChannelId())
36 | .setTxid(orgMsg.getTxid())
37 | .setPayload(getPayload)
38 | .build());
39 | return list;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/InvokeChaincodeStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import com.google.protobuf.ByteString;
9 | import java.util.ArrayList;
10 | import java.util.List;
11 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
12 | import org.hyperledger.fabric.protos.peer.Response;
13 | import org.hyperledger.fabric.shim.Chaincode;
14 |
15 | /**
16 | * Simulates another chaincode invocation Waits for INVOKE_CHAINCODE Sends back RESPONSE message with chaincode response
17 | * inside
18 | */
19 | public final class InvokeChaincodeStep implements ScenarioStep {
20 | private ChaincodeMessage orgMsg;
21 |
22 | @Override
23 | public boolean expected(final ChaincodeMessage msg) {
24 | orgMsg = msg;
25 | return msg.getType() == ChaincodeMessage.Type.INVOKE_CHAINCODE;
26 | }
27 |
28 | /**
29 | * @return Chaincode response packed as payload inside COMPLETE message packed as payload inside RESPONSE message
30 | */
31 | @Override
32 | public List next() {
33 | final ByteString chaincodeResponse = Response.newBuilder()
34 | .setStatus(Chaincode.Response.Status.SUCCESS.getCode())
35 | .setMessage("OK")
36 | .build()
37 | .toByteString();
38 | final ByteString completePayload = ChaincodeMessage.newBuilder()
39 | .setType(ChaincodeMessage.Type.COMPLETED)
40 | .setChannelId(orgMsg.getChannelId())
41 | .setTxid(orgMsg.getTxid())
42 | .setPayload(chaincodeResponse)
43 | .build()
44 | .toByteString();
45 | final List list = new ArrayList<>();
46 | list.add(ChaincodeMessage.newBuilder()
47 | .setType(ChaincodeMessage.Type.RESPONSE)
48 | .setChannelId(orgMsg.getChannelId())
49 | .setTxid(orgMsg.getTxid())
50 | .setPayload(completePayload)
51 | .build());
52 | return list;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PurgeValueStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import java.util.ArrayList;
9 | import java.util.List;
10 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
11 |
12 | /**
13 | * Simulates purgePrivateData() invocation in chaincode Waits for PURGE_PRIVATE_DATA message from chaincode and sends
14 | * back response with empty payload
15 | */
16 | public final class PurgeValueStep implements ScenarioStep {
17 |
18 | private ChaincodeMessage orgMsg;
19 |
20 | @Override
21 | public boolean expected(final ChaincodeMessage msg) {
22 | orgMsg = msg;
23 | return msg.getType() == ChaincodeMessage.Type.PURGE_PRIVATE_DATA;
24 | }
25 |
26 | @Override
27 | public List next() {
28 | final List list = new ArrayList<>();
29 | list.add(ChaincodeMessage.newBuilder()
30 | .setType(ChaincodeMessage.Type.RESPONSE)
31 | .setChannelId(orgMsg.getChannelId())
32 | .setTxid(orgMsg.getTxid())
33 | .build());
34 | return list;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutValueStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.mock.peer;
8 |
9 | import com.google.protobuf.InvalidProtocolBufferException;
10 | import java.nio.charset.StandardCharsets;
11 | import java.util.ArrayList;
12 | import java.util.List;
13 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
14 | import org.hyperledger.fabric.protos.peer.PutState;
15 |
16 | /**
17 | * Simulates putState() invocation in chaincode Waits for PUT_STATE message from chaincode, including value and sends
18 | * back response with empty payload
19 | */
20 | public final class PutValueStep implements ScenarioStep {
21 | private ChaincodeMessage orgMsg;
22 | private final String val;
23 |
24 | /**
25 | * Initiate step
26 | *
27 | * @param val
28 | */
29 | public PutValueStep(final String val) {
30 | this.val = val;
31 | }
32 |
33 | /**
34 | * Check incoming message If message type is PUT_STATE and payload equal to passed in constructor
35 | *
36 | * @param msg message from chaincode
37 | * @return
38 | */
39 | @Override
40 | public boolean expected(final ChaincodeMessage msg) {
41 | orgMsg = msg;
42 | PutState putMsg = null;
43 | try {
44 | putMsg = PutState.parseFrom(msg.getPayload());
45 | } catch (final InvalidProtocolBufferException e) {
46 | return false;
47 | }
48 | return val.equals(new String(putMsg.getValue().toByteArray(), StandardCharsets.UTF_8))
49 | && msg.getType() == ChaincodeMessage.Type.PUT_STATE;
50 | }
51 |
52 | @Override
53 | public List next() {
54 | final List list = new ArrayList<>();
55 | list.add(ChaincodeMessage.newBuilder()
56 | .setType(ChaincodeMessage.Type.RESPONSE)
57 | .setChannelId(orgMsg.getChannelId())
58 | .setTxid(orgMsg.getTxid())
59 | .build());
60 | return list;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryCloseStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import java.util.ArrayList;
9 | import java.util.List;
10 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
11 |
12 | /**
13 | * Simulate last query (close) step. Happens after passing over all query result Waits for QUERY_STATE_CLOSE Sends back
14 | * response with empty payload
15 | */
16 | public final class QueryCloseStep implements ScenarioStep {
17 | private ChaincodeMessage orgMsg;
18 |
19 | @Override
20 | public boolean expected(final ChaincodeMessage msg) {
21 | orgMsg = msg;
22 | return msg.getType() == ChaincodeMessage.Type.QUERY_STATE_CLOSE;
23 | }
24 |
25 | /** @return RESPONSE message with empty payload */
26 | @Override
27 | public List next() {
28 | final List list = new ArrayList<>();
29 | list.add(ChaincodeMessage.newBuilder()
30 | .setType(ChaincodeMessage.Type.RESPONSE)
31 | .setChannelId(orgMsg.getChannelId())
32 | .setTxid(orgMsg.getTxid())
33 | .build());
34 | return list;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryNextStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.mock.peer;
7 |
8 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
9 |
10 | /**
11 | * Simulates requesting/receiving next set of results for query Waits for QUERY_STATE_NEXT Returns message that contains
12 | * list of results in form ("key" => "key Value")*
13 | */
14 | public final class QueryNextStep extends QueryResultStep {
15 |
16 | /**
17 | * Initiate step
18 | *
19 | * @param hasNext is response message QueryResponse hasMore field set
20 | * @param vals list of keys to generate ("key" => "key Value") pairs
21 | */
22 | public QueryNextStep(final boolean hasNext, final String... vals) {
23 | super(hasNext, vals);
24 | }
25 |
26 | @Override
27 | public boolean expected(final ChaincodeMessage msg) {
28 | super.orgMsg = msg;
29 | return msg.getType() == ChaincodeMessage.Type.QUERY_STATE_NEXT;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/RegisterStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.mock.peer;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
12 |
13 | /**
14 | * Simulates chaincode registration after start Waits for REGISTER message from chaincode Sends back pair of messages:
15 | * REGISTERED and READY
16 | */
17 | public final class RegisterStep implements ScenarioStep {
18 |
19 | private ChaincodeMessage orgMsg;
20 |
21 | @Override
22 | public boolean expected(final ChaincodeMessage msg) {
23 | orgMsg = msg;
24 | return msg.getType() == ChaincodeMessage.Type.REGISTER;
25 | }
26 |
27 | @Override
28 | public List next() {
29 | final List list = new ArrayList<>();
30 | list.add(ChaincodeMessage.newBuilder()
31 | .setType(ChaincodeMessage.Type.REGISTERED)
32 | .build());
33 | list.add(ChaincodeMessage.newBuilder()
34 | .setType(ChaincodeMessage.Type.READY)
35 | .build());
36 | return list;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ScenarioStep.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.mock.peer;
8 |
9 | import java.util.List;
10 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
11 |
12 | public interface ScenarioStep {
13 | /**
14 | * Validate incoming message from chaincode side
15 | *
16 | * @param msg message from chaincode
17 | * @return is incoming message was expected
18 | */
19 | boolean expected(ChaincodeMessage msg);
20 |
21 | /**
22 | * List of messages send from peer to chaincode as response(s)
23 | *
24 | * @return
25 | */
26 | List next();
27 | }
28 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/MessageUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | package org.hyperledger.fabric.shim.utils;
8 |
9 | import com.google.protobuf.ByteString;
10 | import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
11 | import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
12 |
13 | public final class MessageUtil {
14 |
15 | private MessageUtil() {}
16 |
17 | /**
18 | * Generate chaincode messages
19 | *
20 | * @param type
21 | * @param channelId
22 | * @param txId
23 | * @param payload
24 | * @param event
25 | * @return
26 | */
27 | public static ChaincodeMessage newEventMessage(
28 | final ChaincodeMessage.Type type,
29 | final String channelId,
30 | final String txId,
31 | final ByteString payload,
32 | final ChaincodeEvent event) {
33 | final ChaincodeMessage.Builder builder = ChaincodeMessage.newBuilder()
34 | .setType(type)
35 | .setChannelId(channelId)
36 | .setTxid(txId)
37 | .setPayload(payload);
38 | if (event != null) {
39 | builder.setChaincodeEvent(event);
40 | }
41 | return builder.build();
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/TimeoutUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.shim.utils;
7 |
8 | import java.util.concurrent.CountDownLatch;
9 | import java.util.concurrent.ExecutorService;
10 | import java.util.concurrent.Executors;
11 | import java.util.concurrent.TimeUnit;
12 | import java.util.concurrent.TimeoutException;
13 |
14 | /** Give possibility to stop runnable execution after specific time, if not ended */
15 | public final class TimeoutUtil {
16 |
17 | private TimeoutUtil() {}
18 |
19 | public static void runWithTimeout(final Runnable callable, final long timeout, final TimeUnit timeUnit)
20 | throws Exception {
21 | final ExecutorService executor = Executors.newSingleThreadExecutor();
22 | final CountDownLatch latch = new CountDownLatch(1);
23 | final Thread t = new Thread(() -> {
24 | try {
25 | callable.run();
26 | } finally {
27 | latch.countDown();
28 | }
29 | });
30 | try {
31 | executor.execute(t);
32 | if (!latch.await(timeout, timeUnit)) {
33 | throw new TimeoutException();
34 | }
35 | } finally {
36 | executor.shutdown();
37 | t.interrupt();
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/DefaultProviderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.traces.impl;
7 |
8 | import static org.assertj.core.api.Assertions.assertThat;
9 |
10 | import io.opentelemetry.api.trace.Span;
11 | import org.hyperledger.fabric.contract.ChaincodeStubNaiveImpl;
12 | import org.hyperledger.fabric.shim.ChaincodeStub;
13 | import org.junit.jupiter.api.Test;
14 |
15 | final class DefaultProviderTest {
16 |
17 | @Test
18 | void testDefaultProvider() {
19 | DefaultTracesProvider provider = new DefaultTracesProvider();
20 | ChaincodeStub stub = new ChaincodeStubNaiveImpl();
21 | Span span = provider.createSpan(stub);
22 | assertThat(span).isNull();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/TestSpanExporterProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 IBM All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | package org.hyperledger.fabric.traces.impl;
7 |
8 | import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties;
9 | import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider;
10 | import io.opentelemetry.sdk.common.CompletableResultCode;
11 | import io.opentelemetry.sdk.trace.data.SpanData;
12 | import io.opentelemetry.sdk.trace.export.SpanExporter;
13 | import java.util.ArrayList;
14 | import java.util.Collection;
15 | import java.util.List;
16 |
17 | public final class TestSpanExporterProvider implements ConfigurableSpanExporterProvider {
18 |
19 | public static final List SPANS = new ArrayList<>();
20 | public static final SpanExporter EXPORTER = new SpanExporter() {
21 |
22 | @Override
23 | public CompletableResultCode export(final Collection spans) {
24 | SPANS.addAll(spans);
25 | return CompletableResultCode.ofSuccess();
26 | }
27 |
28 | @Override
29 | public CompletableResultCode flush() {
30 | return CompletableResultCode.ofSuccess();
31 | }
32 |
33 | @Override
34 | public CompletableResultCode shutdown() {
35 | return CompletableResultCode.ofSuccess();
36 | }
37 | };
38 |
39 | @Override
40 | public SpanExporter createExporter(final ConfigProperties config) {
41 | return EXPORTER;
42 | }
43 |
44 | @Override
45 | public String getName() {
46 | return "TestSpanExporterProvider";
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider:
--------------------------------------------------------------------------------
1 | org.hyperledger.fabric.traces.impl.TestSpanExporterProvider
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/resources/ca.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICSTCCAe+gAwIBAgIQZ97pJjwOf+/15wXlaQhswTAKBggqhkjOPQQDAjB2MQsw
3 | CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy
4 | YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz
5 | Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0xODA4MjExNDEyMzhaFw0yODA4MTgxNDEy
6 | MzhaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH
7 | Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmV4YW1wbGUuY29tMR8wHQYD
8 | VQQDExZ0bHNjYS5vcmcxLmV4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0D
9 | AQcDQgAEgClmvqBKTmruqxNluLAL82p/06D58M6sg/5Qa6epl4/pjc7xv2KpDqIl
10 | ONITgmKzR8VslccRoOpV97PRQljH8qNfMF0wDgYDVR0PAQH/BAQDAgGmMA8GA1Ud
11 | JQQIMAYGBFUdJQAwDwYDVR0TAQH/BAUwAwEB/zApBgNVHQ4EIgQgmGlEDIWlK8zX
12 | Hz3tNOuC1jE58I8yNMaaIiz2fLaopMYwCgYIKoZIzj0EAwIDSAAwRQIhAPSWUrs3
13 | n0Lr6gfaYIxxfEopUm8/J8OVL8cdXPWFnkBbAiBFCCbgtxQRdvPUAHfJLtgOTNwM
14 | MxxvehamsJdpqCUsNA==
15 | -----END CERTIFICATE-----
16 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/resources/client.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICOjCCAeGgAwIBAgIQCSag4gNL7SdBHpN3BtqTeDAKBggqhkjOPQQDAjB2MQsw
3 | CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy
4 | YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz
5 | Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0xODA4MjExNDEyMzhaFw0yODA4MTgxNDEy
6 | MzhaMFsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH
7 | Ew1TYW4gRnJhbmNpc2NvMR8wHQYDVQQDDBZVc2VyMUBvcmcxLmV4YW1wbGUuY29t
8 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzh25F4EJhycT7wKoLRYZt/1rgsaW
9 | 4yIPb+QnDg17jX/fhKSnFRcWE4U0OOmwESKc0MniMWxrdzUIYh+9W0DHPKNsMGow
10 | DgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAM
11 | BgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIJhpRAyFpSvM1x897TTrgtYxOfCPMjTG
12 | miIs9ny2qKTGMAoGCCqGSM49BAMCA0cAMEQCICG6fm4B9BKFfWyLDOwpBOk/KRrI
13 | MqJdlNIFI6d6924wAiB4drv3HQCleeVOg2z9Mm4xflcgl78BsYduECh1+qcEqg==
14 | -----END CERTIFICATE-----
15 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/resources/client.crt.enc:
--------------------------------------------------------------------------------
1 | LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNPakNDQWVHZ0F3SUJBZ0lRQ1NhZzRnTkw3U2RCSHBOM0J0cVRlREFLQmdncWhrak9QUVFEQWpCMk1Rc3cKQ1FZRFZRUUdFd0pWVXpFVE1CRUdBMVVFQ0JNS1EyRnNhV1p2Y201cFlURVdNQlFHQTFVRUJ4TU5VMkZ1SUVaeQpZVzVqYVhOamJ6RVpNQmNHQTFVRUNoTVFiM0puTVM1bGVHRnRjR3hsTG1OdmJURWZNQjBHQTFVRUF4TVdkR3h6ClkyRXViM0puTVM1bGVHRnRjR3hsTG1OdmJUQWVGdzB4T0RBNE1qRXhOREV5TXpoYUZ3MHlPREE0TVRneE5ERXkKTXpoYU1Gc3hDekFKQmdOVkJBWVRBbFZUTVJNd0VRWURWUVFJRXdwRFlXeHBabTl5Ym1saE1SWXdGQVlEVlFRSApFdzFUWVc0Z1JuSmhibU5wYzJOdk1SOHdIUVlEVlFRRERCWlZjMlZ5TVVCdmNtY3hMbVY0WVcxd2JHVXVZMjl0Ck1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXpoMjVGNEVKaHljVDd3S29MUlladC8xcmdzYVcKNHlJUGIrUW5EZzE3algvZmhLU25GUmNXRTRVME9PbXdFU0tjME1uaU1XeHJkelVJWWgrOVcwREhQS05zTUdvdwpEZ1lEVlIwUEFRSC9CQVFEQWdXZ01CMEdBMVVkSlFRV01CUUdDQ3NHQVFVRkJ3TUJCZ2dyQmdFRkJRY0RBakFNCkJnTlZIUk1CQWY4RUFqQUFNQ3NHQTFVZEl3UWtNQ0tBSUpocFJBeUZwU3ZNMXg4OTdUVHJndFl4T2ZDUE1qVEcKbWlJczlueTJxS1RHTUFvR0NDcUdTTTQ5QkFNQ0EwY0FNRVFDSUNHNmZtNEI5QktGZld5TERPd3BCT2svS1JySQpNcUpkbE5JRkk2ZDY5MjR3QWlCNGRydjNIUUNsZWVWT2cyejlNbTR4ZmxjZ2w3OEJzWWR1RUNoMStxY0VxZz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/resources/client.key:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgwCm9EFOOwAugpN3s
3 | leXGaKAzrr1E/0PJbqh8p2/MqnyhRANCAATOHbkXgQmHJxPvAqgtFhm3/WuCxpbj
4 | Ig9v5CcODXuNf9+EpKcVFxYThTQ46bARIpzQyeIxbGt3NQhiH71bQMc8
5 | -----END PRIVATE KEY-----
6 |
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/resources/client.key.enc:
--------------------------------------------------------------------------------
1 | LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JR0hBZ0VBTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEJHMHdhd0lCQVFRZ3dDbTlFRk9Pd0F1Z3BOM3MKbGVYR2FLQXpycjFFLzBQSmJxaDhwMi9NcW55aFJBTkNBQVRPSGJrWGdRbUhKeFB2QXFndEZobTMvV3VDeHBiagpJZzl2NUNjT0RYdU5mOStFcEtjVkZ4WVRoVFE0NmJBUklwelF5ZUl4Ykd0M05RaGlINzFiUU1jOAotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==
--------------------------------------------------------------------------------
/fabric-chaincode-shim/src/test/resources/client.key.password-protected:
--------------------------------------------------------------------------------
1 | -----BEGIN ENCRYPTED PRIVATE KEY-----
2 | MIGxMBwGCiqGSIb3DQEMAQMwDgQIfzm0IqTm+rACAggABIGQDY1vpaSD+KDuVRyT
3 | Gi35536iOYUuVoz01ktV3YCDv03Pm5+8xZ1JXXW8lDM3JP/TcKbocRRk63y/R7O2
4 | dB9kcyV7/gYtYH0B3TMk1/x1WtfHL8JnYRFHQ/OuhYjJ6O04B4aY2waeYByzsIsI
5 | YhNVZq5fZ7/bjsy8b54o57WD4DDHH3uRysbv8I5TaDVyJMJq
6 | -----END ENCRYPTED PRIVATE KEY-----
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperledger/fabric-chaincode-java/826f0779d1d8dc0a41b042f3346563bc8094c050/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/release_notes/v1.3.0.txt:
--------------------------------------------------------------------------------
1 | v1.3.0 September 25, 2018
2 | -------------------------
3 |
4 | Release Notes
5 | -------------
6 | Initial release of Java chaincode support.
7 |
8 | baseimage version 0.4.12
9 | Java version 1.8.0_sr5fp21
10 |
11 | Known Vulnerabilities
12 | ---------------------
13 | none
14 |
15 | Resolved Vulnerabilities
16 | ------------------------
17 | none
18 |
19 | Known Issues & Workarounds
20 | --------------------------
21 | none
22 |
23 | Change Log
24 | ----------
25 | https://github.com/hyperledger/fabric-chaincode-java/blob/master/CHANGELOG.md#v130-rc1
26 |
--------------------------------------------------------------------------------
/release_notes/v1.4.0.txt:
--------------------------------------------------------------------------------
1 | v1.4.0-rc1 December 11, 2018
2 | ----------------------------
3 |
4 | Release Notes
5 | -------------
6 | Java chaincode v1.4.0 adds parity with Go chaincode:
7 | FAB-12329 State-based endorsement support
8 | FAB-12328 Query result pagination support
9 |
10 | Increase test coverage, including integration tests based on
11 | testcontainers framework.
12 |
13 | baseimage version: 0.4.14
14 | Java version: openjdk version "1.8.0_181"
15 |
16 | Known Vulnerabilities
17 | ---------------------
18 | none
19 |
20 | Resolved Vulnerabilities
21 | ------------------------
22 | none
23 |
24 | Known Issues & Workarounds
25 | --------------------------
26 | none
27 |
28 | Change Log
29 | ----------
30 | https://github.com/hyperledger/fabric-chaincode-java/blob/master/CHANGELOG.md#v140-rc1
31 |
--------------------------------------------------------------------------------
/release_notes/v2.0.0-alpha.txt:
--------------------------------------------------------------------------------
1 | v2.0.0-alpha April 9, 2019
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | Java chaincode v2.0.0-alpha includes multiple improvements:
7 |
8 | Javaenv docker images is now based on Alpine to reduce the size.
9 | Integration tests have been improved.
10 | Java chaincode extra validation during start.
11 | Added support for maven projects.
12 |
13 | openjdk:8-slim is now used instead of baseimage for the basis of javaenv Docker image.
14 | Java version: openjdk version "1.8.0_181"
15 |
16 | Known Vulnerabilities
17 | ---------------------
18 | none
19 |
20 | Resolved Vulnerabilities
21 | ------------------------
22 | none
23 |
24 | Known Issues & Workarounds
25 | --------------------------
26 | none
27 |
28 | Change Log
29 | ----------
30 | https://github.com/hyperledger/fabric-chaincode-java/blob/master/CHANGELOG.md#v200-alpha
31 |
--------------------------------------------------------------------------------
/release_notes/v2.0.0-beta.txt:
--------------------------------------------------------------------------------
1 | v2.0.0-beta December 12, 2019
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | Java chaincode v2.0.0-alpha includes multiple improvements:
7 |
8 | Javaenv docker images is now based on Alpine to reduce the size.
9 | Integration tests have been improved.
10 | Java chaincode extra validation during start.
11 | Added support for maven projects.
12 |
13 | adoptopenjdk/openjdk11:jdk-11.0.4_11-alpine is now used instead of baseimage for the basis of javaenv Docker image.
14 |
15 | Known Vulnerabilities
16 | ---------------------
17 | none
18 |
19 | Resolved Vulnerabilities
20 | ------------------------
21 | none
22 |
23 | Known Issues & Workarounds
24 | --------------------------
25 | none
26 |
27 | Change Log
28 | ----------
29 | https://github.com/hyperledger/fabric-chaincode-java/blob/master/CHANGELOG.md#v200-beta
30 |
--------------------------------------------------------------------------------
/release_notes/v2.0.0.txt:
--------------------------------------------------------------------------------
1 | v2.0.0 20 January 2020
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | Java chaincode v2.0.0 includes multiple improvements:
7 |
8 | Javaenv docker images is now based on Alpine to reduce the size.
9 | Integration tests have been improved.
10 | Java chaincode extra validation during start.
11 | Added support for maven projects.
12 |
13 | adoptopenjdk/openjdk11:jdk-11.0.4_11-alpine is now used instead of baseimage for the basis of javaenv Docker image.
14 |
15 | Known Vulnerabilities
16 | ---------------------
17 | none
18 |
19 | Resolved Vulnerabilities
20 | ------------------------
21 | none
22 |
23 | Known Issues & Workarounds
24 | --------------------------
25 | none
26 |
27 | Change Log
28 | ----------
29 | https://github.com/hyperledger/fabric-chaincode-java/blob/master/CHANGELOG.md#v200
--------------------------------------------------------------------------------
/release_notes/v2.0.1.txt:
--------------------------------------------------------------------------------
1 | v2.0.1 4 March 2020
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 |
7 | - Provides access to the localmspid
8 |
9 | adoptopenjdk/openjdk11:jdk-11.0.4_11-alpine is now used for the basis of javaenv Docker image.
10 |
11 | Known Vulnerabilities
12 | ---------------------
13 | none
14 |
15 | Resolved Vulnerabilities
16 | ------------------------
17 | none
18 |
19 | Known Issues & Workarounds
20 | --------------------------
21 | none
22 |
23 | Change Log
24 | ----------
25 | https://github.com/hyperledger/fabric-chaincode-java/blob/master/CHANGELOG.md#v201
--------------------------------------------------------------------------------
/release_notes/v2.1.0.txt:
--------------------------------------------------------------------------------
1 | v2.1.0 4 March 2020
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | There are minimal changes between v2.0.0 and v2.1.0, please see the change log for a full list of updates.
7 |
8 | The release-2.0 branch has been renamed to release-2.x; the v2.1.0 release supercedes v2.0.0.
9 | The release-1.4 branch is currently LTS, please see the proposed Fabric LTS strategy for more information:
10 | https://github.com/hyperledger/fabric-rfcs/pull/23
11 |
12 | Known Vulnerabilities
13 | ---------------------
14 | none
15 |
16 | Resolved Vulnerabilities
17 | ------------------------
18 | none
19 |
20 | Known Issues & Workarounds
21 | --------------------------
22 | none
23 |
24 | Change Log
25 | ----------
26 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v210
27 |
--------------------------------------------------------------------------------
/release_notes/v2.1.1.txt:
--------------------------------------------------------------------------------
1 | v2.1.1 18 May 2020
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | This is a bug fix release with a fix for a performance issue when using query.
7 |
8 | See this JIRA for more information https://jira.hyperledger.org/browse/FABCJ-285
9 |
10 | The release-2.0 branch has been renamed to release-2.x; the v2.1.0 release supercedes v2.0.0.
11 | The release-1.4 branch is currently LTS, please see the proposed Fabric LTS strategy for more information:
12 | https://github.com/hyperledger/fabric-rfcs/pull/23
13 |
14 | Known Vulnerabilities
15 | ---------------------
16 | none
17 |
18 | Resolved Vulnerabilities
19 | ------------------------
20 | none
21 |
22 | Known Issues & Workarounds
23 | --------------------------
24 | none
25 |
26 | Change Log
27 | ----------
28 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v211
29 |
--------------------------------------------------------------------------------
/release_notes/v2.2.0.txt:
--------------------------------------------------------------------------------
1 | v2.2.0
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | This v2.2.0 Release is the LTS version of the fabric-chaincode-java
7 |
8 | Known Vulnerabilities
9 | ---------------------
10 | none
11 |
12 | Resolved Vulnerabilities
13 | ------------------------
14 | none
15 |
16 | Known Issues & Workarounds
17 | --------------------------
18 | none
19 |
20 | Change Log
21 | ----------
22 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v220
23 |
--------------------------------------------------------------------------------
/release_notes/v2.2.1.txt:
--------------------------------------------------------------------------------
1 | v2.2.1
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | This v2.2.1 Release is the LTS version of the fabric-chaincode-java
7 |
8 | Known Vulnerabilities
9 | ---------------------
10 | none
11 |
12 | Resolved Vulnerabilities
13 | ------------------------
14 | none
15 |
16 | Known Issues & Workarounds
17 | --------------------------
18 | none
19 |
20 | Change Log
21 | ----------
22 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v221
--------------------------------------------------------------------------------
/release_notes/v2.3.0.txt:
--------------------------------------------------------------------------------
1 | v2.3.0
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | This v2.3.0 Release is the LTS version of the fabric-chaincode-java
7 |
8 | Known Vulnerabilities
9 | ---------------------
10 | none
11 |
12 | Resolved Vulnerabilities
13 | ------------------------
14 | none
15 |
16 | Known Issues & Workarounds
17 | --------------------------
18 | none
19 |
20 | Change Log
21 | ----------
22 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v221
--------------------------------------------------------------------------------
/release_notes/v2.3.1.txt:
--------------------------------------------------------------------------------
1 | v2.3.1
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | This v2.3.1 Release is a bug fix release of the main branch.
7 |
8 | Known Vulnerabilities
9 | ---------------------
10 | none
11 |
12 | Resolved Vulnerabilities
13 | ------------------------
14 | none
15 |
16 | Known Issues & Workarounds
17 | --------------------------
18 | none
19 |
20 | Change Log
21 | ----------
22 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v231
--------------------------------------------------------------------------------
/release_notes/v2.4.0-beta.txt:
--------------------------------------------------------------------------------
1 | v2.4.0-beta
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | This v2.4.0-beta Release is a bug fix release of the main branch.
7 |
8 | Known Vulnerabilities
9 | ---------------------
10 | none
11 |
12 | Resolved Vulnerabilities
13 | ------------------------
14 | none
15 |
16 | Known Issues & Workarounds
17 | --------------------------
18 | none
19 |
20 | Change Log
21 | ----------
22 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v240
23 |
--------------------------------------------------------------------------------
/release_notes/v2.4.0.txt:
--------------------------------------------------------------------------------
1 | v2.4.0
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | This v2.4.0 Release is to support the Fabric v2.4 release.
7 |
8 | Known Vulnerabilities
9 | ---------------------
10 | none
11 |
12 | Resolved Vulnerabilities
13 | ------------------------
14 | none
15 |
16 | Known Issues & Workarounds
17 | --------------------------
18 | none
19 |
20 | Change Log
21 | ----------
22 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v240
23 |
--------------------------------------------------------------------------------
/release_notes/v2.4.1.txt:
--------------------------------------------------------------------------------
1 | v2.4.1
2 | --------------------------
3 |
4 | Release Notes
5 | -------------
6 | This release improves support for the chaincode-as-a-service feature. It removes the need to write custom 'bootstrap' scripts
7 | See the `examples/fabric-contract-examples-as-service`
8 |
9 | Known Vulnerabilities
10 | ---------------------
11 | none
12 |
13 | Resolved Vulnerabilities
14 | ------------------------
15 | none
16 |
17 | Known Issues & Workarounds
18 | --------------------------
19 | none
20 |
21 | Change Log
22 | ----------
23 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v241
24 |
--------------------------------------------------------------------------------
/release_notes/v2.5.0.txt:
--------------------------------------------------------------------------------
1 | v2.5.0 LTS
2 | ----------
3 |
4 | Release Notes
5 | -------------
6 | This is the LTS Release of of the v2.5 Fabric Chaincode Java. It replaces the previous v2.2 LTS.
7 |
8 | - the default `JavaEnv` docker image has been moved to use the Eclipse Temurin Java 11 JDK
9 | - the PurgePrivateData feature is exposed via a new `PurgePrivateData` API
10 |
11 |
12 | Known Vulnerabilities
13 | ---------------------
14 | none
15 |
16 | Resolved Vulnerabilities
17 | ------------------------
18 | none
19 |
20 | Known Issues & Workarounds
21 | --------------------------
22 | none
23 |
24 | Change Log
25 | ----------
26 | https://github.com/hyperledger/fabric-chaincode-java/blob/release-2.x/CHANGELOG.md#v250
27 |
--------------------------------------------------------------------------------
/scripts/changelog.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | #
3 | # Copyright IBM Corp. All Rights Reserved.
4 | #
5 | # SPDX-License-Identifier: Apache-2.0
6 | #
7 | set -ev
8 |
9 | PREVIOUS_TAG=$1
10 | NEW_VERSION=$2
11 |
12 | : ${PREVIOUS_TAG:?}
13 | : ${NEW_VERSION:?}
14 |
15 | echo "## ${NEW_VERSION}" >> CHANGELOG.new
16 | echo "$(date)" >> CHANGELOG.new
17 | echo "" >> CHANGELOG.new
18 | git log ${PREVIOUS_TAG}..HEAD --oneline | grep -v Merge | sed -e "s/\[\{0,1\}\(FAB[^0-9]*-[0-9]*\)\]\{0,1\}/\[\1\](https:\/\/jira.hyperledger.org\/browse\/\1\)/" -e "s/\([0-9|a-z]*\)/* \[\1\](https:\/\/github.com\/hyperledger\/fabric-chaincode-java\/commit\/\1)/" >> CHANGELOG.new
19 | echo "" >> CHANGELOG.new
20 | cat CHANGELOG.md >> CHANGELOG.new
21 | mv -f CHANGELOG.new CHANGELOG.md
22 |
23 |
--------------------------------------------------------------------------------
/scripts/gittag.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # SPDX-License-Identifier: Apache-2.0
4 | #
5 |
6 | # Exit on first error, print all commands.
7 | set -e
8 | set -o pipefail
9 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
10 |
11 | # release name
12 | RELEASE=release-1.4
13 |
14 | function abort {
15 | echo "!! Exiting shell script"
16 | echo "!!" "$1"
17 | exit -1
18 | }
19 |
20 | # Run printVersionName task in the root directory, grab the first line and remove anything after the version number
21 | VERSION=$(cd ../ && ./gradlew -q printVersionName | head -n 1 | cut -d'-' -f1)
22 |
23 | echo New version string will be v${VERSION}
24 |
25 | # do the release notes for this new version exist?
26 | if [[ -f "${DIR}/release_notes/v${VERSION}.txt" ]]; then
27 | echo "Release notes exist, hope they make sense!"
28 | else
29 | abort "No releases notes under the file ${DIR}/release_notes/v${NEW_VERSION}.txt exist";
30 | fi
31 |
32 | git checkout "${RELEASE}"
33 | git pull
34 | git tag -a "v${VERSION}" `git log -n 1 --pretty=oneline | head -c7` -F release_notes/"v${VERSION}".txt
35 | git push origin v${VERSION} HEAD:refs/heads/${RELEASE}
--------------------------------------------------------------------------------
/scripts/verify-commit.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -ue
2 |
3 | #
4 | # SPDX-License-Identifier: Apache-2.0
5 | ##############################################################################
6 | # Copyright (c) 2018 IBM Corporation, The Linux Foundation and others.
7 | #
8 | # All rights reserved. This program and the accompanying materials
9 | # are made available under the terms of the Apache License 2.0
10 | # which accompanies this distribution, and is available at
11 | # https://www.apache.org/licenses/LICENSE-2.0
12 | ##############################################################################
13 |
14 | # This script makes several basic commit message validations.
15 | # This is with the purpose of keeping up with the aesthetics of our code.
16 | # Verify if the commit message contains JIRA URLs.
17 | # its-jira pluggin attempts to process jira links and breaks.
18 |
19 | set +ue # Temporarily ignore any errors
20 |
21 | set -o pipefail
22 | echo "----> verify-commit.sh"
23 |
24 | if git rev-list --format=%B --max-count=1 HEAD | grep -io 'http[s]*://jira\..*' > /dev/null ; then
25 | echo 'Error: Remove JIRA URLs from commit message'
26 | echo 'Add jira references as: Issue: -, instead of URLs'
27 | exit 1
28 | fi
29 |
30 | # Check for trailing white-space (tab or spaces) in any files that were changed
31 | #commit_files=$(git diff-tree --name-only -r HEAD~2..HEAD)
32 | commit_files=$(find ./fabric-chaincode-shim/src -name *.java)
33 |
34 | found_trailing=false
35 | for filename in $commit_files; do
36 | if [[ $(file -b $filename) == "ASCII text"* ]]; then
37 | if egrep -q "\s$" $filename; then
38 | found_trailing=true
39 | echo "Error: Trailing white spaces found in file: $filename"
40 | fi
41 | fi
42 | done
43 |
44 | #if $found_trailing; then
45 | # echo "#### filename:line-num:line ####"
46 | # egrep -n "\s$" $commit_files
47 | # exit 1
48 | #fi
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright IBM Corp. 2017 All Rights Reserved.
3 | *
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 | rootProject.name = 'fabric-chaincode-java'
7 |
8 | include 'fabric-chaincode-shim'
9 | include 'fabric-chaincode-docker'
10 | include 'fabric-chaincode-integration-test'
11 |
--------------------------------------------------------------------------------