diff --git a/app/platform/fabric/e2e-test/.env b/app/platform/fabric/e2e-test/.env index 2fa228552..cf419615f 100644 --- a/app/platform/fabric/e2e-test/.env +++ b/app/platform/fabric/e2e-test/.env @@ -32,4 +32,6 @@ KAFKA_MESSAGE_MAX_BYTES=1000012 B KAFKA_REPLICA_FETCH_MAX_BYTES=1048576 B KAFKA_REPLICA_FETCH_RESPONSE_MAX_BYTES=10485760 B IMAGE_TAG=latest -FABRIC_CA_SERVER_EXAMPLE_TLS_KEYFILE=/var/hyperledger/fabric-ca-server-config/sk \ No newline at end of file +FABRIC_CA_SERVER_EXAMPLE_TLS_KEYFILE=/var/hyperledger/fabric-ca-server-config/sk +SYS_CHANNEL=byfn-sys-channel + diff --git a/app/platform/fabric/e2e-test/explorer.feature b/app/platform/fabric/e2e-test/explorer.feature index 49a2f47cb..81c44cfe7 100644 --- a/app/platform/fabric/e2e-test/explorer.feature +++ b/app/platform/fabric/e2e-test/explorer.feature @@ -36,7 +36,7 @@ Feature: Bootstrapping Hyperledger Explorer # @doNotDecompose Scenario Outline: [] Bring up explorer with fabric-samples/ and send requests to the basic REST API functions successfully # Start a fabric network by using fabric-samples/ - Given I start + Given I start orderer network of type # Need to specify which profiles should be in use before starting Explorer Given the NETWORK_PROFILE environment variable is When I start explorer @@ -105,9 +105,10 @@ Scenario Outline: [] Bring up explorer with fabric-samples/ - ## Balance transfer A sample Node.js app to demonstrate **__fabric-client__** & **__fabric-ca-client__** Node.js SDK APIs diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app.js index 54c4eb81f..c257e9976 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app.js @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 IBM All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/create-channel.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/create-channel.js index 54c66b04d..f1b2f7b27 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/create-channel.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/create-channel.js @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 IBM All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/helper.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/helper.js index 2be9e3633..ef18f0d28 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/helper.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/helper.js @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 IBM All Rights Reserved. * @@ -94,10 +90,7 @@ var getRegisteredUser = async function(username, userOrg, isJson) { adminUserObj ); logger.debug('Successfully got the secret for user %s', username); - user = await client.setUserContext({ - username: username, - password: secret - }); + user = await client.setUserContext({ username: username, password: secret }); logger.debug( 'Successfully enrolled username %s and setUserContext on the client object', username diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/install-chaincode.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/install-chaincode.js index 7859d65fb..96a7098ea 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/install-chaincode.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/install-chaincode.js @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 IBM All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/instantiate-chaincode.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/instantiate-chaincode.js index 8f80dd35a..772ac7476 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/instantiate-chaincode.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/instantiate-chaincode.js @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 IBM All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/invoke-transaction.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/invoke-transaction.js index fc674825f..5ac8a049a 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/invoke-transaction.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/invoke-transaction.js @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 IBM All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/join-channel.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/join-channel.js index 8744a46c7..3c72ffd85 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/join-channel.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/join-channel.js @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 IBM All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/query.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/query.js index b07b31af0..9c8eb2177 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/query.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/app/query.js @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 IBM All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/base.yaml b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/base.yaml index 875dc4a9e..35027d7ff 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/base.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/base.yaml @@ -12,7 +12,7 @@ services: # the following setting starts chaincode containers on the same # bridge network as the peers # https://docs.docker.com/compose/networking/ - - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${CORE_PEER_NETWORKID}_behave + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=artifacts_default - FABRIC_LOGGING_SPEC=DEBUG - CORE_PEER_GOSSIP_USELEADERELECTION=true - CORE_PEER_GOSSIP_ORGLEADER=false diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/docker-compose-explorer.yaml b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/docker-compose-explorer.yaml new file mode 100644 index 000000000..65b59e4d8 --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/docker-compose-explorer.yaml @@ -0,0 +1,136 @@ +# +# Copyright IBM Corp. All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +version: '2' + +networks: + behave: + +services: + + ca.org1.example.com: + extends: + file: docker-compose.yaml + service: ca.org1.example.com + container_name: ca_peerorg1 + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + ca.org2.example.com: + extends: + file: docker-compose.yaml + service: ca.org2.example.com + container_name: ca_peerorg2 + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + orderer.example.com: + extends: + file: docker-compose.yaml + service: orderer.example.com + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + peer0.org1.example.com: + container_name: peer0.org1.example.com + extends: + file: base.yaml + service: peer-base + environment: + - CORE_PEER_ID=peer0.org1.example.com + - CORE_PEER_LOCALMSPID=Org1MSP + - CORE_PEER_ADDRESS=peer0.org1.example.com:7051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org1.example.com:7051 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051 + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${CORE_PEER_NETWORKID}_behave + ports: + - 7051:7051 + - 7053:7053 + volumes: + - ./channel/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/crypto/peer + depends_on: + - orderer.example.com + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + peer1.org1.example.com: + container_name: peer1.org1.example.com + extends: + file: base.yaml + service: peer-base + environment: + - CORE_PEER_ID=peer1.org1.example.com + - CORE_PEER_LOCALMSPID=Org1MSP + - CORE_PEER_ADDRESS=peer1.org1.example.com:7051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org1.example.com:7051 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org1.example.com:7051 + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${CORE_PEER_NETWORKID}_behave + ports: + - 7056:7051 + - 7058:7053 + volumes: + - ./channel/crypto-config/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/:/etc/hyperledger/crypto/peer + depends_on: + - orderer.example.com + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + peer0.org2.example.com: + container_name: peer0.org2.example.com + extends: + file: base.yaml + service: peer-base + environment: + - CORE_PEER_ID=peer0.org2.example.com + - CORE_PEER_LOCALMSPID=Org2MSP + - CORE_PEER_ADDRESS=peer0.org2.example.com:7051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org2.example.com:7051 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org2.example.com:7051 + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${CORE_PEER_NETWORKID}_behave + ports: + - 8051:7051 + - 8053:7053 + volumes: + - ./channel/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/:/etc/hyperledger/crypto/peer + depends_on: + - orderer.example.com + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + peer1.org2.example.com: + container_name: peer1.org2.example.com + extends: + file: base.yaml + service: peer-base + environment: + - CORE_PEER_ID=peer1.org2.example.com + - CORE_PEER_LOCALMSPID=Org2MSP + - CORE_PEER_ADDRESS=peer1.org2.example.com:7051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org2.example.com:7051 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org2.example.com:7051 + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${CORE_PEER_NETWORKID}_behave + ports: + - 8056:7051 + - 8058:7053 + volumes: + - ./channel/crypto-config/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/:/etc/hyperledger/crypto/peer + depends_on: + - orderer.example.com + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/docker-compose.yaml b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/docker-compose.yaml index d73bf0c8d..6fd88df2f 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/docker-compose.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/docker-compose.yaml @@ -5,9 +5,6 @@ # version: '2' -networks: - behave: - services: ca.org1.example.com: @@ -25,11 +22,7 @@ services: command: sh -c 'fabric-ca-server start -b admin:adminpw -d' volumes: - ./channel/crypto-config/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config - container_name: ca_peerorg1 - networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} + container_name: ca_peerOrg1 ca.org2.example.com: image: hyperledger/fabric-ca @@ -46,11 +39,7 @@ services: command: sh -c 'fabric-ca-server start -b admin:adminpw -d' volumes: - ./channel/crypto-config/peerOrganizations/org2.example.com/ca/:/etc/hyperledger/fabric-ca-server-config - container_name: ca_peerorg2 - networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} + container_name: ca_peerOrg2 orderer.example.com: container_name: orderer.example.com @@ -75,10 +64,6 @@ services: - ./channel/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/:/etc/hyperledger/crypto/orderer - ./channel/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/crypto/peerOrg1 - ./channel/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/:/etc/hyperledger/crypto/peerOrg2 - networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} peer0.org1.example.com: container_name: peer0.org1.example.com @@ -89,7 +74,7 @@ services: - CORE_PEER_ID=peer0.org1.example.com - CORE_PEER_LOCALMSPID=Org1MSP - CORE_PEER_ADDRESS=peer0.org1.example.com:7051 - - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org1.example.com:7051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org1.example.com:7051 - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051 ports: - 7051:7051 @@ -98,10 +83,6 @@ services: - ./channel/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/crypto/peer depends_on: - orderer.example.com - networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} peer1.org1.example.com: container_name: peer1.org1.example.com @@ -112,7 +93,7 @@ services: - CORE_PEER_ID=peer1.org1.example.com - CORE_PEER_LOCALMSPID=Org1MSP - CORE_PEER_ADDRESS=peer1.org1.example.com:7051 - - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org1.example.com:7051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org1.example.com:7051 - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org1.example.com:7051 ports: - 7056:7051 @@ -121,10 +102,6 @@ services: - ./channel/crypto-config/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/:/etc/hyperledger/crypto/peer depends_on: - orderer.example.com - networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} peer0.org2.example.com: container_name: peer0.org2.example.com @@ -135,7 +112,7 @@ services: - CORE_PEER_ID=peer0.org2.example.com - CORE_PEER_LOCALMSPID=Org2MSP - CORE_PEER_ADDRESS=peer0.org2.example.com:7051 - - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org2.example.com:7051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org2.example.com:7051 - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org2.example.com:7051 ports: - 8051:7051 @@ -144,10 +121,6 @@ services: - ./channel/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/:/etc/hyperledger/crypto/peer depends_on: - orderer.example.com - networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} peer1.org2.example.com: container_name: peer1.org2.example.com @@ -158,7 +131,7 @@ services: - CORE_PEER_ID=peer1.org2.example.com - CORE_PEER_LOCALMSPID=Org2MSP - CORE_PEER_ADDRESS=peer1.org2.example.com:7051 - - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org2.example.com:7051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org2.example.com:7051 - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org2.example.com:7051 ports: - 8056:7051 @@ -167,7 +140,3 @@ services: - ./channel/crypto-config/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/:/etc/hyperledger/crypto/peer depends_on: - orderer.example.com - networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/network-config-aws.yaml b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/network-config-aws.yaml index a38b33be4..87912d719 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/network-config-aws.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/network-config-aws.yaml @@ -1,5 +1,4 @@ --- -# SPDX-License-Identifier: Apache-2.0 # # The network connection profile provides client applications the information about the target # blockchain network that are necessary for the applications to interact with it. These are all diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/network-config.yaml b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/network-config.yaml index 74441ad1c..1d6d9efee 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/network-config.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/network-config.yaml @@ -1,5 +1,4 @@ --- -# SPDX-License-Identifier: Apache-2.0 # # The network connection profile provides client applications the information about the target # blockchain network that are necessary for the applications to interact with it. These are all diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/org1.yaml b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/org1.yaml index 7ae336c22..9f80b2a9c 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/org1.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/org1.yaml @@ -1,5 +1,4 @@ --- -# SPDX-License-Identifier: Apache-2.0 # # The network connection profile provides client applications the information about the target # blockchain network that are necessary for the applications to interact with it. These are all diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/org2.yaml b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/org2.yaml index fb98206ad..6edc731cf 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/org2.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/org2.yaml @@ -1,5 +1,4 @@ --- -# SPDX-License-Identifier: Apache-2.0 # # The network connection profile provides client applications the information about the target # blockchain network that are necessary for the applications to interact with it. These are all diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/src/github.com/example_cc/go/example_cc.go b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/src/github.com/example_cc/go/example_cc.go index d01bba477..06fd76b96 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/src/github.com/example_cc/go/example_cc.go +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/artifacts/src/github.com/example_cc/go/example_cc.go @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /* Copyright IBM Corp. 2016 All Rights Reserved. diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/config.js b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/config.js index 8b8bc8e7f..5364a778b 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/config.js +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/config.js @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: Apache-2.0 var util = require('util'); var path = require('path'); var hfc = require('fabric-client'); diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/runApp.sh b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/runApp.sh index e1e7d3028..03885ae76 100755 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/runApp.sh +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/runApp.sh @@ -31,7 +31,7 @@ function restartNetwork() { echo #teardown the network and clean the containers and intermediate images - docker-compose -f ./artifacts/docker-compose.yaml down + docker-compose -f ./artifacts/docker-compose-explorer.yaml down dkcl dkrm @@ -39,7 +39,7 @@ function restartNetwork() { rm -rf ./fabric-client-kv-org* #Start the network - docker-compose -f ./artifacts/docker-compose.yaml up -d + docker-compose -f ./artifacts/docker-compose-explorer.yaml up -d echo } diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/testAPIs.sh b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/testAPIs.sh index 6526f3f6f..ad503b2b2 100755 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/testAPIs.sh +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/testAPIs.sh @@ -185,16 +185,19 @@ echo echo "POST invoke chaincode on peers of Org1 and Org2" echo -curl -s -X POST \ +VALUES=$(curl -s -X POST \ http://localhost:4000/channels/mychannel/chaincodes/mycc \ -H "authorization: Bearer $ORG1_TOKEN" \ -H "content-type: application/json" \ -d "{ - \"peers\": [\"peer0.org1.example.com\",\"peer0.org2.example.com\"], - \"fcn\":\"move\", - \"args\":[\"a\",\"b\",\"10\"] -}" -echo + \"peers\": [\"peer0.org1.example.com\",\"peer0.org2.example.com\"], + \"fcn\":\"move\", + \"args\":[\"a\",\"b\",\"10\"] +}") +echo $VALUES +# Assign previous invoke transaction id to TRX_ID +MESSAGE=$(echo $VALUES | jq -r ".message") +TRX_ID=${MESSAGE#*ID:} echo echo "GET query chaincode on peer1 of Org1" @@ -213,7 +216,7 @@ BLOCK_INFO=$(curl -s -X GET \ -H "authorization: Bearer $ORG1_TOKEN" \ -H "content-type: application/json") echo $BLOCK_INFO -# Assign previvious block hash to HASH +# Assign previous block hash to HASH HASH=$(echo $BLOCK_INFO | jq -r ".header.previous_hash") echo diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/.gitignore b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/.gitignore index be8a40aac..5e283e61a 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/.gitignore +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/.gitignore @@ -1,6 +1,3 @@ -# -# SPDX-License-Identifier: Apache-2.0 -# node_modules package-lock.json dist diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/README.md b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/README.md index cee3fb830..bbfdc1f82 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/README.md +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/README.md @@ -1,6 +1,3 @@ - - - ## Balance transfer This is a sample Node.js application written using typescript which demonstrates diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/chaincode.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/chaincode.ts index c05a6c4ce..4c5fda6bd 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/chaincode.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/chaincode.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/channel.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/channel.ts index c199b8747..49a79c721 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/channel.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/channel.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/index.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/index.ts index cabc310f0..f49700e08 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/index.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/index.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/users.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/users.ts index 222fbed8f..d9462555d 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/users.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/users.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/utils.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/utils.ts index a41bc8c07..128545fe9 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/utils.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/api/utils.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/app.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/app.ts index 59139156f..66e8680bf 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/app.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/app.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/config.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/config.ts index 03cd54a54..1277eee48 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/config.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/config.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/interfaces.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/interfaces.ts index 3f33e9d20..6acd2b1b6 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/interfaces.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/interfaces.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/chaincode.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/chaincode.ts index afefeb6c4..45629acb4 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/chaincode.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/chaincode.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * @@ -22,6 +18,7 @@ import * as util from 'util'; import * as fs from 'fs'; import * as path from 'path'; import * as helper from './helper'; +import { Peer, ProposalResponse, ChaincodeQueryResponse } from 'fabric-client'; // tslint:disable-next-line:no-var-requires const config = require('../app_config.json'); @@ -57,7 +54,8 @@ export async function installChaincode( targets: helper.newPeers(peers, org), chaincodePath, chaincodeId: chaincodeName, - chaincodeVersion + chaincodeVersion, + txId: client.newTransactionID(true) }; try { @@ -68,7 +66,7 @@ export async function installChaincode( const proposal = results[1]; let allGood = true; - proposalResponses.forEach((pr) => { + proposalResponses.forEach((pr: ProposalResponse) => { let oneGood = false; if (pr.response && pr.response.status === 200) { oneGood = true; @@ -80,9 +78,10 @@ export async function installChaincode( }); if (allGood) { + const proposalResponse = proposalResponses[0] as ProposalResponse; logger.info(util.format( 'Successfully sent install Proposal and received ProposalResponse: Status - %s', - proposalResponses[0].response.status)); + proposalResponse.response.status)); logger.debug('\nSuccessfully Installed chaincode on organization ' + org + '\n'); return 'Successfully Installed chaincode on organization ' + org; @@ -149,4 +148,4 @@ export async function getInstalledChaincodes( logger.error('Failed to query with error:' + err.stack ? err.stack : err); return 'Failed to query with error:' + err.stack ? err.stack : err; } -} \ No newline at end of file +} diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/channel.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/channel.ts index f53b65f7a..5976351dd 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/channel.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/channel.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * @@ -22,11 +18,14 @@ import * as util from 'util'; import * as fs from 'fs'; import * as path from 'path'; import * as helper from './helper'; +import { ChannelEventHub, Peer, ProposalResponse, ChaincodeInvokeRequest, + ChaincodeQueryRequest, ChannelInfo } from 'fabric-client'; + const logger = helper.getLogger('ChannelApi'); // tslint:disable-next-line:no-var-requires const config = require('../app_config.json'); -const allEventhubs: EventHub[] = []; +const allEventhubs: ChannelEventHub[] = []; function buildTarget(peer: string, org: string): Peer { let target: Peer = null; @@ -136,40 +135,10 @@ export async function joinChannel( block: genesisBlock }; - const eventhubs = helper.newEventHubs(peers, org); - eventhubs.forEach((eh) => { - eh.connect(); - allEventhubs.push(eh); - }); - - const eventPromises: Array> = []; - eventhubs.forEach((eh) => { - const txPromise = new Promise((resolve, reject) => { - const handle = setTimeout(reject, parseInt(config.eventWaitTime, 10)); - eh.registerBlockEvent((block: any) => { - clearTimeout(handle); - // in real-world situations, a peer may have more than one channels so - // we must check that this block came from the channel we asked the peer to join - if (block.data.data.length === 1) { - // Config block must only contain one transaction - const channel_header = block.data.data[0].payload.header.channel_header; - if (channel_header.channel_id === channelName) { - resolve(); - } else { - reject(); - } - } - }); - }); - eventPromises.push(txPromise); - }); - - const sendPromise = channel.joinChannel(request2); - const results = await Promise.all([sendPromise].concat(eventPromises)); + const results = await channel.joinChannel(request2); logger.debug(util.format('Join Channel R E S P O N S E : %j', results)); - if (results[0] && results[0][0] && results[0][0].response && results[0][0] - .response.status === 200) { + if (results[0] && results[0].response && results[0].response.status === 200) { logger.info(util.format( 'Successfully joined peers in organization %s to the channel \'%s\'', org, channelName)); @@ -220,7 +189,7 @@ export async function instantiateChainCode( let allGood = true; - proposalResponses.forEach((pr) => { + proposalResponses.forEach((pr: ProposalResponse) => { let oneGood = false; if (pr.response && pr.response.status === 200) { oneGood = true; @@ -232,15 +201,17 @@ export async function instantiateChainCode( }); if (allGood) { + const responses = proposalResponses as ProposalResponse[]; + const proposalResponse = responses[0]; logger.info(util.format( // tslint:disable-next-line:max-line-length 'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s', - proposalResponses[0].response.status, proposalResponses[0].response.message, - proposalResponses[0].response.payload, proposalResponses[0].endorsement + proposalResponse.response.status, proposalResponse.response.message, + proposalResponse.response.payload, proposalResponse.endorsement .signature)); const request2 = { - proposalResponses, + proposalResponses: responses, proposal }; // set the transaction listener and set a timeout of 30sec @@ -249,15 +220,7 @@ export async function instantiateChainCode( const deployId = txId.getTransactionID(); const ORGS = helper.getOrgs(); - const eh = client.newEventHub(); - const data = fs.readFileSync(path.join(__dirname, ORGS[org].peers['peer1'][ - 'tls_cacerts' - ])); - - eh.setPeerAddr(ORGS[org].peers['peer1']['events'], { - 'pem': Buffer.from(data).toString(), - 'ssl-target-name-override': ORGS[org].peers['peer1']['server-hostname'] - }); + const eh = channel.newChannelEventHub('peer1'); eh.connect(); const txPromise: Promise = new Promise((resolve, reject) => { @@ -266,7 +229,7 @@ export async function instantiateChainCode( reject(); }, 30000); - eh.registerTxEvent(deployId, (tx, code) => { + eh.registerTxEvent(deployId, (tx: string, code: string) => { // logger.info( // 'The chaincode instantiate transaction has been committed on peer ' + // eh._ep._endpoint.addr); @@ -350,7 +313,7 @@ export async function invokeChaincode( const proposal = results[1]; let allGood = true; - proposalResponses.forEach((pr) => { + proposalResponses.forEach((pr: ProposalResponse) => { let oneGood = false; if (pr.response && pr.response.status === 200) { oneGood = true; @@ -362,15 +325,17 @@ export async function invokeChaincode( }); if (allGood) { + const responses = proposalResponses as ProposalResponse[]; + const proposalResponse = responses[0]; logger.debug(util.format( // tslint:disable-next-line:max-line-length 'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s', - proposalResponses[0].response.status, proposalResponses[0].response.message, - proposalResponses[0].response.payload, proposalResponses[0].endorsement + proposalResponse.response.status, proposalResponse.response.message, + proposalResponse.response.payload, proposalResponse.endorsement .signature)); const request2 = { - proposalResponses, + proposalResponses: responses, proposal }; @@ -388,7 +353,7 @@ export async function invokeChaincode( const eventhubs = helper.newEventHubs(peerNames, org); - eventhubs.forEach((eh: EventHub) => { + eventhubs.forEach((eh: ChannelEventHub) => { eh.connect(); const txPromise = new Promise((resolve, reject) => { @@ -456,11 +421,9 @@ export async function queryChaincode( const user = await helper.getRegisteredUsers(username, org); - const txId = client.newTransactionID(); // send query const request: ChaincodeQueryRequest = { chaincodeId: chaincodeName, - txId, fcn, args }; @@ -474,7 +437,7 @@ export async function queryChaincode( if (responsePayloads) { - responsePayloads.forEach((rp) => { + responsePayloads.forEach((rp: Buffer) => { logger.info(args[0] + ' now has ' + rp.toString('utf8') + ' after the move'); return args[0] + ' now has ' + rp.toString('utf8') + @@ -505,7 +468,7 @@ export async function getBlockByNumber( const responsePayloads = await channel.queryBlock(parseInt(blockNumber, 10), target); if (responsePayloads) { - logger.debug(responsePayloads); + logger.debug(responsePayloads.toString()); return responsePayloads; // response_payloads.data.data[0].buffer; } else { logger.error('response_payloads is null'); @@ -558,7 +521,7 @@ export async function getChainInfo(peer: string, username: string, org: string) if (blockChainInfo) { // FIXME: Save this for testing 'getBlockByHash' ? logger.debug('==========================================='); - logger.debug(blockChainInfo.currentBlockHash); + logger.debug(blockChainInfo.currentBlockHash.toString()); logger.debug('==========================================='); // logger.debug(blockchainInfo); return blockChainInfo; @@ -587,7 +550,7 @@ export async function getChannels(peer: string, username: string, org: string) { if (response) { logger.debug('<<< channels >>>'); const channelNames: string[] = []; - response.channels.forEach((ci) => { + response.channels.forEach((ci: ChannelInfo) => { channelNames.push('channel id: ' + ci.channel_id); }); return response; diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/helper.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/helper.ts index ffb995d4b..15c7a4cf9 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/helper.ts +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/lib/helper.ts @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /** * Copyright 2017 Kapil Sachdeva All Rights Reserved. * @@ -23,13 +19,14 @@ import * as path from 'path'; import * as fs from 'fs'; import * as util from 'util'; import config from '../config'; -import hfc = require('fabric-client'); +import Client = require('fabric-client'); +import { User, UserOpts, Channel } from 'fabric-client'; // tslint:disable-next-line:no-var-requires const copService = require('fabric-ca-client'); const logger = log4js.getLogger('Helper'); logger.setLevel('DEBUG'); -hfc.setLogger(logger); +Client.setLogger(logger); let ORGS: any; const clients = {}; @@ -48,7 +45,7 @@ function readAllFiles(dir: string) { } function getKeyStoreForOrg(org: string) { - return hfc.getConfigSetting('keyValueStore') + '_' + org; + return Client.getConfigSetting('keyValueStore') + '_' + org; } function setupPeers(channel: any, org: string, client: Client) { @@ -91,7 +88,7 @@ function getMspID(org: string) { function newRemotes(names: string[], forPeers: boolean, userOrg: string) { const client = getClientForOrg(userOrg); - + const channel = getChannelForOrg(userOrg); const targets: any[] = []; // find the peer that match the names names.forEach((n) => { @@ -104,11 +101,11 @@ function newRemotes(names: string[], forPeers: boolean, userOrg: string) { 'ssl-target-name-override': ORGS[userOrg].peers[n]['server-hostname'] }; + const peer = client.newPeer(ORGS[userOrg].peers[n].requests, grpcOpts); if (forPeers) { - targets.push(client.newPeer(ORGS[userOrg].peers[n].requests, grpcOpts)); + targets.push(peer); } else { - const eh = client.newEventHub(); - eh.setPeerAddr(ORGS[userOrg].peers[n].events, grpcOpts); + const eh = channel.newChannelEventHub(peer); targets.push(eh); } } @@ -122,13 +119,13 @@ function newRemotes(names: string[], forPeers: boolean, userOrg: string) { } async function getAdminUser(userOrg: string): Promise { - const users = hfc.getConfigSetting('admins'); + const users = Client.getConfigSetting('admins'); const username = users[0].username; const password = users[0].secret; const client = getClientForOrg(userOrg); - const store = await hfc.newDefaultKeyValueStore({ + const store = await Client.newDefaultKeyValueStore({ path: getKeyStoreForOrg(getOrgName(userOrg)) }); @@ -149,13 +146,14 @@ async function getAdminUser(userOrg: string): Promise { }); logger.info('Successfully enrolled user \'' + username + '\''); - const userOptions: UserOptions = { + const userOptions: UserOpts = { username, mspid: getMspID(userOrg), cryptoContent: { privateKeyPEM: enrollment.key.toBytes(), signedCertPEM: enrollment.certificate - } + }, + skipPersistence: false }; const member = await client.createUser(userOptions); @@ -171,7 +169,7 @@ export function newEventHubs(names: string[], org: string) { } export function setupChaincodeDeploy() { - process.env.GOPATH = path.join(__dirname, hfc.getConfigSetting('CC_SRC_PATH')); + process.env.GOPATH = path.join(__dirname, Client.getConfigSetting('CC_SRC_PATH')); } export function getOrgs() { @@ -188,26 +186,26 @@ export function getChannelForOrg(org: string): Channel { export function init() { - hfc.addConfigFile(path.join(__dirname, config.networkConfigFile)); - hfc.addConfigFile(path.join(__dirname, '../app_config.json')); + Client.addConfigFile(path.join(__dirname, config.networkConfigFile)); + Client.addConfigFile(path.join(__dirname, '../app_config.json')); - ORGS = hfc.getConfigSetting('network-config'); + ORGS = Client.getConfigSetting('network-config'); // set up the client and channel objects for each org for (const key in ORGS) { if (key.indexOf('org') === 0) { - const client = new hfc(); + const client = new Client(); - const cryptoSuite = hfc.newCryptoSuite(); + const cryptoSuite = Client.newCryptoSuite(); // TODO: Fix it up as setCryptoKeyStore is only available for s/w impl (cryptoSuite as any).setCryptoKeyStore( - hfc.newCryptoKeyStore({ + Client.newCryptoKeyStore({ path: getKeyStoreForOrg(ORGS[key].name) })); client.setCryptoSuite(cryptoSuite); - const channel = client.newChannel(hfc.getConfigSetting('channelName')); + const channel = client.newChannel(Client.getConfigSetting('channelName')); channel.addOrderer(newOrderer(client)); clients[key] = client; @@ -227,7 +225,7 @@ export async function getRegisteredUsers( const client = getClientForOrg(userOrg); - const store = await hfc.newDefaultKeyValueStore({ + const store = await Client.newDefaultKeyValueStore({ path: getKeyStoreForOrg(getOrgName(userOrg)) }); @@ -263,13 +261,14 @@ export async function getRegisteredUsers( } logger.debug(username + ' enrolled successfully'); - const userOptions: UserOptions = { + const userOptions: UserOpts = { username, mspid: getMspID(userOrg), cryptoContent: { privateKeyPEM: message.key.toBytes(), signedCertPEM: message.certificate - } + }, + skipPersistence: false }; const member = await client.createUser(userOptions); @@ -290,15 +289,15 @@ export async function getOrgAdmin(userOrg: string): Promise { const certPEM = readAllFiles(certPath)[0].toString(); const client = getClientForOrg(userOrg); - const cryptoSuite = hfc.newCryptoSuite(); + const cryptoSuite = Client.newCryptoSuite(); if (userOrg) { (cryptoSuite as any).setCryptoKeyStore( - hfc.newCryptoKeyStore({ path: getKeyStoreForOrg(getOrgName(userOrg)) })); + Client.newCryptoKeyStore({ path: getKeyStoreForOrg(getOrgName(userOrg)) })); client.setCryptoSuite(cryptoSuite); } - const store = await hfc.newDefaultKeyValueStore({ + const store = await Client.newDefaultKeyValueStore({ path: getKeyStoreForOrg(getOrgName(userOrg)) }); @@ -310,6 +309,7 @@ export async function getOrgAdmin(userOrg: string): Promise { cryptoContent: { privateKeyPEM: keyPEM, signedCertPEM: certPEM - } + }, + skipPersistence: false }); } diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/package.json b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/package.json index 179706b17..a94f7e7a8 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/package.json +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/package.json @@ -10,6 +10,7 @@ "license": "Apache-2.0", "devDependencies": { "@types/body-parser": "^1.16.5", + "@types/bytebuffer": "^5.0.36", "@types/cors": "^2.8.1", "@types/express-jwt": "0.0.37", "@types/express-session": "^1.15.3", @@ -18,7 +19,7 @@ "@types/node": "^8.0.33", "express-bearer-token": "^2.1.0", "jsonwebtoken": "^8.1.0", - "ts-node": "^3.3.0", + "ts-node": "^7.0.1", "tslint": "^5.6.0", "tslint-microsoft-contrib": "^5.0.1", "typescript": "^2.5.3" diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/runApp.sh b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/runApp.sh index be79b9d4a..3a86224d4 100755 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/runApp.sh +++ b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/runApp.sh @@ -51,21 +51,13 @@ function installNodeModules() { echo "============== Installing node modules =============" npm install fi - copyIndex fabric-client/index.d.ts - copyIndex fabric-ca-client/index.d.ts echo } -function copyIndex() { - if [ ! -f node_modules/$1 ]; then - cp types/$1 node_modules/$1 - fi -} - restartNetwork installNodeModules -PORT=4000 ts-node app.ts +PORT=4000 `npm bin`/ts-node app.ts diff --git a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/types/fabric-ca-client/index.d.ts b/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/types/fabric-ca-client/index.d.ts deleted file mode 100644 index 6fd877a83..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/balance-transfer/typescript/types/fabric-ca-client/index.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -/** - * Copyright 2017 Kapil Sachdeva All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -declare module 'fabric-ca-client' { -} \ No newline at end of file diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/abac.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/abac.go deleted file mode 100644 index f41d3c51c..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/abac.go +++ /dev/null @@ -1,210 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package main - -import ( - "fmt" - "strconv" - - "github.com/hyperledger/fabric/core/chaincode/shim/ext/cid" - "github.com/hyperledger/fabric/core/chaincode/shim" - pb "github.com/hyperledger/fabric/protos/peer" -) - -// SimpleChaincode example simple Chaincode implementation -type SimpleChaincode struct { -} - -// Init initializes the chaincode -func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { - - fmt.Println("abac Init") - - // - // Demonstrate the use of Attribute-Based Access Control (ABAC) by checking - // to see if the caller has the "abac.init" attribute with a value of true; - // if not, return an error. - // - err := cid.AssertAttributeValue(stub, "abac.init", "true") - if err != nil { - return shim.Error(err.Error()) - } - - _, args := stub.GetFunctionAndParameters() - var A, B string // Entities - var Aval, Bval int // Asset holdings - - if len(args) != 4 { - return shim.Error("Incorrect number of arguments. Expecting 4") - } - - // Initialize the chaincode - A = args[0] - Aval, err = strconv.Atoi(args[1]) - if err != nil { - return shim.Error("Expecting integer value for asset holding") - } - B = args[2] - Bval, err = strconv.Atoi(args[3]) - if err != nil { - return shim.Error("Expecting integer value for asset holding") - } - fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval) - - // Write the state to the ledger - err = stub.PutState(A, []byte(strconv.Itoa(Aval))) - if err != nil { - return shim.Error(err.Error()) - } - - err = stub.PutState(B, []byte(strconv.Itoa(Bval))) - if err != nil { - return shim.Error(err.Error()) - } - - return shim.Success(nil) -} - -func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response { - fmt.Println("abac Invoke") - function, args := stub.GetFunctionAndParameters() - if function == "invoke" { - // Make payment of X units from A to B - return t.invoke(stub, args) - } else if function == "delete" { - // Deletes an entity from its state - return t.delete(stub, args) - } else if function == "query" { - // the old "Query" is now implemtned in invoke - return t.query(stub, args) - } - - return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"") -} - -// Transaction makes payment of X units from A to B -func (t *SimpleChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response { - var A, B string // Entities - var Aval, Bval int // Asset holdings - var X int // Transaction value - var err error - - if len(args) != 3 { - return shim.Error("Incorrect number of arguments. Expecting 3") - } - - A = args[0] - B = args[1] - - // Get the state from the ledger - // TODO: will be nice to have a GetAllState call to ledger - Avalbytes, err := stub.GetState(A) - if err != nil { - return shim.Error("Failed to get state") - } - if Avalbytes == nil { - return shim.Error("Entity not found") - } - Aval, _ = strconv.Atoi(string(Avalbytes)) - - Bvalbytes, err := stub.GetState(B) - if err != nil { - return shim.Error("Failed to get state") - } - if Bvalbytes == nil { - return shim.Error("Entity not found") - } - Bval, _ = strconv.Atoi(string(Bvalbytes)) - - // Perform the execution - X, err = strconv.Atoi(args[2]) - if err != nil { - return shim.Error("Invalid transaction amount, expecting a integer value") - } - Aval = Aval - X - Bval = Bval + X - fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval) - - // Write the state back to the ledger - err = stub.PutState(A, []byte(strconv.Itoa(Aval))) - if err != nil { - return shim.Error(err.Error()) - } - - err = stub.PutState(B, []byte(strconv.Itoa(Bval))) - if err != nil { - return shim.Error(err.Error()) - } - - return shim.Success(nil) -} - -// Deletes an entity from state -func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response { - if len(args) != 1 { - return shim.Error("Incorrect number of arguments. Expecting 1") - } - - A := args[0] - - // Delete the key from the state in ledger - err := stub.DelState(A) - if err != nil { - return shim.Error("Failed to delete state") - } - - return shim.Success(nil) -} - -// query callback representing the query of a chaincode -func (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response { - var A string // Entities - var err error - - if len(args) != 1 { - return shim.Error("Incorrect number of arguments. Expecting name of the person to query") - } - - A = args[0] - - // Get the state from the ledger - Avalbytes, err := stub.GetState(A) - if err != nil { - jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}" - return shim.Error(jsonResp) - } - - if Avalbytes == nil { - jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}" - return shim.Error(jsonResp) - } - - jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}" - fmt.Printf("Query Response:%s\n", jsonResp) - return shim.Success(Avalbytes) -} - -func main() { - err := shim.Start(new(SimpleChaincode)) - if err != nil { - fmt.Printf("Error starting Simple chaincode: %s", err) - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/LICENSE b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/LICENSE deleted file mode 100644 index 0f646931a..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2010 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/clone.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/clone.go deleted file mode 100644 index df45fc48e..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,257 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer deep copy and merge. -// TODO: RawMessage. - -package proto - -import ( - "fmt" - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(src Message) Message { - in := reflect.ValueOf(src) - if in.IsNil() { - return src - } - out := reflect.New(in.Type().Elem()) - dst := out.Interface().(Message) - Merge(dst, src) - return dst -} - -// Merger is the interface representing objects that can merge messages of the same type. -type Merger interface { - // Merge merges src into this message. - // Required and optional fields that are set in src will be set to that value in dst. - // Elements of repeated fields will be appended. - // - // Merge may panic if called with a different argument type than the receiver. - Merge(src Message) -} - -// generatedMerger is the custom merge method that generated protos will have. -// We must add this method since a generate Merge method will conflict with -// many existing protos that have a Merge data field already defined. -type generatedMerger interface { - XXX_Merge(src Message) -} - -// Merge merges src into dst. -// Required and optional fields that are set in src will be set to that value in dst. -// Elements of repeated fields will be appended. -// Merge panics if src and dst are not the same type, or if dst is nil. -func Merge(dst, src Message) { - if m, ok := dst.(Merger); ok { - m.Merge(src) - return - } - - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) - } - if in.IsNil() { - return // Merge from nil src is a noop - } - if m, ok := dst.(generatedMerger); ok { - m.XXX_Merge(src) - return - } - mergeStruct(out.Elem(), in.Elem()) -} - -func mergeStruct(out, in reflect.Value) { - sprop := GetProperties(in.Type()) - for i := 0; i < in.NumField(); i++ { - f := in.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) - } - - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// mergeAny performs a merge between two values of the same type. -// viaPtr indicates whether the values were indirected through a pointer (implying proto2). -// prop is set if this is a struct field (it may be nil). -func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { - if in.Type() == protoMessageType { - if !in.IsNil() { - if out.IsNil() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - switch in.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - if !viaPtr && isProto3Zero(in) { - return - } - out.Set(in) - case reflect.Interface: - // Probably a oneof field; copy non-nil values. - if in.IsNil() { - return - } - // Allocate destination if it is not set, or set to a different type. - // Otherwise we will merge as normal. - if out.IsNil() || out.Elem().Type() != in.Elem().Type() { - out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) - } - mergeAny(out.Elem(), in.Elem(), false, nil) - case reflect.Map: - if in.Len() == 0 { - return - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - mergeAny(out.Elem(), in.Elem(), true, nil) - case reflect.Slice: - if in.IsNil() { - return - } - if in.Type().Elem().Kind() == reflect.Uint8 { - // []byte is a scalar bytes field, not a repeated field. - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value, and should not - // be merged. - if prop != nil && prop.proto3 && in.Len() == 0 { - return - } - - // Make a deep copy. - // Append to []byte{} instead of []byte(nil) so that we never end up - // with a nil result. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/decode.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/decode.go deleted file mode 100644 index 96805227f..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,431 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for decoding protocol buffer data to construct in-memory representations. - */ - -import ( - "errors" - "fmt" - "io" -) - -// errOverflow is returned when an integer is too large to be represented. -var errOverflow = errors.New("proto: integer overflow") - -// ErrInternalBadWireType is returned by generated code when an incorrect -// wire type is encountered. It does not get returned to user code. -var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func DecodeVarint(buf []byte) (x uint64, n int) { - for shift := uint(0); shift < 64; shift += 7 { - if n >= len(buf) { - return 0, 0 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - return 0, 0 -} - -func (p *Buffer) decodeVarintSlow() (x uint64, err error) { - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - i := p.index - buf := p.buf - - if i >= len(buf) { - return 0, io.ErrUnexpectedEOF - } else if buf[i] < 0x80 { - p.index++ - return uint64(buf[i]), nil - } else if len(buf)-i < 10 { - return p.decodeVarintSlow() - } - - var b uint64 - // we already checked the first byte - x = uint64(buf[i]) - 0x80 - i++ - - b = uint64(buf[i]) - i++ - x += b << 7 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 7 - - b = uint64(buf[i]) - i++ - x += b << 14 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 14 - - b = uint64(buf[i]) - i++ - x += b << 21 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 21 - - b = uint64(buf[i]) - i++ - x += b << 28 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 28 - - b = uint64(buf[i]) - i++ - x += b << 35 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 35 - - b = uint64(buf[i]) - i++ - x += b << 42 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 42 - - b = uint64(buf[i]) - i++ - x += b << 49 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 49 - - b = uint64(buf[i]) - i++ - x += b << 56 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 56 - - b = uint64(buf[i]) - i++ - x += b << 63 - if b&0x80 == 0 { - goto done - } - - return 0, errOverflow - -done: - p.index = i - return x, nil -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { - n, err := p.DecodeVarint() - if err != nil { - return nil, err - } - - nb := int(n) - if nb < 0 { - return nil, fmt.Errorf("proto: bad byte length %d", nb) - } - end := p.index + nb - if end < p.index || end > len(p.buf) { - return nil, io.ErrUnexpectedEOF - } - - if !alloc { - // todo: check if can get more uses of alloc=false - buf = p.buf[p.index:end] - p.index += nb - return - } - - buf = make([]byte, nb) - copy(buf, p.buf[p.index:]) - p.index += nb - return -} - -// DecodeStringBytes reads an encoded string from the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) DecodeStringBytes() (s string, err error) { - buf, err := p.DecodeRawBytes(false) - if err != nil { - return - } - return string(buf), nil -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -// Unmarshal implementations should not clear the receiver. -// Any unmarshaled data should be merged into the receiver. -// Callers of Unmarshal that do not want to retain existing data -// should Reset the receiver before calling Unmarshal. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// newUnmarshaler is the interface representing objects that can -// unmarshal themselves. The semantics are identical to Unmarshaler. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newUnmarshaler interface { - XXX_Unmarshal([]byte) error -} - -// Unmarshal parses the protocol buffer representation in buf and places the -// decoded result in pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// Unmarshal resets pb before starting to unmarshal, so any -// existing data in pb is always removed. Use UnmarshalMerge -// to preserve and append to existing data. -func Unmarshal(buf []byte, pb Message) error { - pb.Reset() - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// UnmarshalMerge parses the protocol buffer representation in buf and -// writes the decoded result to pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// UnmarshalMerge merges into existing data in pb. -// Most code should use Unmarshal instead. -func UnmarshalMerge(buf []byte, pb Message) error { - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// DecodeMessage reads a count-delimited message from the Buffer. -func (p *Buffer) DecodeMessage(pb Message) error { - enc, err := p.DecodeRawBytes(false) - if err != nil { - return err - } - return NewBuffer(enc).Unmarshal(pb) -} - -// DecodeGroup reads a tag-delimited group from the Buffer. -// StartGroup tag is already consumed. This function consumes -// EndGroup tag. -func (p *Buffer) DecodeGroup(pb Message) error { - b := p.buf[p.index:] - x, y := findEndGroup(b) - if x < 0 { - return io.ErrUnexpectedEOF - } - err := Unmarshal(b[:x], pb) - p.index += y - return err -} - -// Unmarshal parses the protocol buffer representation in the -// Buffer and places the decoded result in pb. If the struct -// underlying pb does not match the data in the buffer, the results can be -// unpredictable. -// -// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(newUnmarshaler); ok { - err := u.XXX_Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - // Slow workaround for messages that aren't Unmarshalers. - // This includes some hand-coded .pb.go files and - // bootstrap protos. - // TODO: fix all of those and then add Unmarshal to - // the Message interface. Then: - // The cast above and code below can be deleted. - // The old unmarshaler can be deleted. - // Clients can call Unmarshal directly (can already do that, actually). - var info InternalMessageInfo - err := info.Unmarshal(pb, p.buf[p.index:]) - p.index = len(p.buf) - return err -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/deprecated.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/deprecated.go deleted file mode 100644 index e953d3ab7..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/deprecated.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Deprecated: do not use. -type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } - -// Deprecated: do not use. -func GetStats() Stats { return Stats{} } diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/discard.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/discard.go deleted file mode 100644 index 299993015..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/discard.go +++ /dev/null @@ -1,354 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2017 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type generatedDiscarder interface { - XXX_DiscardUnknown() -} - -// DiscardUnknown recursively discards all unknown fields from this message -// and all embedded messages. -// -// When unmarshaling a message with unrecognized fields, the tags and values -// of such fields are preserved in the Message. This allows a later call to -// marshal to be able to produce a message that continues to have those -// unrecognized fields. To avoid this, DiscardUnknown is used to -// explicitly clear the unknown fields after unmarshaling. -// -// For proto2 messages, the unknown fields of message extensions are only -// discarded from messages that have been accessed via GetExtension. -func DiscardUnknown(m Message) { - if m, ok := m.(generatedDiscarder); ok { - m.XXX_DiscardUnknown() - return - } - // TODO: Dynamically populate a InternalMessageInfo for legacy messages, - // but the master branch has no implementation for InternalMessageInfo, - // so it would be more work to replicate that approach. - discardLegacy(m) -} - -// DiscardUnknown recursively discards all unknown fields. -func (a *InternalMessageInfo) DiscardUnknown(m Message) { - di := atomicLoadDiscardInfo(&a.discard) - if di == nil { - di = getDiscardInfo(reflect.TypeOf(m).Elem()) - atomicStoreDiscardInfo(&a.discard, di) - } - di.discard(toPointer(&m)) -} - -type discardInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []discardFieldInfo - unrecognized field -} - -type discardFieldInfo struct { - field field // Offset of field, guaranteed to be valid - discard func(src pointer) -} - -var ( - discardInfoMap = map[reflect.Type]*discardInfo{} - discardInfoLock sync.Mutex -) - -func getDiscardInfo(t reflect.Type) *discardInfo { - discardInfoLock.Lock() - defer discardInfoLock.Unlock() - di := discardInfoMap[t] - if di == nil { - di = &discardInfo{typ: t} - discardInfoMap[t] = di - } - return di -} - -func (di *discardInfo) discard(src pointer) { - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&di.initialized) == 0 { - di.computeDiscardInfo() - } - - for _, fi := range di.fields { - sfp := src.offset(fi.field) - fi.discard(sfp) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { - // Ignore lock since DiscardUnknown is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - DiscardUnknown(m) - } - } - } - - if di.unrecognized.IsValid() { - *src.offset(di.unrecognized).toBytes() = nil - } -} - -func (di *discardInfo) computeDiscardInfo() { - di.lock.Lock() - defer di.lock.Unlock() - if di.initialized != 0 { - return - } - t := di.typ - n := t.NumField() - - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - dfi := discardFieldInfo{field: toField(&f)} - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) - case isSlice: // E.g., []*pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sps := src.getPointerSlice() - for _, sp := range sps { - if !sp.isNil() { - di.discard(sp) - } - } - } - default: // E.g., *pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sp := src.getPointer() - if !sp.isNil() { - di.discard(sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) - default: // E.g., map[K]V - if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) - dfi.discard = func(src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - DiscardUnknown(val.Interface().(Message)) - } - } - } else { - dfi.discard = func(pointer) {} // Noop - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) - default: // E.g., interface{} - // TODO: Make this faster? - dfi.discard = func(src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - DiscardUnknown(sv.Interface().(Message)) - } - } - } - } - default: - continue - } - di.fields = append(di.fields, dfi) - } - - di.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - di.unrecognized = toField(&f) - } - - atomic.StoreInt32(&di.initialized, 1) -} - -func discardLegacy(m Message) { - v := reflect.ValueOf(m) - if v.Kind() != reflect.Ptr || v.IsNil() { - return - } - v = v.Elem() - if v.Kind() != reflect.Struct { - return - } - t := v.Type() - - for i := 0; i < v.NumField(); i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - vf := v.Field(i) - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name)) - case isSlice: // E.g., []*pb.T - for j := 0; j < vf.Len(); j++ { - discardLegacy(vf.Index(j).Interface().(Message)) - } - default: // E.g., *pb.T - discardLegacy(vf.Interface().(Message)) - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name)) - default: // E.g., map[K]V - tv := vf.Type().Elem() - if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T) - for _, key := range vf.MapKeys() { - val := vf.MapIndex(key) - discardLegacy(val.Interface().(Message)) - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name)) - default: // E.g., test_proto.isCommunique_Union interface - if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" { - vf = vf.Elem() // E.g., *test_proto.Communique_Msg - if !vf.IsNil() { - vf = vf.Elem() // E.g., test_proto.Communique_Msg - vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value - if vf.Kind() == reflect.Ptr { - discardLegacy(vf.Interface().(Message)) - } - } - } - } - } - } - - if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() { - if vf.Type() != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - vf.Set(reflect.ValueOf([]byte(nil))) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(m); err == nil { - // Ignore lock since discardLegacy is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - discardLegacy(m) - } - } - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/encode.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/encode.go deleted file mode 100644 index 1c5e4be78..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/encode.go +++ /dev/null @@ -1,207 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "errors" - "reflect" -) - -var ( - // errRepeatedHasNil is the error returned if Marshal is called with - // a struct with a repeated field containing a nil element. - errRepeatedHasNil = errors.New("proto: repeated field has nil element") - - // errOneofHasNil is the error returned if Marshal is called with - // a struct with a oneof field containing a nil element. - errOneofHasNil = errors.New("proto: oneof field has nil value") - - // ErrNil is the error returned if Marshal is called with nil. - ErrNil = errors.New("proto: Marshal called with nil") - - // ErrTooLarge is the error returned if Marshal is called with a - // message that encodes to >2GB. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// EncodeVarint returns the varint encoding of x. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -// Not used by the package itself, but helpful to clients -// wishing to use the same encoding. -func EncodeVarint(x uint64) []byte { - var buf [maxVarintBytes]byte - var n int - for n = 0; x > 127; n++ { - buf[n] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - buf[n] = uint8(x) - n++ - return buf[0:n] -} - -// EncodeVarint writes a varint-encoded integer to the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) EncodeVarint(x uint64) error { - for x >= 1<<7 { - p.buf = append(p.buf, uint8(x&0x7f|0x80)) - x >>= 7 - } - p.buf = append(p.buf, uint8(x)) - return nil -} - -// SizeVarint returns the varint encoding size of an integer. -func SizeVarint(x uint64) int { - switch { - case x < 1<<7: - return 1 - case x < 1<<14: - return 2 - case x < 1<<21: - return 3 - case x < 1<<28: - return 4 - case x < 1<<35: - return 5 - case x < 1<<42: - return 6 - case x < 1<<49: - return 7 - case x < 1<<56: - return 8 - case x < 1<<63: - return 9 - } - return 10 -} - -// EncodeFixed64 writes a 64-bit integer to the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) EncodeFixed64(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24), - uint8(x>>32), - uint8(x>>40), - uint8(x>>48), - uint8(x>>56)) - return nil -} - -// EncodeFixed32 writes a 32-bit integer to the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) EncodeFixed32(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24)) - return nil -} - -// EncodeZigzag64 writes a zigzag-encoded 64-bit integer -// to the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) EncodeZigzag64(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -// EncodeZigzag32 writes a zigzag-encoded 32-bit integer -// to the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) EncodeZigzag32(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) EncodeRawBytes(b []byte) error { - p.EncodeVarint(uint64(len(b))) - p.buf = append(p.buf, b...) - return nil -} - -// EncodeStringBytes writes an encoded string to the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) EncodeStringBytes(s string) error { - p.EncodeVarint(uint64(len(s))) - p.buf = append(p.buf, s...) - return nil -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// EncodeMessage writes the protocol buffer to the Buffer, -// prefixed by a varint-encoded length. -func (p *Buffer) EncodeMessage(pb Message) error { - siz := Size(pb) - p.EncodeVarint(uint64(siz)) - return p.Marshal(pb) -} - -// All protocol buffer fields are nillable, but be careful. -func isNil(v reflect.Value) bool { - switch v.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/equal.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/equal.go deleted file mode 100644 index 9dd7eddf8..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/equal.go +++ /dev/null @@ -1,304 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer comparison. - -package proto - -import ( - "bytes" - "log" - "reflect" - "strings" -) - -/* -Equal returns true iff protocol buffers a and b are equal. -The arguments must both be pointers to protocol buffer structs. - -Equality is defined in this way: - - Two messages are equal iff they are the same type, - corresponding fields are equal, unknown field sets - are equal, and extensions sets are equal. - - Two set scalar fields are equal iff their values are equal. - If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. If the message is defined - in a proto3 .proto file, fields are not "set"; specifically, - zero length proto3 "bytes" fields are equal (nil == {}). - - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal. Note a "bytes" field, - although represented by []byte, is not a repeated field and the - rule for the scalar fields described above applies. - - Two unset fields are equal. - - Two unknown field sets are equal if their current - encoded state is equal. - - Two extension sets are equal iff they have corresponding - elements that are pairwise equal. - - Two map fields are equal iff their lengths are the same, - and they contain the same set of elements. Zero-length map - fields are equal. - - Every other combination of things are not equal. - -The return value is undefined if a and b are not protocol buffers. -*/ -func Equal(a, b Message) bool { - if a == nil || b == nil { - return a == b - } - v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) - if v1.Type() != v2.Type() { - return false - } - if v1.Kind() == reflect.Ptr { - if v1.IsNil() { - return v2.IsNil() - } - if v2.IsNil() { - return false - } - v1, v2 = v1.Elem(), v2.Elem() - } - if v1.Kind() != reflect.Struct { - return false - } - return equalStruct(v1, v2) -} - -// v1 and v2 are known to have the same type. -func equalStruct(v1, v2 reflect.Value) bool { - sprop := GetProperties(v1.Type()) - for i := 0; i < v1.NumField(); i++ { - f := v1.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - f1, f2 := v1.Field(i), v2.Field(i) - if f.Type.Kind() == reflect.Ptr { - if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { - // both unset - continue - } else if n1 != n2 { - // set/unset mismatch - return false - } - f1, f2 = f1.Elem(), f2.Elem() - } - if !equalAny(f1, f2, sprop.Prop[i]) { - return false - } - } - - if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_InternalExtensions") - if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { - return false - } - } - - if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_extensions") - if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { - return false - } - } - - uf := v1.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return true - } - - u1 := uf.Bytes() - u2 := v2.FieldByName("XXX_unrecognized").Bytes() - return bytes.Equal(u1, u2) -} - -// v1 and v2 are known to have the same type. -// prop may be nil. -func equalAny(v1, v2 reflect.Value, prop *Properties) bool { - if v1.Type() == protoMessageType { - m1, _ := v1.Interface().(Message) - m2, _ := v2.Interface().(Message) - return Equal(m1, m2) - } - switch v1.Kind() { - case reflect.Bool: - return v1.Bool() == v2.Bool() - case reflect.Float32, reflect.Float64: - return v1.Float() == v2.Float() - case reflect.Int32, reflect.Int64: - return v1.Int() == v2.Int() - case reflect.Interface: - // Probably a oneof field; compare the inner values. - n1, n2 := v1.IsNil(), v2.IsNil() - if n1 || n2 { - return n1 == n2 - } - e1, e2 := v1.Elem(), v2.Elem() - if e1.Type() != e2.Type() { - return false - } - return equalAny(e1, e2, nil) - case reflect.Map: - if v1.Len() != v2.Len() { - return false - } - for _, key := range v1.MapKeys() { - val2 := v2.MapIndex(key) - if !val2.IsValid() { - // This key was not found in the second map. - return false - } - if !equalAny(v1.MapIndex(key), val2, nil) { - return false - } - } - return true - case reflect.Ptr: - // Maps may have nil values in them, so check for nil. - if v1.IsNil() && v2.IsNil() { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return equalAny(v1.Elem(), v2.Elem(), prop) - case reflect.Slice: - if v1.Type().Elem().Kind() == reflect.Uint8 { - // short circuit: []byte - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value. - if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) - } - - if v1.Len() != v2.Len() { - return false - } - for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i), prop) { - return false - } - } - return true - case reflect.String: - return v1.Interface().(string) == v2.Interface().(string) - case reflect.Struct: - return equalStruct(v1, v2) - case reflect.Uint32, reflect.Uint64: - return v1.Uint() == v2.Uint() - } - - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to compare %v", v1) - return false -} - -// base is the struct type that the extensions are based on. -// x1 and x2 are InternalExtensions. -func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { - em1, _ := x1.extensionsRead() - em2, _ := x2.extensionsRead() - return equalExtMap(base, em1, em2) -} - -func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { - if len(em1) != len(em2) { - return false - } - - for extNum, e1 := range em1 { - e2, ok := em2[extNum] - if !ok { - return false - } - - m1, m2 := e1.value, e2.value - - if m1 == nil && m2 == nil { - // Both have only encoded form. - if bytes.Equal(e1.enc, e2.enc) { - continue - } - // The bytes are different, but the extensions might still be - // equal. We need to decode them to compare. - } - - if m1 != nil && m2 != nil { - // Both are unencoded. - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - continue - } - - // At least one is encoded. To do a semantically correct comparison - // we need to unmarshal them first. - var desc *ExtensionDesc - if m := extensionMaps[base]; m != nil { - desc = m[extNum] - } - if desc == nil { - // If both have only encoded form and the bytes are the same, - // it is handled above. We get here when the bytes are different. - // We don't know how to decode it, so just compare them as byte - // slices. - log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - return false - } - var err error - if m1 == nil { - m1, err = decodeExtension(e1.enc, desc) - } - if m2 == nil && err == nil { - m2, err = decodeExtension(e2.enc, desc) - } - if err != nil { - // The encoded form is invalid. - log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) - return false - } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - } - - return true -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/extensions.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index 3298d252a..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,547 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Types and routines for supporting protocol buffer extensions. - */ - -import ( - "errors" - "fmt" - "io" - "reflect" - "strconv" - "sync" -) - -// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. -var ErrMissingExtension = errors.New("proto: missing extension") - -// ExtensionRange represents a range of message extensions for a protocol buffer. -// Used in code generated by the protocol compiler. -type ExtensionRange struct { - Start, End int32 // both inclusive -} - -// extendableProto is an interface implemented by any protocol buffer generated by the current -// proto compiler that may be extended. -type extendableProto interface { - Message - ExtensionRangeArray() []ExtensionRange - extensionsWrite() map[int32]Extension - extensionsRead() (map[int32]Extension, sync.Locker) -} - -// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous -// version of the proto compiler that may be extended. -type extendableProtoV1 interface { - Message - ExtensionRangeArray() []ExtensionRange - ExtensionMap() map[int32]Extension -} - -// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. -type extensionAdapter struct { - extendableProtoV1 -} - -func (e extensionAdapter) extensionsWrite() map[int32]Extension { - return e.ExtensionMap() -} - -func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { - return e.ExtensionMap(), notLocker{} -} - -// notLocker is a sync.Locker whose Lock and Unlock methods are nops. -type notLocker struct{} - -func (n notLocker) Lock() {} -func (n notLocker) Unlock() {} - -// extendable returns the extendableProto interface for the given generated proto message. -// If the proto message has the old extension format, it returns a wrapper that implements -// the extendableProto interface. -func extendable(p interface{}) (extendableProto, error) { - switch p := p.(type) { - case extendableProto: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return p, nil - case extendableProtoV1: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return extensionAdapter{p}, nil - } - // Don't allocate a specific error containing %T: - // this is the hot path for Clone and MarshalText. - return nil, errNotExtendable -} - -var errNotExtendable = errors.New("proto: not an extendable proto.Message") - -func isNilPtr(x interface{}) bool { - v := reflect.ValueOf(x) - return v.Kind() == reflect.Ptr && v.IsNil() -} - -// XXX_InternalExtensions is an internal representation of proto extensions. -// -// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, -// thus gaining the unexported 'extensions' method, which can be called only from the proto package. -// -// The methods of XXX_InternalExtensions are not concurrency safe in general, -// but calls to logically read-only methods such as has and get may be executed concurrently. -type XXX_InternalExtensions struct { - // The struct must be indirect so that if a user inadvertently copies a - // generated message and its embedded XXX_InternalExtensions, they - // avoid the mayhem of a copied mutex. - // - // The mutex serializes all logically read-only operations to p.extensionMap. - // It is up to the client to ensure that write operations to p.extensionMap are - // mutually exclusive with other accesses. - p *struct { - mu sync.Mutex - extensionMap map[int32]Extension - } -} - -// extensionsWrite returns the extension map, creating it on first use. -func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { - if e.p == nil { - e.p = new(struct { - mu sync.Mutex - extensionMap map[int32]Extension - }) - e.p.extensionMap = make(map[int32]Extension) - } - return e.p.extensionMap -} - -// extensionsRead returns the extensions map for read-only use. It may be nil. -// The caller must hold the returned mutex's lock when accessing Elements within the map. -func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { - if e.p == nil { - return nil, nil - } - return e.p.extensionMap, &e.p.mu -} - -// ExtensionDesc represents an extension specification. -// Used in generated code from the protocol compiler. -type ExtensionDesc struct { - ExtendedType Message // nil pointer to the type that is being extended - ExtensionType interface{} // nil pointer to the extension type - Field int32 // field number - Name string // fully-qualified name of extension, for text formatting - Tag string // protobuf tag style - Filename string // name of the file in which the extension is defined -} - -func (ed *ExtensionDesc) repeated() bool { - t := reflect.TypeOf(ed.ExtensionType) - return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 -} - -// Extension represents an extension in a message. -type Extension struct { - // When an extension is stored in a message using SetExtension - // only desc and value are set. When the message is marshaled - // enc will be set to the encoded form of the message. - // - // When a message is unmarshaled and contains extensions, each - // extension will have only enc set. When such an extension is - // accessed using GetExtension (or GetExtensions) desc and value - // will be set. - desc *ExtensionDesc - value interface{} - enc []byte -} - -// SetRawExtension is for testing only. -func SetRawExtension(base Message, id int32, b []byte) { - epb, err := extendable(base) - if err != nil { - return - } - extmap := epb.extensionsWrite() - extmap[id] = Extension{enc: b} -} - -// isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extendableProto, field int32) bool { - for _, er := range pb.ExtensionRangeArray() { - if er.Start <= field && field <= er.End { - return true - } - } - return false -} - -// checkExtensionTypes checks that the given extension is valid for pb. -func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { - var pbi interface{} = pb - // Check the extended type. - if ea, ok := pbi.(extensionAdapter); ok { - pbi = ea.extendableProtoV1 - } - if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { - return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a) - } - // Check the range. - if !isExtensionField(pb, extension.Field) { - return errors.New("proto: bad extension number; not in declared ranges") - } - return nil -} - -// extPropKey is sufficient to uniquely identify an extension. -type extPropKey struct { - base reflect.Type - field int32 -} - -var extProp = struct { - sync.RWMutex - m map[extPropKey]*Properties -}{ - m: make(map[extPropKey]*Properties), -} - -func extensionProperties(ed *ExtensionDesc) *Properties { - key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} - - extProp.RLock() - if prop, ok := extProp.m[key]; ok { - extProp.RUnlock() - return prop - } - extProp.RUnlock() - - extProp.Lock() - defer extProp.Unlock() - // Check again. - if prop, ok := extProp.m[key]; ok { - return prop - } - - prop := new(Properties) - prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) - extProp.m[key] = prop - return prop -} - -// HasExtension returns whether the given extension is present in pb. -func HasExtension(pb Message, extension *ExtensionDesc) bool { - // TODO: Check types, field numbers, etc.? - epb, err := extendable(pb) - if err != nil { - return false - } - extmap, mu := epb.extensionsRead() - if extmap == nil { - return false - } - mu.Lock() - _, ok := extmap[extension.Field] - mu.Unlock() - return ok -} - -// ClearExtension removes the given extension from pb. -func ClearExtension(pb Message, extension *ExtensionDesc) { - epb, err := extendable(pb) - if err != nil { - return - } - // TODO: Check types, field numbers, etc.? - extmap := epb.extensionsWrite() - delete(extmap, extension.Field) -} - -// GetExtension retrieves a proto2 extended field from pb. -// -// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), -// then GetExtension parses the encoded field and returns a Go value of the specified type. -// If the field is not present, then the default value is returned (if one is specified), -// otherwise ErrMissingExtension is reported. -// -// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil), -// then GetExtension returns the raw encoded bytes of the field extension. -func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - - if extension.ExtendedType != nil { - // can only check type if this is a complete descriptor - if err := checkExtensionTypes(epb, extension); err != nil { - return nil, err - } - } - - emap, mu := epb.extensionsRead() - if emap == nil { - return defaultExtensionValue(extension) - } - mu.Lock() - defer mu.Unlock() - e, ok := emap[extension.Field] - if !ok { - // defaultExtensionValue returns the default value or - // ErrMissingExtension if there is no default. - return defaultExtensionValue(extension) - } - - if e.value != nil { - // Already decoded. Check the descriptor, though. - if e.desc != extension { - // This shouldn't happen. If it does, it means that - // GetExtension was called twice with two different - // descriptors with the same field number. - return nil, errors.New("proto: descriptor conflict") - } - return e.value, nil - } - - if extension.ExtensionType == nil { - // incomplete descriptor - return e.enc, nil - } - - v, err := decodeExtension(e.enc, extension) - if err != nil { - return nil, err - } - - // Remember the decoded version and drop the encoded version. - // That way it is safe to mutate what we return. - e.value = v - e.desc = extension - e.enc = nil - emap[extension.Field] = e - return e.value, nil -} - -// defaultExtensionValue returns the default value for extension. -// If no default for an extension is defined ErrMissingExtension is returned. -func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { - if extension.ExtensionType == nil { - // incomplete descriptor, so no default - return nil, ErrMissingExtension - } - - t := reflect.TypeOf(extension.ExtensionType) - props := extensionProperties(extension) - - sf, _, err := fieldDefault(t, props) - if err != nil { - return nil, err - } - - if sf == nil || sf.value == nil { - // There is no default value. - return nil, ErrMissingExtension - } - - if t.Kind() != reflect.Ptr { - // We do not need to return a Ptr, we can directly return sf.value. - return sf.value, nil - } - - // We need to return an interface{} that is a pointer to sf.value. - value := reflect.New(t).Elem() - value.Set(reflect.New(value.Type().Elem())) - if sf.kind == reflect.Int32 { - // We may have an int32 or an enum, but the underlying data is int32. - // Since we can't set an int32 into a non int32 reflect.value directly - // set it as a int32. - value.Elem().SetInt(int64(sf.value.(int32))) - } else { - value.Elem().Set(reflect.ValueOf(sf.value)) - } - return value.Interface(), nil -} - -// decodeExtension decodes an extension encoded in b. -func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { - t := reflect.TypeOf(extension.ExtensionType) - unmarshal := typeUnmarshaler(t, extension.Tag) - - // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate space to store the pointer/slice. - value := reflect.New(t).Elem() - - var err error - for { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - wire := int(x) & 7 - - b, err = unmarshal(b, valToPointer(value.Addr()), wire) - if err != nil { - return nil, err - } - - if len(b) == 0 { - break - } - } - return value.Interface(), nil -} - -// GetExtensions returns a slice of the extensions present in pb that are also listed in es. -// The returned slice has the same length as es; missing extensions will appear as nil elements. -func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - extensions = make([]interface{}, len(es)) - for i, e := range es { - extensions[i], err = GetExtension(epb, e) - if err == ErrMissingExtension { - err = nil - } - if err != nil { - return - } - } - return -} - -// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. -// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing -// just the Field field, which defines the extension's field number. -func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - registeredExtensions := RegisteredExtensions(pb) - - emap, mu := epb.extensionsRead() - if emap == nil { - return nil, nil - } - mu.Lock() - defer mu.Unlock() - extensions := make([]*ExtensionDesc, 0, len(emap)) - for extid, e := range emap { - desc := e.desc - if desc == nil { - desc = registeredExtensions[extid] - if desc == nil { - desc = &ExtensionDesc{Field: extid} - } - } - - extensions = append(extensions, desc) - } - return extensions, nil -} - -// SetExtension sets the specified extension of pb to the specified value. -func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { - epb, err := extendable(pb) - if err != nil { - return err - } - if err := checkExtensionTypes(epb, extension); err != nil { - return err - } - typ := reflect.TypeOf(extension.ExtensionType) - if typ != reflect.TypeOf(value) { - return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType) - } - // nil extension values need to be caught early, because the - // encoder can't distinguish an ErrNil due to a nil extension - // from an ErrNil due to a missing field. Extensions are - // always optional, so the encoder would just swallow the error - // and drop all the extensions from the encoded message. - if reflect.ValueOf(value).IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) - } - - extmap := epb.extensionsWrite() - extmap[extension.Field] = Extension{desc: extension, value: value} - return nil -} - -// ClearAllExtensions clears all extensions from pb. -func ClearAllExtensions(pb Message) { - epb, err := extendable(pb) - if err != nil { - return - } - m := epb.extensionsWrite() - for k := range m { - delete(m, k) - } -} - -// A global registry of extensions. -// The generated code will register the generated descriptors by calling RegisterExtension. - -var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) - -// RegisterExtension is called from the generated code. -func RegisterExtension(desc *ExtensionDesc) { - st := reflect.TypeOf(desc.ExtendedType).Elem() - m := extensionMaps[st] - if m == nil { - m = make(map[int32]*ExtensionDesc) - extensionMaps[st] = m - } - if _, ok := m[desc.Field]; ok { - panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) - } - m[desc.Field] = desc -} - -// RegisteredExtensions returns a map of the registered extensions of a -// protocol buffer struct, indexed by the extension number. -// The argument pb should be a nil pointer to the struct type. -func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { - return extensionMaps[reflect.TypeOf(pb).Elem()] -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/lib.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/lib.go deleted file mode 100644 index 175fb8022..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,963 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package proto converts data structures to and from the wire format of -protocol buffers. It works in concert with the Go source code generated -for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed by the enclosing message's name, or by the - enum's type name if it is a top-level enum. Enum types have a String - method, and a Enum method to assist in message construction. - - Nested messages, groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -The simplest way to describe this is to see an example. -Given file test.proto, containing - - package example; - - enum FOO { X = 17; } - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - oneof union { - int32 number = 6; - string name = 7; - } - } - -The resulting file, test.pb.go, is: - - package example - - import proto "github.com/golang/protobuf/proto" - import math "math" - - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", - } - var FOO_value = map[string]int32{ - "X": 17, - } - - func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p - } - func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) - } - func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data) - if err != nil { - return err - } - *x = FOO(value) - return nil - } - - type Test struct { - Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` - Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` - Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` - Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - // Types that are valid to be assigned to Union: - // *Test_Number - // *Test_Name - Union isTest_Union `protobuf_oneof:"union"` - XXX_unrecognized []byte `json:"-"` - } - func (m *Test) Reset() { *m = Test{} } - func (m *Test) String() string { return proto.CompactTextString(m) } - func (*Test) ProtoMessage() {} - - type isTest_Union interface { - isTest_Union() - } - - type Test_Number struct { - Number int32 `protobuf:"varint,6,opt,name=number"` - } - type Test_Name struct { - Name string `protobuf:"bytes,7,opt,name=name"` - } - - func (*Test_Number) isTest_Union() {} - func (*Test_Name) isTest_Union() {} - - func (m *Test) GetUnion() isTest_Union { - if m != nil { - return m.Union - } - return nil - } - const Default_Test_Type int32 = 77 - - func (m *Test) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" - } - - func (m *Test) GetType() int32 { - if m != nil && m.Type != nil { - return *m.Type - } - return Default_Test_Type - } - - func (m *Test) GetOptionalgroup() *Test_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil - } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - } - func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } - func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } - - func (m *Test_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" - } - - func (m *Test) GetNumber() int32 { - if x, ok := m.GetUnion().(*Test_Number); ok { - return x.Number - } - return 0 - } - - func (m *Test) GetName() string { - if x, ok := m.GetUnion().(*Test_Name); ok { - return x.Name - } - return "" - } - - func init() { - proto.RegisterEnum("example.FOO", FOO_name, FOO_value) - } - -To create and play with a Test object: - - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - pb "./example.pb" - ) - - func main() { - test := &pb.Test{ - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &pb.Test_OptionalGroup{ - RequiredField: proto.String("good bye"), - }, - Union: &pb.Test_Name{"fred"}, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &pb.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // Use a type switch to determine which oneof was set. - switch u := test.Union.(type) { - case *pb.Test_Number: // u.Number contains the number. - case *pb.Test_Name: // u.Name contains the string. - } - // etc. - } -*/ -package proto - -import ( - "encoding/json" - "fmt" - "log" - "reflect" - "sort" - "strconv" - "sync" -) - -// RequiredNotSetError is an error type returned by either Marshal or Unmarshal. -// Marshal reports this when a required field is not initialized. -// Unmarshal reports this when a required field is missing from the wire data. -type RequiredNotSetError struct{ field string } - -func (e *RequiredNotSetError) Error() string { - if e.field == "" { - return fmt.Sprintf("proto: required field not set") - } - return fmt.Sprintf("proto: required field %q not set", e.field) -} -func (e *RequiredNotSetError) RequiredNotSet() bool { - return true -} - -type invalidUTF8Error struct{ field string } - -func (e *invalidUTF8Error) Error() string { - if e.field == "" { - return "proto: invalid UTF-8 detected" - } - return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field) -} -func (e *invalidUTF8Error) InvalidUTF8() bool { - return true -} - -// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8. -// This error should not be exposed to the external API as such errors should -// be recreated with the field information. -var errInvalidUTF8 = &invalidUTF8Error{} - -// isNonFatal reports whether the error is either a RequiredNotSet error -// or a InvalidUTF8 error. -func isNonFatal(err error) bool { - if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() { - return true - } - if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() { - return true - } - return false -} - -type nonFatal struct{ E error } - -// Merge merges err into nf and reports whether it was successful. -// Otherwise it returns false for any fatal non-nil errors. -func (nf *nonFatal) Merge(err error) (ok bool) { - if err == nil { - return true // not an error - } - if !isNonFatal(err) { - return false // fatal error - } - if nf.E == nil { - nf.E = err // store first instance of non-fatal error - } - return true -} - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // read point - - deterministic bool -} - -// NewBuffer allocates a new Buffer and initializes its internal data to -// the contents of the argument slice. -func NewBuffer(e []byte) *Buffer { - return &Buffer{buf: e} -} - -// Reset resets the Buffer, ready for marshaling a new protocol buffer. -func (p *Buffer) Reset() { - p.buf = p.buf[0:0] // for reading/writing - p.index = 0 // for reading -} - -// SetBuf replaces the internal buffer with the slice, -// ready for unmarshaling the contents of the slice. -func (p *Buffer) SetBuf(s []byte) { - p.buf = s - p.index = 0 -} - -// Bytes returns the contents of the Buffer. -func (p *Buffer) Bytes() []byte { return p.buf } - -// SetDeterministic sets whether to use deterministic serialization. -// -// Deterministic serialization guarantees that for a given binary, equal -// messages will always be serialized to the same bytes. This implies: -// -// - Repeated serialization of a message will return the same bytes. -// - Different processes of the same binary (which may be executing on -// different machines) will serialize equal messages to the same bytes. -// -// Note that the deterministic serialization is NOT canonical across -// languages. It is not guaranteed to remain stable over time. It is unstable -// across different builds with schema changes due to unknown fields. -// Users who need canonical serialization (e.g., persistent storage in a -// canonical form, fingerprinting, etc.) should define their own -// canonicalization specification and implement their own serializer rather -// than relying on this API. -// -// If deterministic serialization is requested, map entries will be sorted -// by keys in lexographical order. This is an implementation detail and -// subject to change. -func (p *Buffer) SetDeterministic(deterministic bool) { - p.deterministic = deterministic -} - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { - return &v -} - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { - return &v -} - -// Int is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it, but unlike Int32 -// its argument value is an int. -func Int(v int) *int32 { - p := new(int32) - *p = int32(v) - return p -} - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { - return &v -} - -// Float32 is a helper routine that allocates a new float32 value -// to store v and returns a pointer to it. -func Float32(v float32) *float32 { - return &v -} - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { - return &v -} - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { - return &v -} - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { - return &v -} - -// EnumName is a helper function to simplify printing protocol buffer enums -// by name. Given an enum map and a value, it returns a useful string. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// UnmarshalJSONEnum is a helper function to simplify recovering enum int values -// from their JSON-encoded representation. Given a map from the enum's symbolic -// names to its int values, and a byte buffer containing the JSON-encoded -// value, it returns an int32 that can be cast to the enum type by the caller. -// -// The function can deal with both JSON representations, numeric and symbolic. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// DebugPrint dumps the encoded data in b in a debugging format with a header -// including the string s. Used in testing but made available for general debugging. -func (p *Buffer) DebugPrint(s string, b []byte) { - var u uint64 - - obuf := p.buf - index := p.index - p.buf = b - p.index = 0 - depth := 0 - - fmt.Printf("\n--- %s ---\n", s) - -out: - for { - for i := 0; i < depth; i++ { - fmt.Print(" ") - } - - index := p.index - if index == len(p.buf) { - break - } - - op, err := p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: fetching op err %v\n", index, err) - break out - } - tag := op >> 3 - wire := op & 7 - - switch wire { - default: - fmt.Printf("%3d: t=%3d unknown wire=%d\n", - index, tag, wire) - break out - - case WireBytes: - var r []byte - - r, err = p.DecodeRawBytes(false) - if err != nil { - break out - } - fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) - if len(r) <= 6 { - for i := 0; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } else { - for i := 0; i < 3; i++ { - fmt.Printf(" %.2x", r[i]) - } - fmt.Printf(" ..") - for i := len(r) - 3; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } - fmt.Printf("\n") - - case WireFixed32: - u, err = p.DecodeFixed32() - if err != nil { - fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) - - case WireFixed64: - u, err = p.DecodeFixed64() - if err != nil { - fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - - case WireVarint: - u, err = p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) - - case WireStartGroup: - fmt.Printf("%3d: t=%3d start\n", index, tag) - depth++ - - case WireEndGroup: - depth-- - fmt.Printf("%3d: t=%3d end\n", index, tag) - } - } - - if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) - } - fmt.Printf("\n") - - p.buf = obuf - p.index = index -} - -// SetDefaults sets unset protocol buffer fields to their default values. -// It only modifies fields that are both unset and have defined defaults. -// It recursively sets default values in any non-nil sub-messages. -func SetDefaults(pb Message) { - setDefaults(reflect.ValueOf(pb), true, false) -} - -// v is a pointer to a struct. -func setDefaults(v reflect.Value, recur, zeros bool) { - v = v.Elem() - - defaultMu.RLock() - dm, ok := defaults[v.Type()] - defaultMu.RUnlock() - if !ok { - dm = buildDefaultMessage(v.Type()) - defaultMu.Lock() - defaults[v.Type()] = dm - defaultMu.Unlock() - } - - for _, sf := range dm.scalars { - f := v.Field(sf.index) - if !f.IsNil() { - // field already set - continue - } - dv := sf.value - if dv == nil && !zeros { - // no explicit default, and don't want to set zeros - continue - } - fptr := f.Addr().Interface() // **T - // TODO: Consider batching the allocations we do here. - switch sf.kind { - case reflect.Bool: - b := new(bool) - if dv != nil { - *b = dv.(bool) - } - *(fptr.(**bool)) = b - case reflect.Float32: - f := new(float32) - if dv != nil { - *f = dv.(float32) - } - *(fptr.(**float32)) = f - case reflect.Float64: - f := new(float64) - if dv != nil { - *f = dv.(float64) - } - *(fptr.(**float64)) = f - case reflect.Int32: - // might be an enum - if ft := f.Type(); ft != int32PtrType { - // enum - f.Set(reflect.New(ft.Elem())) - if dv != nil { - f.Elem().SetInt(int64(dv.(int32))) - } - } else { - // int32 field - i := new(int32) - if dv != nil { - *i = dv.(int32) - } - *(fptr.(**int32)) = i - } - case reflect.Int64: - i := new(int64) - if dv != nil { - *i = dv.(int64) - } - *(fptr.(**int64)) = i - case reflect.String: - s := new(string) - if dv != nil { - *s = dv.(string) - } - *(fptr.(**string)) = s - case reflect.Uint8: - // exceptional case: []byte - var b []byte - if dv != nil { - db := dv.([]byte) - b = make([]byte, len(db)) - copy(b, db) - } else { - b = []byte{} - } - *(fptr.(*[]byte)) = b - case reflect.Uint32: - u := new(uint32) - if dv != nil { - *u = dv.(uint32) - } - *(fptr.(**uint32)) = u - case reflect.Uint64: - u := new(uint64) - if dv != nil { - *u = dv.(uint64) - } - *(fptr.(**uint64)) = u - default: - log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) - } - } - - for _, ni := range dm.nested { - f := v.Field(ni) - // f is *T or []*T or map[T]*T - switch f.Kind() { - case reflect.Ptr: - if f.IsNil() { - continue - } - setDefaults(f, recur, zeros) - - case reflect.Slice: - for i := 0; i < f.Len(); i++ { - e := f.Index(i) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - - case reflect.Map: - for _, k := range f.MapKeys() { - e := f.MapIndex(k) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - } - } -} - -var ( - // defaults maps a protocol buffer struct type to a slice of the fields, - // with its scalar fields set to their proto-declared non-zero default values. - defaultMu sync.RWMutex - defaults = make(map[reflect.Type]defaultMessage) - - int32PtrType = reflect.TypeOf((*int32)(nil)) -) - -// defaultMessage represents information about the default values of a message. -type defaultMessage struct { - scalars []scalarField - nested []int // struct field index of nested messages -} - -type scalarField struct { - index int // struct field index - kind reflect.Kind // element type (the T in *T or []T) - value interface{} // the proto-declared default value, or nil -} - -// t is a struct type. -func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { - sprop := GetProperties(t) - for _, prop := range sprop.Prop { - fi, ok := sprop.decoderTags.get(prop.Tag) - if !ok { - // XXX_unrecognized - continue - } - ft := t.Field(fi).Type - - sf, nested, err := fieldDefault(ft, prop) - switch { - case err != nil: - log.Print(err) - case nested: - dm.nested = append(dm.nested, fi) - case sf != nil: - sf.index = fi - dm.scalars = append(dm.scalars, *sf) - } - } - - return dm -} - -// fieldDefault returns the scalarField for field type ft. -// sf will be nil if the field can not have a default. -// nestedMessage will be true if this is a nested message. -// Note that sf.index is not set on return. -func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { - var canHaveDefault bool - switch ft.Kind() { - case reflect.Ptr: - if ft.Elem().Kind() == reflect.Struct { - nestedMessage = true - } else { - canHaveDefault = true // proto2 scalar field - } - - case reflect.Slice: - switch ft.Elem().Kind() { - case reflect.Ptr: - nestedMessage = true // repeated message - case reflect.Uint8: - canHaveDefault = true // bytes field - } - - case reflect.Map: - if ft.Elem().Kind() == reflect.Ptr { - nestedMessage = true // map with message values - } - } - - if !canHaveDefault { - if nestedMessage { - return nil, true, nil - } - return nil, false, nil - } - - // We now know that ft is a pointer or slice. - sf = &scalarField{kind: ft.Elem().Kind()} - - // scalar fields without defaults - if !prop.HasDefault { - return sf, false, nil - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) - } - sf.value = x - default: - return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) - } - - return sf, false, nil -} - -// mapKeys returns a sort.Interface to be used for sorting the map keys. -// Map fields may have key types of non-float scalars, strings and enums. -func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{vs: vs} - - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. - if len(vs) == 0 { - return s - } - switch vs[0].Kind() { - case reflect.Int32, reflect.Int64: - s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } - case reflect.Uint32, reflect.Uint64: - s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } - case reflect.Bool: - s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true - case reflect.String: - s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } - default: - panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) - } - - return s -} - -type mapKeySorter struct { - vs []reflect.Value - less func(a, b reflect.Value) bool -} - -func (s mapKeySorter) Len() int { return len(s.vs) } -func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } -func (s mapKeySorter) Less(i, j int) bool { - return s.less(s.vs[i], s.vs[j]) -} - -// isProto3Zero reports whether v is a zero proto3 value. -func isProto3Zero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint32, reflect.Uint64: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.String: - return v.String() == "" - } - return false -} - -// ProtoPackageIsVersion2 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion2 = true - -// ProtoPackageIsVersion1 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion1 = true - -// InternalMessageInfo is a type used internally by generated .pb.go files. -// This type is not intended to be used by non-generated code. -// This type is not subject to any compatibility guarantee. -type InternalMessageInfo struct { - marshal *marshalInfo - unmarshal *unmarshalInfo - merge *mergeInfo - discard *discardInfo -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/message_set.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/message_set.go deleted file mode 100644 index c504d2fc3..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,318 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Support for message sets. - */ - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" - "sync" -) - -// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. -// A message type ID is required for storing a protocol buffer in a message set. -var errNoMessageTypeID = errors.New("proto does not have a message type ID") - -// The first two types (_MessageSet_Item and messageSet) -// model what the protocol compiler produces for the following protocol message: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } -// That is the MessageSet wire format. We can't use a proto to generate these -// because that would introduce a circular dependency between it and this package. - -type _MessageSet_Item struct { - TypeId *int32 `protobuf:"varint,2,req,name=type_id"` - Message []byte `protobuf:"bytes,3,req,name=message"` -} - -type messageSet struct { - Item []*_MessageSet_Item `protobuf:"group,1,rep"` - XXX_unrecognized []byte - // TODO: caching? -} - -// Make sure messageSet is a Message. -var _ Message = (*messageSet)(nil) - -// messageTypeIder is an interface satisfied by a protocol buffer type -// that may be stored in a MessageSet. -type messageTypeIder interface { - MessageTypeId() int32 -} - -func (ms *messageSet) find(pb Message) *_MessageSet_Item { - mti, ok := pb.(messageTypeIder) - if !ok { - return nil - } - id := mti.MessageTypeId() - for _, item := range ms.Item { - if *item.TypeId == id { - return item - } - } - return nil -} - -func (ms *messageSet) Has(pb Message) bool { - return ms.find(pb) != nil -} - -func (ms *messageSet) Unmarshal(pb Message) error { - if item := ms.find(pb); item != nil { - return Unmarshal(item.Message, pb) - } - if _, ok := pb.(messageTypeIder); !ok { - return errNoMessageTypeID - } - return nil // TODO: return error instead? -} - -func (ms *messageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return errNoMessageTypeID - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -func (ms *messageSet) Reset() { *ms = messageSet{} } -func (ms *messageSet) String() string { return CompactTextString(ms) } -func (*messageSet) ProtoMessage() {} - -// Support for the message_set_wire_format message option. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// MarshalMessageSet encodes the extension map represented by m in the message set wire format. -// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSet(exts interface{}) ([]byte, error) { - return marshalMessageSet(exts, false) -} - -// marshaMessageSet implements above function, with the opt to turn on / off deterministic during Marshal. -func marshalMessageSet(exts interface{}, deterministic bool) ([]byte, error) { - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var u marshalInfo - siz := u.sizeMessageSet(exts) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, exts, deterministic) - - case map[int32]Extension: - // This is an old-style extension map. - // Wrap it in a new-style XXX_InternalExtensions. - ie := XXX_InternalExtensions{ - p: &struct { - mu sync.Mutex - extensionMap map[int32]Extension - }{ - extensionMap: exts, - }, - } - - var u marshalInfo - siz := u.sizeMessageSet(&ie) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, &ie, deterministic) - - default: - return nil, errors.New("proto: not an extension map") - } -} - -// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSet(buf []byte, exts interface{}) error { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - m = exts.extensionsWrite() - case map[int32]Extension: - m = exts - default: - return errors.New("proto: not an extension map") - } - - ms := new(messageSet) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} - -// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. -// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var mu sync.Locker - m, mu = exts.extensionsRead() - if m != nil { - // Keep the extensions map locked until we're done marshaling to prevent - // races between marshaling and unmarshaling the lazily-{en,de}coded - // values. - mu.Lock() - defer mu.Unlock() - } - case map[int32]Extension: - m = exts - default: - return nil, errors.New("proto: not an extension map") - } - var b bytes.Buffer - b.WriteByte('{') - - // Process the map in key order for deterministic output. - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) // int32Slice defined in text.go - - for i, id := range ids { - ext := m[id] - msd, ok := messageSetMap[id] - if !ok { - // Unknown type; we can't render it, so skip it. - continue - } - - if i > 0 && b.Len() > 1 { - b.WriteByte(',') - } - - fmt.Fprintf(&b, `"[%s]":`, msd.name) - - x := ext.value - if x == nil { - x = reflect.New(msd.t.Elem()).Interface() - if err := Unmarshal(ext.enc, x.(Message)); err != nil { - return nil, err - } - } - d, err := json.Marshal(x) - if err != nil { - return nil, err - } - b.Write(d) - } - b.WriteByte('}') - return b.Bytes(), nil -} - -// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. -// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { - // Common-case fast path. - if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { - return nil - } - - // This is fairly tricky, and it's not clear that it is needed. - return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") -} - -// A global registry of types that can be used in a MessageSet. - -var messageSetMap = make(map[int32]messageSetDesc) - -type messageSetDesc struct { - t reflect.Type // pointer to struct - name string -} - -// RegisterMessageSetType is called from the generated code. -func RegisterMessageSetType(m Message, fieldNum int32, name string) { - messageSetMap[fieldNum] = messageSetDesc{ - t: reflect.TypeOf(m), - name: name, - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100644 index 1239fa018..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,361 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build purego appengine js - -// This file contains an implementation of proto field accesses using package reflect. -// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can -// be used on App Engine. - -package proto - -import ( - "reflect" - "sync" -) - -const unsafeAllowed = false - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by the sequence of field indices -// passed to reflect's FieldByIndex. -type field []int - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return f.Index -} - -// invalidField is an invalid field identifier. -var invalidField = field(nil) - -// zeroField is a noop when calling pointer.offset. -var zeroField = field([]int{}) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// The pointer type is for the table-driven decoder. -// The implementation here uses a reflect.Value of pointer type to -// create a generic pointer. In pointer_unsafe.go we use unsafe -// instead of reflect to implement the same (but faster) interface. -type pointer struct { - v reflect.Value -} - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - return pointer{v: reflect.ValueOf(*i)} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr bool) pointer { - v := reflect.ValueOf(*i) - u := reflect.New(v.Type()) - u.Elem().Set(v) - return pointer{v: u} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{v: v} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} -} - -func (p pointer) isNil() bool { - return p.v.IsNil() -} - -// grow updates the slice s in place to make it one element longer. -// s must be addressable. -// Returns the (addressable) new element. -func grow(s reflect.Value) reflect.Value { - n, m := s.Len(), s.Cap() - if n < m { - s.SetLen(n + 1) - } else { - s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) - } - return s.Index(n) -} - -func (p pointer) toInt64() *int64 { - return p.v.Interface().(*int64) -} -func (p pointer) toInt64Ptr() **int64 { - return p.v.Interface().(**int64) -} -func (p pointer) toInt64Slice() *[]int64 { - return p.v.Interface().(*[]int64) -} - -var int32ptr = reflect.TypeOf((*int32)(nil)) - -func (p pointer) toInt32() *int32 { - return p.v.Convert(int32ptr).Interface().(*int32) -} - -// The toInt32Ptr/Slice methods don't work because of enums. -// Instead, we must use set/get methods for the int32ptr/slice case. -/* - func (p pointer) toInt32Ptr() **int32 { - return p.v.Interface().(**int32) -} - func (p pointer) toInt32Slice() *[]int32 { - return p.v.Interface().(*[]int32) -} -*/ -func (p pointer) getInt32Ptr() *int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().(*int32) - } - // an enum - return p.v.Elem().Convert(int32PtrType).Interface().(*int32) -} -func (p pointer) setInt32Ptr(v int32) { - // Allocate value in a *int32. Possibly convert that to a *enum. - // Then assign it to a **int32 or **enum. - // Note: we can convert *int32 to *enum, but we can't convert - // **int32 to **enum! - p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) -} - -// getInt32Slice copies []int32 from p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getInt32Slice() []int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().([]int32) - } - // an enum - // Allocate a []int32, then assign []enum's values into it. - // Note: we can't convert []enum to []int32. - slice := p.v.Elem() - s := make([]int32, slice.Len()) - for i := 0; i < slice.Len(); i++ { - s[i] = int32(slice.Index(i).Int()) - } - return s -} - -// setInt32Slice copies []int32 into p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setInt32Slice(v []int32) { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - p.v.Elem().Set(reflect.ValueOf(v)) - return - } - // an enum - // Allocate a []enum, then assign []int32's values into it. - // Note: we can't convert []enum to []int32. - slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) - for i, x := range v { - slice.Index(i).SetInt(int64(x)) - } - p.v.Elem().Set(slice) -} -func (p pointer) appendInt32Slice(v int32) { - grow(p.v.Elem()).SetInt(int64(v)) -} - -func (p pointer) toUint64() *uint64 { - return p.v.Interface().(*uint64) -} -func (p pointer) toUint64Ptr() **uint64 { - return p.v.Interface().(**uint64) -} -func (p pointer) toUint64Slice() *[]uint64 { - return p.v.Interface().(*[]uint64) -} -func (p pointer) toUint32() *uint32 { - return p.v.Interface().(*uint32) -} -func (p pointer) toUint32Ptr() **uint32 { - return p.v.Interface().(**uint32) -} -func (p pointer) toUint32Slice() *[]uint32 { - return p.v.Interface().(*[]uint32) -} -func (p pointer) toBool() *bool { - return p.v.Interface().(*bool) -} -func (p pointer) toBoolPtr() **bool { - return p.v.Interface().(**bool) -} -func (p pointer) toBoolSlice() *[]bool { - return p.v.Interface().(*[]bool) -} -func (p pointer) toFloat64() *float64 { - return p.v.Interface().(*float64) -} -func (p pointer) toFloat64Ptr() **float64 { - return p.v.Interface().(**float64) -} -func (p pointer) toFloat64Slice() *[]float64 { - return p.v.Interface().(*[]float64) -} -func (p pointer) toFloat32() *float32 { - return p.v.Interface().(*float32) -} -func (p pointer) toFloat32Ptr() **float32 { - return p.v.Interface().(**float32) -} -func (p pointer) toFloat32Slice() *[]float32 { - return p.v.Interface().(*[]float32) -} -func (p pointer) toString() *string { - return p.v.Interface().(*string) -} -func (p pointer) toStringPtr() **string { - return p.v.Interface().(**string) -} -func (p pointer) toStringSlice() *[]string { - return p.v.Interface().(*[]string) -} -func (p pointer) toBytes() *[]byte { - return p.v.Interface().(*[]byte) -} -func (p pointer) toBytesSlice() *[][]byte { - return p.v.Interface().(*[][]byte) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return p.v.Interface().(*XXX_InternalExtensions) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return p.v.Interface().(*map[int32]Extension) -} -func (p pointer) getPointer() pointer { - return pointer{v: p.v.Elem()} -} -func (p pointer) setPointer(q pointer) { - p.v.Elem().Set(q.v) -} -func (p pointer) appendPointer(q pointer) { - grow(p.v.Elem()).Set(q.v) -} - -// getPointerSlice copies []*T from p as a new []pointer. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getPointerSlice() []pointer { - if p.v.IsNil() { - return nil - } - n := p.v.Elem().Len() - s := make([]pointer, n) - for i := 0; i < n; i++ { - s[i] = pointer{v: p.v.Elem().Index(i)} - } - return s -} - -// setPointerSlice copies []pointer into p as a new []*T. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setPointerSlice(v []pointer) { - if v == nil { - p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) - return - } - s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) - for _, p := range v { - s = reflect.Append(s, p.v) - } - p.v.Elem().Set(s) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - if p.v.Elem().IsNil() { - return pointer{v: p.v.Elem()} - } - return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct -} - -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - // TODO: check that p.v.Type().Elem() == t? - return p.v -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} - -var atomicLock sync.Mutex diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100644 index bdc9a3609..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,312 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build !purego,!appengine,!js - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "sync/atomic" - "unsafe" -) - -const unsafeAllowed = true - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by its byte offset from the start of the struct. -type field uintptr - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return field(f.Offset) -} - -// invalidField is an invalid field identifier. -const invalidField = ^field(0) - -// zeroField is a noop when calling pointer.offset. -const zeroField = field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != invalidField -} - -// The pointer type below is for the new table-driven encoder/decoder. -// The implementation here uses unsafe.Pointer to create a generic pointer. -// In pointer_reflect.go we use reflect instead of unsafe to implement -// the same (but slower) interface. -type pointer struct { - p unsafe.Pointer -} - -// size of pointer -var ptrSize = unsafe.Sizeof(uintptr(0)) - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - // Super-tricky - read pointer out of data word of interface value. - // Saves ~25ns over the equivalent: - // return valToPointer(reflect.ValueOf(*i)) - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr bool) pointer { - // Super-tricky - read or get the address of data word of interface value. - if isptr { - // The interface is of pointer type, thus it is a direct interface. - // The data word is the pointer data itself. We take its address. - return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} - } - // The interface is not of pointer type. The data word is the pointer - // to the data. - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{p: unsafe.Pointer(v.Pointer())} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - // For safety, we should panic if !f.IsValid, however calling panic causes - // this to no longer be inlineable, which is a serious performance cost. - /* - if !f.IsValid() { - panic("invalid field") - } - */ - return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} -} - -func (p pointer) isNil() bool { - return p.p == nil -} - -func (p pointer) toInt64() *int64 { - return (*int64)(p.p) -} -func (p pointer) toInt64Ptr() **int64 { - return (**int64)(p.p) -} -func (p pointer) toInt64Slice() *[]int64 { - return (*[]int64)(p.p) -} -func (p pointer) toInt32() *int32 { - return (*int32)(p.p) -} - -// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. -/* - func (p pointer) toInt32Ptr() **int32 { - return (**int32)(p.p) - } - func (p pointer) toInt32Slice() *[]int32 { - return (*[]int32)(p.p) - } -*/ -func (p pointer) getInt32Ptr() *int32 { - return *(**int32)(p.p) -} -func (p pointer) setInt32Ptr(v int32) { - *(**int32)(p.p) = &v -} - -// getInt32Slice loads a []int32 from p. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getInt32Slice() []int32 { - return *(*[]int32)(p.p) -} - -// setInt32Slice stores a []int32 to p. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setInt32Slice(v []int32) { - *(*[]int32)(p.p) = v -} - -// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? -func (p pointer) appendInt32Slice(v int32) { - s := (*[]int32)(p.p) - *s = append(*s, v) -} - -func (p pointer) toUint64() *uint64 { - return (*uint64)(p.p) -} -func (p pointer) toUint64Ptr() **uint64 { - return (**uint64)(p.p) -} -func (p pointer) toUint64Slice() *[]uint64 { - return (*[]uint64)(p.p) -} -func (p pointer) toUint32() *uint32 { - return (*uint32)(p.p) -} -func (p pointer) toUint32Ptr() **uint32 { - return (**uint32)(p.p) -} -func (p pointer) toUint32Slice() *[]uint32 { - return (*[]uint32)(p.p) -} -func (p pointer) toBool() *bool { - return (*bool)(p.p) -} -func (p pointer) toBoolPtr() **bool { - return (**bool)(p.p) -} -func (p pointer) toBoolSlice() *[]bool { - return (*[]bool)(p.p) -} -func (p pointer) toFloat64() *float64 { - return (*float64)(p.p) -} -func (p pointer) toFloat64Ptr() **float64 { - return (**float64)(p.p) -} -func (p pointer) toFloat64Slice() *[]float64 { - return (*[]float64)(p.p) -} -func (p pointer) toFloat32() *float32 { - return (*float32)(p.p) -} -func (p pointer) toFloat32Ptr() **float32 { - return (**float32)(p.p) -} -func (p pointer) toFloat32Slice() *[]float32 { - return (*[]float32)(p.p) -} -func (p pointer) toString() *string { - return (*string)(p.p) -} -func (p pointer) toStringPtr() **string { - return (**string)(p.p) -} -func (p pointer) toStringSlice() *[]string { - return (*[]string)(p.p) -} -func (p pointer) toBytes() *[]byte { - return (*[]byte)(p.p) -} -func (p pointer) toBytesSlice() *[][]byte { - return (*[][]byte)(p.p) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(p.p) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return (*map[int32]Extension)(p.p) -} - -// getPointerSlice loads []*T from p as a []pointer. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getPointerSlice() []pointer { - // Super-tricky - p should point to a []*T where T is a - // message type. We load it as []pointer. - return *(*[]pointer)(p.p) -} - -// setPointerSlice stores []pointer into p as a []*T. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setPointerSlice(v []pointer) { - // Super-tricky - p should point to a []*T where T is a - // message type. We store it as []pointer. - *(*[]pointer)(p.p) = v -} - -// getPointer loads the pointer at p and returns it. -func (p pointer) getPointer() pointer { - return pointer{p: *(*unsafe.Pointer)(p.p)} -} - -// setPointer stores the pointer q at p. -func (p pointer) setPointer(q pointer) { - *(*unsafe.Pointer)(p.p) = q.p -} - -// append q to the slice pointed to by p. -func (p pointer) appendPointer(q pointer) { - s := (*[]unsafe.Pointer)(p.p) - *s = append(*s, q.p) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - // Super-tricky - read pointer out of data word of interface value. - return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} -} - -// asPointerTo returns a reflect.Value that is a pointer to an -// object of type t stored at p. -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - return reflect.NewAt(t, p.p) -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/properties.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index 1e3818744..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,539 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "fmt" - "log" - "os" - "reflect" - "sort" - "strconv" - "strings" - "sync" -) - -const debug bool = false - -// Constants that identify the encoding of a value on the wire. -const ( - WireVarint = 0 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 - WireFixed32 = 5 -) - -// tagMap is an optimization over map[int]int for typical protocol buffer -// use-cases. Encoded protocol buffers are often in tag order with small tag -// numbers. -type tagMap struct { - fastTags []int - slowTags map[int]int -} - -// tagMapFastLimit is the upper bound on the tag number that will be stored in -// the tagMap slice rather than its map. -const tagMapFastLimit = 1024 - -func (p *tagMap) get(t int) (int, bool) { - if t > 0 && t < tagMapFastLimit { - if t >= len(p.fastTags) { - return 0, false - } - fi := p.fastTags[t] - return fi, fi >= 0 - } - fi, ok := p.slowTags[t] - return fi, ok -} - -func (p *tagMap) put(t int, fi int) { - if t > 0 && t < tagMapFastLimit { - for len(p.fastTags) < t+1 { - p.fastTags = append(p.fastTags, -1) - } - p.fastTags[t] = fi - return - } - if p.slowTags == nil { - p.slowTags = make(map[int]int) - } - p.slowTags[t] = fi -} - -// StructProperties represents properties for all the fields of a struct. -// decoderTags and decoderOrigNames should only be used by the decoder. -type StructProperties struct { - Prop []*Properties // properties for each field - reqCount int // required count - decoderTags tagMap // map from proto tag to struct field number - decoderOrigNames map[string]int // map from original name to struct field number - order []int // list of struct field numbers in tag order - - // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the original name of a field. - OneofTypes map[string]*OneofProperties -} - -// OneofProperties represents information about a specific field in a oneof. -type OneofProperties struct { - Type reflect.Type // pointer to generated struct type for this oneof field - Field int // struct field number of the containing oneof in the message - Prop *Properties -} - -// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. -type Properties struct { - Name string // name of the field, for error messages - OrigName string // original name before protocol compiler (always set) - JSONName string // name to use for JSON; determined by protoc - Wire string - WireType int - Tag int - Required bool - Optional bool - Repeated bool - Packed bool // relevant for repeated primitives only - Enum string // set for enum types only - proto3 bool // whether this is known to be a proto3 field - oneof bool // whether this is a oneof field - - Default string // default value - HasDefault bool // whether an explicit default was provided - - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - - mtype reflect.Type // set for map types only - MapKeyProp *Properties // set for map types only - MapValProp *Properties // set for map types only -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s += "," - s += strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - s += ",name=" + p.OrigName - if p.JSONName != p.OrigName { - s += ",json=" + p.JSONName - } - if p.proto3 { - s += ",proto3" - } - if p.oneof { - s += ",oneof" - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - case "fixed32": - p.WireType = WireFixed32 - case "fixed64": - p.WireType = WireFixed64 - case "zigzag32": - p.WireType = WireVarint - case "zigzag64": - p.WireType = WireVarint - case "bytes", "group": - p.WireType = WireBytes - // no numeric converter for non-numeric types - default: - fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) - return - } - - var err error - p.Tag, err = strconv.Atoi(fields[1]) - if err != nil { - return - } - -outer: - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": - p.Optional = true - case f == "rep": - p.Repeated = true - case f == "packed": - p.Packed = true - case strings.HasPrefix(f, "name="): - p.OrigName = f[5:] - case strings.HasPrefix(f, "json="): - p.JSONName = f[5:] - case strings.HasPrefix(f, "enum="): - p.Enum = f[5:] - case f == "proto3": - p.proto3 = true - case f == "oneof": - p.oneof = true - case strings.HasPrefix(f, "def="): - p.HasDefault = true - p.Default = f[4:] // rest of string - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break outer - } - } - } -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// setFieldProps initializes the field properties for submessages and maps. -func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - switch t1 := typ; t1.Kind() { - case reflect.Ptr: - if t1.Elem().Kind() == reflect.Struct { - p.stype = t1.Elem() - } - - case reflect.Slice: - if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct { - p.stype = t2.Elem() - } - - case reflect.Map: - p.mtype = t1 - p.MapKeyProp = &Properties{} - p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.MapValProp = &Properties{} - vtype := p.mtype.Elem() - if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { - // The value type is not a message (*T) or bytes ([]byte), - // so we need encoders for the pointer to this type. - vtype = reflect.PtrTo(vtype) - } - p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() -) - -// Init populates the properties from a protocol buffer struct tag. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.init(typ, name, tag, f, true) -} - -func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { - // "bytes,49,opt,def=hello!" - p.Name = name - p.OrigName = name - if tag == "" { - return - } - p.Parse(tag) - p.setFieldProps(typ, f, lockGetProp) -} - -var ( - propertiesMu sync.RWMutex - propertiesMap = make(map[reflect.Type]*StructProperties) -) - -// GetProperties returns the list of properties for the type represented by t. -// t must represent a generated struct type of a protocol message. -func GetProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic("proto: type must have kind struct") - } - - // Most calls to GetProperties in a long-running program will be - // retrieving details for types we have seen before. - propertiesMu.RLock() - sprop, ok := propertiesMap[t] - propertiesMu.RUnlock() - if ok { - return sprop - } - - propertiesMu.Lock() - sprop = getPropertiesLocked(t) - propertiesMu.Unlock() - return sprop -} - -// getPropertiesLocked requires that propertiesMu is held. -func getPropertiesLocked(t reflect.Type) *StructProperties { - if prop, ok := propertiesMap[t]; ok { - return prop - } - - prop := new(StructProperties) - // in case of recursive protos, fill this in now. - propertiesMap[t] = prop - - // build properties - prop.Prop = make([]*Properties, t.NumField()) - prop.order = make([]int, t.NumField()) - - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - p := new(Properties) - name := f.Name - p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - - oneof := f.Tag.Get("protobuf_oneof") // special case - if oneof != "" { - // Oneof fields don't use the traditional protobuf tag. - p.OrigName = oneof - } - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") - } - } - - // Re-order prop.order. - sort.Sort(prop) - - type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) - } - if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - var oots []interface{} - _, _, _, oots = om.XXX_OneofFuncs() - - // Interpret oneof metadata. - prop.OneofTypes = make(map[string]*OneofProperties) - for _, oot := range oots { - oop := &OneofProperties{ - Type: reflect.ValueOf(oot).Type(), // *T - Prop: new(Properties), - } - sft := oop.Type.Elem().Field(0) - oop.Prop.Name = sft.Name - oop.Prop.Parse(sft.Tag.Get("protobuf")) - // There will be exactly one interface field that - // this new value is assignable to. - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if f.Type.Kind() != reflect.Interface { - continue - } - if !oop.Type.AssignableTo(f.Type) { - continue - } - oop.Field = i - break - } - prop.OneofTypes[oop.Prop.OrigName] = oop - } - } - - // build required counts - // build tags - reqCount := 0 - prop.decoderOrigNames = make(map[string]int) - for i, p := range prop.Prop { - if strings.HasPrefix(p.Name, "XXX_") { - // Internal fields should not appear in tags/origNames maps. - // They are handled specially when encoding and decoding. - continue - } - if p.Required { - reqCount++ - } - prop.decoderTags.put(p.Tag, i) - prop.decoderOrigNames[p.OrigName] = i - } - prop.reqCount = reqCount - - return prop -} - -// A global registry of enum types. -// The generated code will register the generated maps by calling RegisterEnum. - -var enumValueMaps = make(map[string]map[string]int32) - -// RegisterEnum is called from the generated code to install the enum descriptor -// maps into the global table to aid parsing text format protocol buffers. -func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { - if _, ok := enumValueMaps[typeName]; ok { - panic("proto: duplicate enum registered: " + typeName) - } - enumValueMaps[typeName] = valueMap -} - -// EnumValueMap returns the mapping from names to integers of the -// enum type enumType, or a nil if not found. -func EnumValueMap(enumType string) map[string]int32 { - return enumValueMaps[enumType] -} - -// A registry of all linked message types. -// The string is a fully-qualified proto name ("pkg.Message"). -var ( - protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers - protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types - revProtoTypes = make(map[reflect.Type]string) -) - -// RegisterType is called from generated code and maps from the fully qualified -// proto name to the type (pointer to struct) of the protocol buffer. -func RegisterType(x Message, name string) { - if _, ok := protoTypedNils[name]; ok { - // TODO: Some day, make this a panic. - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { - // Generated code always calls RegisterType with nil x. - // This check is just for extra safety. - protoTypedNils[name] = x - } else { - protoTypedNils[name] = reflect.Zero(t).Interface().(Message) - } - revProtoTypes[t] = name -} - -// RegisterMapType is called from generated code and maps from the fully qualified -// proto name to the native map type of the proto map definition. -func RegisterMapType(x interface{}, name string) { - if reflect.TypeOf(x).Kind() != reflect.Map { - panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) - } - if _, ok := protoMapTypes[name]; ok { - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - protoMapTypes[name] = t - revProtoTypes[t] = name -} - -// MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { - type xname interface { - XXX_MessageName() string - } - if m, ok := x.(xname); ok { - return m.XXX_MessageName() - } - return revProtoTypes[reflect.TypeOf(x)] -} - -// MessageType returns the message type (pointer to struct) for a named message. -// The type is not guaranteed to implement proto.Message if the name refers to a -// map entry. -func MessageType(name string) reflect.Type { - if t, ok := protoTypedNils[name]; ok { - return reflect.TypeOf(t) - } - return protoMapTypes[name] -} - -// A registry of all linked proto files. -var ( - protoFiles = make(map[string][]byte) // file name => fileDescriptor -) - -// RegisterFile is called from generated code and maps from the -// full file name of a .proto file to its compressed FileDescriptorProto. -func RegisterFile(filename string, fileDescriptor []byte) { - protoFiles[filename] = fileDescriptor -} - -// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. -func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_marshal.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_marshal.go deleted file mode 100644 index 4393779f2..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_marshal.go +++ /dev/null @@ -1,2771 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// a sizer takes a pointer to a field and the size of its tag, computes the size of -// the encoded data. -type sizer func(pointer, int) int - -// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), -// marshals the field to the end of the slice, returns the slice and error (if any). -type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) - -// marshalInfo is the information used for marshaling a message. -type marshalInfo struct { - typ reflect.Type - fields []*marshalFieldInfo - unrecognized field // offset of XXX_unrecognized - extensions field // offset of XXX_InternalExtensions - v1extensions field // offset of XXX_extensions - sizecache field // offset of XXX_sizecache - initialized int32 // 0 -- only typ is set, 1 -- fully initialized - messageset bool // uses message set wire format - hasmarshaler bool // has custom marshaler - sync.RWMutex // protect extElems map, also for initialization - extElems map[int32]*marshalElemInfo // info of extension elements -} - -// marshalFieldInfo is the information used for marshaling a field of a message. -type marshalFieldInfo struct { - field field - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isPointer bool - required bool // field is required - name string // name of the field, for error reporting - oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements -} - -// marshalElemInfo is the information used for marshaling an extension or oneof element. -type marshalElemInfo struct { - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) -} - -var ( - marshalInfoMap = map[reflect.Type]*marshalInfo{} - marshalInfoLock sync.Mutex -) - -// getMarshalInfo returns the information to marshal a given type of message. -// The info it returns may not necessarily initialized. -// t is the type of the message (NOT the pointer to it). -func getMarshalInfo(t reflect.Type) *marshalInfo { - marshalInfoLock.Lock() - u, ok := marshalInfoMap[t] - if !ok { - u = &marshalInfo{typ: t} - marshalInfoMap[t] = u - } - marshalInfoLock.Unlock() - return u -} - -// Size is the entry point from generated code, -// and should be ONLY called by generated code. -// It computes the size of encoded data of msg. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Size(msg Message) int { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return 0 - } - return u.size(ptr) -} - -// Marshal is the entry point from generated code, -// and should be ONLY called by generated code. -// It marshals msg to the end of b. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return b, ErrNil - } - return u.marshal(b, ptr, deterministic) -} - -func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { - // u := a.marshal, but atomically. - // We use an atomic here to ensure memory consistency. - u := atomicLoadMarshalInfo(&a.marshal) - if u == nil { - // Get marshal information from type of message. - t := reflect.ValueOf(msg).Type() - if t.Kind() != reflect.Ptr { - panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) - } - u = getMarshalInfo(t.Elem()) - // Store it in the cache for later users. - // a.marshal = u, but atomically. - atomicStoreMarshalInfo(&a.marshal, u) - } - return u -} - -// size is the main function to compute the size of the encoded data of a message. -// ptr is the pointer to the message. -func (u *marshalInfo) size(ptr pointer) int { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b, _ := m.Marshal() - return len(b) - } - - n := 0 - for _, f := range u.fields { - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - n += f.sizer(ptr.offset(f.field), f.tagsize) - } - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - n += u.sizeMessageSet(e) - } else { - n += u.sizeExtensions(e) - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - n += u.sizeV1Extensions(m) - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - n += len(s) - } - // cache the result for use in marshal - if u.sizecache.IsValid() { - atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) - } - return n -} - -// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), -// fall back to compute the size. -func (u *marshalInfo) cachedsize(ptr pointer) int { - if u.sizecache.IsValid() { - return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) - } - return u.size(ptr) -} - -// marshal is the main function to marshal a message. It takes a byte slice and appends -// the encoded data to the end of the slice, returns the slice and error (if any). -// ptr is the pointer to the message. -// If deterministic is true, map is marshaled in deterministic order. -func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b1, err := m.Marshal() - b = append(b, b1...) - return b, err - } - - var err, errLater error - // The old marshaler encodes extensions at beginning. - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - b, err = u.appendMessageSet(b, e, deterministic) - } else { - b, err = u.appendExtensions(b, e, deterministic) - } - if err != nil { - return b, err - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - b, err = u.appendV1Extensions(b, m, deterministic) - if err != nil { - return b, err - } - } - for _, f := range u.fields { - if f.required { - if ptr.offset(f.field).getPointer().isNil() { - // Required field is not set. - // We record the error but keep going, to give a complete marshaling. - if errLater == nil { - errLater = &RequiredNotSetError{f.name} - } - continue - } - } - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) - if err != nil { - if err1, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errLater == nil { - errLater = &RequiredNotSetError{f.name + "." + err1.field} - } - continue - } - if err == errRepeatedHasNil { - err = errors.New("proto: repeated field " + f.name + " has nil element") - } - if err == errInvalidUTF8 { - if errLater == nil { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - errLater = &invalidUTF8Error{fullName} - } - continue - } - return b, err - } - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - b = append(b, s...) - } - return b, errLater -} - -// computeMarshalInfo initializes the marshal info. -func (u *marshalInfo) computeMarshalInfo() { - u.Lock() - defer u.Unlock() - if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock - return - } - - t := u.typ - u.unrecognized = invalidField - u.extensions = invalidField - u.v1extensions = invalidField - u.sizecache = invalidField - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if reflect.PtrTo(t).Implements(marshalerType) { - u.hasmarshaler = true - atomic.StoreInt32(&u.initialized, 1) - return - } - - // get oneof implementers - var oneofImplementers []interface{} - if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - } - - n := t.NumField() - - // deal with XXX fields first - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if !strings.HasPrefix(f.Name, "XXX_") { - continue - } - switch f.Name { - case "XXX_sizecache": - u.sizecache = toField(&f) - case "XXX_unrecognized": - u.unrecognized = toField(&f) - case "XXX_InternalExtensions": - u.extensions = toField(&f) - u.messageset = f.Tag.Get("protobuf_messageset") == "1" - case "XXX_extensions": - u.v1extensions = toField(&f) - case "XXX_NoUnkeyedLiteral": - // nothing to do - default: - panic("unknown XXX field: " + f.Name) - } - n-- - } - - // normal fields - fields := make([]marshalFieldInfo, n) // batch allocation - u.fields = make([]*marshalFieldInfo, 0, n) - for i, j := 0, 0; i < t.NumField(); i++ { - f := t.Field(i) - - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - field := &fields[j] - j++ - field.name = f.Name - u.fields = append(u.fields, field) - if f.Tag.Get("protobuf_oneof") != "" { - field.computeOneofFieldInfo(&f, oneofImplementers) - continue - } - if f.Tag.Get("protobuf") == "" { - // field has no tag (not in generated message), ignore it - u.fields = u.fields[:len(u.fields)-1] - j-- - continue - } - field.computeMarshalFieldInfo(&f) - } - - // fields are marshaled in tag order on the wire. - sort.Sort(byTag(u.fields)) - - atomic.StoreInt32(&u.initialized, 1) -} - -// helper for sorting fields by tag -type byTag []*marshalFieldInfo - -func (a byTag) Len() int { return len(a) } -func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } - -// getExtElemInfo returns the information to marshal an extension element. -// The info it returns is initialized. -func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { - // get from cache first - u.RLock() - e, ok := u.extElems[desc.Field] - u.RUnlock() - if ok { - return e - } - - t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct - tags := strings.Split(desc.Tag, ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(t, tags, false, false) - e = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - isptr: t.Kind() == reflect.Ptr, - } - - // update cache - u.Lock() - if u.extElems == nil { - u.extElems = make(map[int32]*marshalElemInfo) - } - u.extElems[desc.Field] = e - u.Unlock() - return e -} - -// computeMarshalFieldInfo fills up the information to marshal a field. -func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { - // parse protobuf tag of the field. - // tag has format of "bytes,49,opt,name=foo,def=hello!" - tags := strings.Split(f.Tag.Get("protobuf"), ",") - if tags[0] == "" { - return - } - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if tags[2] == "req" { - fi.required = true - } - fi.setTag(f, tag, wt) - fi.setMarshaler(f, tags) -} - -func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { - fi.field = toField(f) - fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. - fi.isPointer = true - fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) - fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) - - ityp := f.Type // interface type - for _, o := range oneofImplementers { - t := reflect.TypeOf(o) - if !t.Implements(ityp) { - continue - } - sf := t.Elem().Field(0) // oneof implementer is a struct with a single field - tags := strings.Split(sf.Tag.Get("protobuf"), ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value - fi.oneofElems[t.Elem()] = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - } - } -} - -type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) -} - -// wiretype returns the wire encoding of the type. -func wiretype(encoding string) uint64 { - switch encoding { - case "fixed32": - return WireFixed32 - case "fixed64": - return WireFixed64 - case "varint", "zigzag32", "zigzag64": - return WireVarint - case "bytes": - return WireBytes - case "group": - return WireStartGroup - } - panic("unknown wire type " + encoding) -} - -// setTag fills up the tag (in wire format) and its size in the info of a field. -func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { - fi.field = toField(f) - fi.wiretag = uint64(tag)<<3 | wt - fi.tagsize = SizeVarint(uint64(tag) << 3) -} - -// setMarshaler fills up the sizer and marshaler in the info of a field. -func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { - switch f.Type.Kind() { - case reflect.Map: - // map field - fi.isPointer = true - fi.sizer, fi.marshaler = makeMapMarshaler(f) - return - case reflect.Ptr, reflect.Slice: - fi.isPointer = true - } - fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) -} - -// typeMarshaler returns the sizer and marshaler of a given field. -// t is the type of the field. -// tags is the generated "protobuf" tag of the field. -// If nozero is true, zero value is not marshaled to the wire. -// If oneof is true, it is a oneof field. -func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { - encoding := tags[0] - - pointer := false - slice := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - packed := false - proto3 := false - validateUTF8 := true - for i := 2; i < len(tags); i++ { - if tags[i] == "packed" { - packed = true - } - if tags[i] == "proto3" { - proto3 = true - } - } - validateUTF8 = validateUTF8 && proto3 - - switch t.Kind() { - case reflect.Bool: - if pointer { - return sizeBoolPtr, appendBoolPtr - } - if slice { - if packed { - return sizeBoolPackedSlice, appendBoolPackedSlice - } - return sizeBoolSlice, appendBoolSlice - } - if nozero { - return sizeBoolValueNoZero, appendBoolValueNoZero - } - return sizeBoolValue, appendBoolValue - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixed32Ptr, appendFixed32Ptr - } - if slice { - if packed { - return sizeFixed32PackedSlice, appendFixed32PackedSlice - } - return sizeFixed32Slice, appendFixed32Slice - } - if nozero { - return sizeFixed32ValueNoZero, appendFixed32ValueNoZero - } - return sizeFixed32Value, appendFixed32Value - case "varint": - if pointer { - return sizeVarint32Ptr, appendVarint32Ptr - } - if slice { - if packed { - return sizeVarint32PackedSlice, appendVarint32PackedSlice - } - return sizeVarint32Slice, appendVarint32Slice - } - if nozero { - return sizeVarint32ValueNoZero, appendVarint32ValueNoZero - } - return sizeVarint32Value, appendVarint32Value - } - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixedS32Ptr, appendFixedS32Ptr - } - if slice { - if packed { - return sizeFixedS32PackedSlice, appendFixedS32PackedSlice - } - return sizeFixedS32Slice, appendFixedS32Slice - } - if nozero { - return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero - } - return sizeFixedS32Value, appendFixedS32Value - case "varint": - if pointer { - return sizeVarintS32Ptr, appendVarintS32Ptr - } - if slice { - if packed { - return sizeVarintS32PackedSlice, appendVarintS32PackedSlice - } - return sizeVarintS32Slice, appendVarintS32Slice - } - if nozero { - return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero - } - return sizeVarintS32Value, appendVarintS32Value - case "zigzag32": - if pointer { - return sizeZigzag32Ptr, appendZigzag32Ptr - } - if slice { - if packed { - return sizeZigzag32PackedSlice, appendZigzag32PackedSlice - } - return sizeZigzag32Slice, appendZigzag32Slice - } - if nozero { - return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero - } - return sizeZigzag32Value, appendZigzag32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixed64Ptr, appendFixed64Ptr - } - if slice { - if packed { - return sizeFixed64PackedSlice, appendFixed64PackedSlice - } - return sizeFixed64Slice, appendFixed64Slice - } - if nozero { - return sizeFixed64ValueNoZero, appendFixed64ValueNoZero - } - return sizeFixed64Value, appendFixed64Value - case "varint": - if pointer { - return sizeVarint64Ptr, appendVarint64Ptr - } - if slice { - if packed { - return sizeVarint64PackedSlice, appendVarint64PackedSlice - } - return sizeVarint64Slice, appendVarint64Slice - } - if nozero { - return sizeVarint64ValueNoZero, appendVarint64ValueNoZero - } - return sizeVarint64Value, appendVarint64Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixedS64Ptr, appendFixedS64Ptr - } - if slice { - if packed { - return sizeFixedS64PackedSlice, appendFixedS64PackedSlice - } - return sizeFixedS64Slice, appendFixedS64Slice - } - if nozero { - return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero - } - return sizeFixedS64Value, appendFixedS64Value - case "varint": - if pointer { - return sizeVarintS64Ptr, appendVarintS64Ptr - } - if slice { - if packed { - return sizeVarintS64PackedSlice, appendVarintS64PackedSlice - } - return sizeVarintS64Slice, appendVarintS64Slice - } - if nozero { - return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero - } - return sizeVarintS64Value, appendVarintS64Value - case "zigzag64": - if pointer { - return sizeZigzag64Ptr, appendZigzag64Ptr - } - if slice { - if packed { - return sizeZigzag64PackedSlice, appendZigzag64PackedSlice - } - return sizeZigzag64Slice, appendZigzag64Slice - } - if nozero { - return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero - } - return sizeZigzag64Value, appendZigzag64Value - } - case reflect.Float32: - if pointer { - return sizeFloat32Ptr, appendFloat32Ptr - } - if slice { - if packed { - return sizeFloat32PackedSlice, appendFloat32PackedSlice - } - return sizeFloat32Slice, appendFloat32Slice - } - if nozero { - return sizeFloat32ValueNoZero, appendFloat32ValueNoZero - } - return sizeFloat32Value, appendFloat32Value - case reflect.Float64: - if pointer { - return sizeFloat64Ptr, appendFloat64Ptr - } - if slice { - if packed { - return sizeFloat64PackedSlice, appendFloat64PackedSlice - } - return sizeFloat64Slice, appendFloat64Slice - } - if nozero { - return sizeFloat64ValueNoZero, appendFloat64ValueNoZero - } - return sizeFloat64Value, appendFloat64Value - case reflect.String: - if validateUTF8 { - if pointer { - return sizeStringPtr, appendUTF8StringPtr - } - if slice { - return sizeStringSlice, appendUTF8StringSlice - } - if nozero { - return sizeStringValueNoZero, appendUTF8StringValueNoZero - } - return sizeStringValue, appendUTF8StringValue - } - if pointer { - return sizeStringPtr, appendStringPtr - } - if slice { - return sizeStringSlice, appendStringSlice - } - if nozero { - return sizeStringValueNoZero, appendStringValueNoZero - } - return sizeStringValue, appendStringValue - case reflect.Slice: - if slice { - return sizeBytesSlice, appendBytesSlice - } - if oneof { - // Oneof bytes field may also have "proto3" tag. - // We want to marshal it as a oneof field. Do this - // check before the proto3 check. - return sizeBytesOneof, appendBytesOneof - } - if proto3 { - return sizeBytes3, appendBytes3 - } - return sizeBytes, appendBytes - case reflect.Struct: - switch encoding { - case "group": - if slice { - return makeGroupSliceMarshaler(getMarshalInfo(t)) - } - return makeGroupMarshaler(getMarshalInfo(t)) - case "bytes": - if slice { - return makeMessageSliceMarshaler(getMarshalInfo(t)) - } - return makeMessageMarshaler(getMarshalInfo(t)) - } - } - panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) -} - -// Below are functions to size/marshal a specific type of a field. -// They are stored in the field's info, and called by function pointers. -// They have type sizer or marshaler. - -func sizeFixed32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixedS32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFloat32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - return (4 + tagsize) * len(s) -} -func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixed64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFixedS64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFloat64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - return (8 + tagsize) * len(s) -} -func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeVarint32Value(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarint32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarint64Value(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - return SizeVarint(v) + tagsize -} -func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return SizeVarint(v) + tagsize -} -func sizeVarint64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return SizeVarint(*p) + tagsize -} -func sizeVarint64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(v) + tagsize - } - return n -} -func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize - } - return n -} -func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize - } - return n -} -func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeBoolValue(_ pointer, tagsize int) int { - return 1 + tagsize -} -func sizeBoolValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toBool() - if !v { - return 0 - } - return 1 + tagsize -} -func sizeBoolPtr(ptr pointer, tagsize int) int { - p := *ptr.toBoolPtr() - if p == nil { - return 0 - } - return 1 + tagsize -} -func sizeBoolSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - return (1 + tagsize) * len(s) -} -func sizeBoolPackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return 0 - } - return len(s) + SizeVarint(uint64(len(s))) + tagsize -} -func sizeStringValue(ptr pointer, tagsize int) int { - v := *ptr.toString() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toString() - if v == "" { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringPtr(ptr pointer, tagsize int) int { - p := *ptr.toStringPtr() - if p == nil { - return 0 - } - v := *p - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringSlice(ptr pointer, tagsize int) int { - s := *ptr.toStringSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} -func sizeBytes(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if v == nil { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytes3(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if len(v) == 0 { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesOneof(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesSlice(ptr pointer, tagsize int) int { - s := *ptr.toBytesSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} - -// appendFixed32 appends an encoded fixed32 to b. -func appendFixed32(b []byte, v uint32) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24)) - return b -} - -// appendFixed64 appends an encoded fixed64 to b. -func appendFixed64(b []byte, v uint64) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24), - byte(v>>32), - byte(v>>40), - byte(v>>48), - byte(v>>56)) - return b -} - -// appendVarint appends an encoded varint to b. -func appendVarint(b []byte, v uint64) []byte { - // TODO: make 1-byte (maybe 2-byte) case inline-able, once we - // have non-leaf inliner. - switch { - case v < 1<<7: - b = append(b, byte(v)) - case v < 1<<14: - b = append(b, - byte(v&0x7f|0x80), - byte(v>>7)) - case v < 1<<21: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte(v>>14)) - case v < 1<<28: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte(v>>21)) - case v < 1<<35: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte(v>>28)) - case v < 1<<42: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte(v>>35)) - case v < 1<<49: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte(v>>42)) - case v < 1<<56: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte(v>>49)) - case v < 1<<63: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte(v>>56)) - default: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte((v>>56)&0x7f|0x80), - 1) - } - return b -} - -func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, *p) - return b, nil -} -func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(*p)) - return b, nil -} -func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(*p)) - return b, nil -} -func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, *p) - return b, nil -} -func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(*p)) - return b, nil -} -func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(*p)) - return b, nil -} -func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, *p) - return b, nil -} -func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - } - return b, nil -} -func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, v) - } - return b, nil -} -func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - if !v { - return b, nil - } - b = appendVarint(b, wiretag) - b = append(b, 1) - return b, nil -} - -func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toBoolPtr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - if *p { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(len(s))) - for _, v := range s { - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if v == "" { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toStringSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} -func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - v := *ptr.toString() - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - v := *ptr.toString() - if v == "" { - return b, nil - } - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - s := *ptr.toStringSlice() - for _, v := range s { - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if v == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if len(v) == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBytesSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} - -// makeGroupMarshaler returns the sizer and marshaler for a group. -// u is the marshal info of the underlying message. -func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - return u.size(p) + 2*tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - var err error - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, p, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - return b, err - } -} - -// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. -// u is the marshal info of the underlying message. -func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - n += u.size(v) + 2*tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err error - var nerr nonFatal - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, v, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - if !nerr.Merge(err) { - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, nerr.E - } -} - -// makeMessageMarshaler returns the sizer and marshaler for a message field. -// u is the marshal info of the message. -func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.size(p) - return siz + SizeVarint(uint64(siz)) + tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(p) - b = appendVarint(b, uint64(siz)) - return u.marshal(b, p, deterministic) - } -} - -// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. -// u is the marshal info of the message. -func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - siz := u.size(v) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err error - var nerr nonFatal - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(v) - b = appendVarint(b, uint64(siz)) - b, err = u.marshal(b, v, deterministic) - - if !nerr.Merge(err) { - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, nerr.E - } -} - -// makeMapMarshaler returns the sizer and marshaler for a map field. -// f is the pointer to the reflect data structure of the field. -func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { - // figure out key and value type - t := f.Type - keyType := t.Key() - valType := t.Elem() - keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") - valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") - keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map - valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map - keyWireTag := 1<<3 | wiretype(keyTags[0]) - valWireTag := 2<<3 | wiretype(valTags[0]) - - // We create an interface to get the addresses of the map key and value. - // If value is pointer-typed, the interface is a direct interface, the - // idata itself is the value. Otherwise, the idata is the pointer to the - // value. - // Key cannot be pointer-typed. - valIsPtr := valType.Kind() == reflect.Ptr - - // If value is a message with nested maps, calling - // valSizer in marshal may be quadratic. We should use - // cached version in marshal (but not in size). - // If value is not message type, we don't have size cache, - // but it cannot be nested either. Just use valSizer. - valCachedSizer := valSizer - if valIsPtr && valType.Elem().Kind() == reflect.Struct { - u := getMarshalInfo(valType.Elem()) - valCachedSizer = func(ptr pointer, tagsize int) int { - // Same as message sizer, but use cache. - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.cachedsize(p) - return siz + SizeVarint(uint64(siz)) + tagsize - } - } - return func(ptr pointer, tagsize int) int { - m := ptr.asPointerTo(t).Elem() // the map - n := 0 - for _, k := range m.MapKeys() { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { - m := ptr.asPointerTo(t).Elem() // the map - var err error - keys := m.MapKeys() - if len(keys) > 1 && deterministic { - sort.Sort(mapKeys(keys)) - } - - var nerr nonFatal - for _, k := range keys { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - b = appendVarint(b, tag) - siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - b = appendVarint(b, uint64(siz)) - b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) - if !nerr.Merge(err) { - return b, err - } - b, err = valMarshaler(b, vaddr, valWireTag, deterministic) - if err != ErrNil && !nerr.Merge(err) { // allow nil value in map - return b, err - } - } - return b, nerr.E - } -} - -// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. -// fi is the marshal info of the field. -// f is the pointer to the reflect data structure of the field. -func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { - // Oneof field is an interface. We need to get the actual data type on the fly. - t := f.Type - return func(ptr pointer, _ int) int { - p := ptr.getInterfacePointer() - if p.isNil() { - return 0 - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - e := fi.oneofElems[telem] - return e.sizer(p, e.tagsize) - }, - func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { - p := ptr.getInterfacePointer() - if p.isNil() { - return b, nil - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { - return b, errOneofHasNil - } - e := fi.oneofElems[telem] - return e.marshaler(b, p, e.wiretag, deterministic) - } -} - -// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. -func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - mu.Unlock() - return n -} - -// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. -func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - var nerr nonFatal - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E - } - - // Sort the keys to provide a deterministic encoding. - // Not sure this is required, but the old code does it. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// message set format is: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } - -// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field -// in message set format (above). -func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for id, e := range m { - n += 2 // start group, end group. tag = 1 (size=1) - n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - siz := len(msgWithLen) - n += siz + 1 // message, tag = 3 (size=1) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, 1) // message, tag = 3 (size=1) - } - mu.Unlock() - return n -} - -// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) -// to the end of byte slice b. -func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - var nerr nonFatal - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for id, e := range m { - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - if !nerr.Merge(err) { - return b, err - } - b = append(b, 1<<3|WireEndGroup) - } - return b, nerr.E - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, id := range keys { - e := m[int32(id)] - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - b = append(b, 1<<3|WireEndGroup) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// sizeV1Extensions computes the size of encoded data for a V1-API extension field. -func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { - if m == nil { - return 0 - } - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - return n -} - -// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. -func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { - if m == nil { - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - var err error - var nerr nonFatal - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// newMarshaler is the interface representing objects that can marshal themselves. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newMarshaler interface { - XXX_Size() int - XXX_Marshal(b []byte, deterministic bool) ([]byte, error) -} - -// Size returns the encoded size of a protocol buffer message. -// This is the main entry point. -func Size(pb Message) int { - if m, ok := pb.(newMarshaler); ok { - return m.XXX_Size() - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, _ := m.Marshal() - return len(b) - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return 0 - } - var info InternalMessageInfo - return info.Size(pb) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, returning the data. -// This is the main entry point. -func Marshal(pb Message) ([]byte, error) { - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - b := make([]byte, 0, siz) - return m.XXX_Marshal(b, false) - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - return m.Marshal() - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return nil, ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - b := make([]byte, 0, siz) - return info.Marshal(b, pb, false) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, writing the result to the -// Buffer. -// This is an alternative entry point. It is not necessary to use -// a Buffer for most applications. -func (p *Buffer) Marshal(pb Message) error { - var err error - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - p.grow(siz) // make sure buf has enough capacity - p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) - return err - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, err := m.Marshal() - p.buf = append(p.buf, b...) - return err - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - p.grow(siz) // make sure buf has enough capacity - p.buf, err = info.Marshal(p.buf, pb, p.deterministic) - return err -} - -// grow grows the buffer's capacity, if necessary, to guarantee space for -// another n bytes. After grow(n), at least n bytes can be written to the -// buffer without another allocation. -func (p *Buffer) grow(n int) { - need := len(p.buf) + n - if need <= cap(p.buf) { - return - } - newCap := len(p.buf) * 2 - if newCap < need { - newCap = need - } - p.buf = append(make([]byte, 0, newCap), p.buf...) -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_merge.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_merge.go deleted file mode 100644 index 1bda05305..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_merge.go +++ /dev/null @@ -1,658 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -// Merge merges the src message into dst. -// This assumes that dst and src of the same type and are non-nil. -func (a *InternalMessageInfo) Merge(dst, src Message) { - mi := atomicLoadMergeInfo(&a.merge) - if mi == nil { - mi = getMergeInfo(reflect.TypeOf(dst).Elem()) - atomicStoreMergeInfo(&a.merge, mi) - } - mi.merge(toPointer(&dst), toPointer(&src)) -} - -type mergeInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []mergeFieldInfo - unrecognized field // Offset of XXX_unrecognized -} - -type mergeFieldInfo struct { - field field // Offset of field, guaranteed to be valid - - // isPointer reports whether the value in the field is a pointer. - // This is true for the following situations: - // * Pointer to struct - // * Pointer to basic type (proto2 only) - // * Slice (first value in slice header is a pointer) - // * String (first value in string header is a pointer) - isPointer bool - - // basicWidth reports the width of the field assuming that it is directly - // embedded in the struct (as is the case for basic types in proto3). - // The possible values are: - // 0: invalid - // 1: bool - // 4: int32, uint32, float32 - // 8: int64, uint64, float64 - basicWidth int - - // Where dst and src are pointers to the types being merged. - merge func(dst, src pointer) -} - -var ( - mergeInfoMap = map[reflect.Type]*mergeInfo{} - mergeInfoLock sync.Mutex -) - -func getMergeInfo(t reflect.Type) *mergeInfo { - mergeInfoLock.Lock() - defer mergeInfoLock.Unlock() - mi := mergeInfoMap[t] - if mi == nil { - mi = &mergeInfo{typ: t} - mergeInfoMap[t] = mi - } - return mi -} - -// merge merges src into dst assuming they are both of type *mi.typ. -func (mi *mergeInfo) merge(dst, src pointer) { - if dst.isNil() { - panic("proto: nil destination") - } - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&mi.initialized) == 0 { - mi.computeMergeInfo() - } - - for _, fi := range mi.fields { - sfp := src.offset(fi.field) - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string - continue - } - if fi.basicWidth > 0 { - switch { - case fi.basicWidth == 1 && !*sfp.toBool(): - continue - case fi.basicWidth == 4 && *sfp.toUint32() == 0: - continue - case fi.basicWidth == 8 && *sfp.toUint64() == 0: - continue - } - } - } - - dfp := dst.offset(fi.field) - fi.merge(dfp, sfp) - } - - // TODO: Make this faster? - out := dst.asPointerTo(mi.typ).Elem() - in := src.asPointerTo(mi.typ).Elem() - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - if mi.unrecognized.IsValid() { - if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { - *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) - } - } -} - -func (mi *mergeInfo) computeMergeInfo() { - mi.lock.Lock() - defer mi.lock.Unlock() - if mi.initialized != 0 { - return - } - t := mi.typ - n := t.NumField() - - props := GetProperties(t) - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - mfi := mergeFieldInfo{field: toField(&f)} - tf := f.Type - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - switch tf.Kind() { - case reflect.Ptr, reflect.Slice, reflect.String: - // As a special case, we assume slices and strings are pointers - // since we know that the first field in the SliceSlice or - // StringHeader is a data pointer. - mfi.isPointer = true - case reflect.Bool: - mfi.basicWidth = 1 - case reflect.Int32, reflect.Uint32, reflect.Float32: - mfi.basicWidth = 4 - case reflect.Int64, reflect.Uint64, reflect.Float64: - mfi.basicWidth = 8 - } - } - - // Unwrap tf to get at its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + tf.Name()) - } - - switch tf.Kind() { - case reflect.Int32: - switch { - case isSlice: // E.g., []int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Slice is not defined (see pointer_reflect.go). - /* - sfsp := src.toInt32Slice() - if *sfsp != nil { - dfsp := dst.toInt32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - */ - sfs := src.getInt32Slice() - if sfs != nil { - dfs := dst.getInt32Slice() - dfs = append(dfs, sfs...) - if dfs == nil { - dfs = []int32{} - } - dst.setInt32Slice(dfs) - } - } - case isPointer: // E.g., *int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). - /* - sfpp := src.toInt32Ptr() - if *sfpp != nil { - dfpp := dst.toInt32Ptr() - if *dfpp == nil { - *dfpp = Int32(**sfpp) - } else { - **dfpp = **sfpp - } - } - */ - sfp := src.getInt32Ptr() - if sfp != nil { - dfp := dst.getInt32Ptr() - if dfp == nil { - dst.setInt32Ptr(*sfp) - } else { - *dfp = *sfp - } - } - } - default: // E.g., int32 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt32(); v != 0 { - *dst.toInt32() = v - } - } - } - case reflect.Int64: - switch { - case isSlice: // E.g., []int64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toInt64Slice() - if *sfsp != nil { - dfsp := dst.toInt64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - } - case isPointer: // E.g., *int64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toInt64Ptr() - if *sfpp != nil { - dfpp := dst.toInt64Ptr() - if *dfpp == nil { - *dfpp = Int64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., int64 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt64(); v != 0 { - *dst.toInt64() = v - } - } - } - case reflect.Uint32: - switch { - case isSlice: // E.g., []uint32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint32Slice() - if *sfsp != nil { - dfsp := dst.toUint32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint32{} - } - } - } - case isPointer: // E.g., *uint32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint32Ptr() - if *sfpp != nil { - dfpp := dst.toUint32Ptr() - if *dfpp == nil { - *dfpp = Uint32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint32 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint32(); v != 0 { - *dst.toUint32() = v - } - } - } - case reflect.Uint64: - switch { - case isSlice: // E.g., []uint64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint64Slice() - if *sfsp != nil { - dfsp := dst.toUint64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint64{} - } - } - } - case isPointer: // E.g., *uint64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint64Ptr() - if *sfpp != nil { - dfpp := dst.toUint64Ptr() - if *dfpp == nil { - *dfpp = Uint64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint64 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint64(); v != 0 { - *dst.toUint64() = v - } - } - } - case reflect.Float32: - switch { - case isSlice: // E.g., []float32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat32Slice() - if *sfsp != nil { - dfsp := dst.toFloat32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float32{} - } - } - } - case isPointer: // E.g., *float32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat32Ptr() - if *sfpp != nil { - dfpp := dst.toFloat32Ptr() - if *dfpp == nil { - *dfpp = Float32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float32 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat32(); v != 0 { - *dst.toFloat32() = v - } - } - } - case reflect.Float64: - switch { - case isSlice: // E.g., []float64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat64Slice() - if *sfsp != nil { - dfsp := dst.toFloat64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float64{} - } - } - } - case isPointer: // E.g., *float64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat64Ptr() - if *sfpp != nil { - dfpp := dst.toFloat64Ptr() - if *dfpp == nil { - *dfpp = Float64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float64 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat64(); v != 0 { - *dst.toFloat64() = v - } - } - } - case reflect.Bool: - switch { - case isSlice: // E.g., []bool - mfi.merge = func(dst, src pointer) { - sfsp := src.toBoolSlice() - if *sfsp != nil { - dfsp := dst.toBoolSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []bool{} - } - } - } - case isPointer: // E.g., *bool - mfi.merge = func(dst, src pointer) { - sfpp := src.toBoolPtr() - if *sfpp != nil { - dfpp := dst.toBoolPtr() - if *dfpp == nil { - *dfpp = Bool(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., bool - mfi.merge = func(dst, src pointer) { - if v := *src.toBool(); v { - *dst.toBool() = v - } - } - } - case reflect.String: - switch { - case isSlice: // E.g., []string - mfi.merge = func(dst, src pointer) { - sfsp := src.toStringSlice() - if *sfsp != nil { - dfsp := dst.toStringSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []string{} - } - } - } - case isPointer: // E.g., *string - mfi.merge = func(dst, src pointer) { - sfpp := src.toStringPtr() - if *sfpp != nil { - dfpp := dst.toStringPtr() - if *dfpp == nil { - *dfpp = String(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., string - mfi.merge = func(dst, src pointer) { - if v := *src.toString(); v != "" { - *dst.toString() = v - } - } - } - case reflect.Slice: - isProto3 := props.Prop[i].proto3 - switch { - case isPointer: - panic("bad pointer in byte slice case in " + tf.Name()) - case tf.Elem().Kind() != reflect.Uint8: - panic("bad element kind in byte slice case in " + tf.Name()) - case isSlice: // E.g., [][]byte - mfi.merge = func(dst, src pointer) { - sbsp := src.toBytesSlice() - if *sbsp != nil { - dbsp := dst.toBytesSlice() - for _, sb := range *sbsp { - if sb == nil { - *dbsp = append(*dbsp, nil) - } else { - *dbsp = append(*dbsp, append([]byte{}, sb...)) - } - } - if *dbsp == nil { - *dbsp = [][]byte{} - } - } - } - default: // E.g., []byte - mfi.merge = func(dst, src pointer) { - sbp := src.toBytes() - if *sbp != nil { - dbp := dst.toBytes() - if !isProto3 || len(*sbp) > 0 { - *dbp = append([]byte{}, *sbp...) - } - } - } - } - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("message field %s without pointer", tf)) - case isSlice: // E.g., []*pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sps := src.getPointerSlice() - if sps != nil { - dps := dst.getPointerSlice() - for _, sp := range sps { - var dp pointer - if !sp.isNil() { - dp = valToPointer(reflect.New(tf)) - mi.merge(dp, sp) - } - dps = append(dps, dp) - } - if dps == nil { - dps = []pointer{} - } - dst.setPointerSlice(dps) - } - } - default: // E.g., *pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sp := src.getPointer() - if !sp.isNil() { - dp := dst.getPointer() - if dp.isNil() { - dp = valToPointer(reflect.New(tf)) - dst.setPointer(dp) - } - mi.merge(dp, sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic("bad pointer or slice in map case in " + tf.Name()) - default: // E.g., map[K]V - mfi.merge = func(dst, src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - dm := dst.asPointerTo(tf).Elem() - if dm.IsNil() { - dm.Set(reflect.MakeMap(tf)) - } - - switch tf.Elem().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(Clone(val.Interface().(Message))) - dm.SetMapIndex(key, val) - } - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - dm.SetMapIndex(key, val) - } - default: // Basic type (e.g., string) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - dm.SetMapIndex(key, val) - } - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic("bad pointer or slice in interface case in " + tf.Name()) - default: // E.g., interface{} - // TODO: Make this faster? - mfi.merge = func(dst, src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - du := dst.asPointerTo(tf).Elem() - typ := su.Elem().Type() - if du.IsNil() || du.Elem().Type() != typ { - du.Set(reflect.New(typ.Elem())) // Initialize interface if empty - } - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - dv := du.Elem().Elem().Field(0) - if dv.Kind() == reflect.Ptr && dv.IsNil() { - dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - Merge(dv.Interface().(Message), sv.Interface().(Message)) - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) - default: // Basic type (e.g., string) - dv.Set(sv) - } - } - } - } - default: - panic(fmt.Sprintf("merger not found for type:%s", tf)) - } - mi.fields = append(mi.fields, mfi) - } - - mi.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - mi.unrecognized = toField(&f) - } - - atomic.StoreInt32(&mi.initialized, 1) -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_unmarshal.go deleted file mode 100644 index d7260aee1..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/table_unmarshal.go +++ /dev/null @@ -1,2055 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// Unmarshal is the entry point from the generated .pb.go files. -// This function is not intended to be used by non-generated code. -// This function is not subject to any compatibility guarantee. -// msg contains a pointer to a protocol buffer struct. -// b is the data to be unmarshaled into the protocol buffer. -// a is a pointer to a place to store cached unmarshal information. -func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { - // Load the unmarshal information for this message type. - // The atomic load ensures memory consistency. - u := atomicLoadUnmarshalInfo(&a.unmarshal) - if u == nil { - // Slow path: find unmarshal info for msg, update a with it. - u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) - atomicStoreUnmarshalInfo(&a.unmarshal, u) - } - // Then do the unmarshaling. - err := u.unmarshal(toPointer(&msg), b) - return err -} - -type unmarshalInfo struct { - typ reflect.Type // type of the protobuf struct - - // 0 = only typ field is initialized - // 1 = completely initialized - initialized int32 - lock sync.Mutex // prevents double initialization - dense []unmarshalFieldInfo // fields indexed by tag # - sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # - reqFields []string // names of required fields - reqMask uint64 // 1< 0 { - // Read tag and wire type. - // Special case 1 and 2 byte varints. - var x uint64 - if b[0] < 128 { - x = uint64(b[0]) - b = b[1:] - } else if len(b) >= 2 && b[1] < 128 { - x = uint64(b[0]&0x7f) + uint64(b[1])<<7 - b = b[2:] - } else { - var n int - x, n = decodeVarint(b) - if n == 0 { - return io.ErrUnexpectedEOF - } - b = b[n:] - } - tag := x >> 3 - wire := int(x) & 7 - - // Dispatch on the tag to one of the unmarshal* functions below. - var f unmarshalFieldInfo - if tag < uint64(len(u.dense)) { - f = u.dense[tag] - } else { - f = u.sparse[tag] - } - if fn := f.unmarshal; fn != nil { - var err error - b, err = fn(b, m.offset(f.field), wire) - if err == nil { - reqMask |= f.reqMask - continue - } - if r, ok := err.(*RequiredNotSetError); ok { - // Remember this error, but keep parsing. We need to produce - // a full parse even if a required field is missing. - if errLater == nil { - errLater = r - } - reqMask |= f.reqMask - continue - } - if err != errInternalBadWireType { - if err == errInvalidUTF8 { - if errLater == nil { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - errLater = &invalidUTF8Error{fullName} - } - continue - } - return err - } - // Fragments with bad wire type are treated as unknown fields. - } - - // Unknown tag. - if !u.unrecognized.IsValid() { - // Don't keep unrecognized data; just skip it. - var err error - b, err = skipField(b, wire) - if err != nil { - return err - } - continue - } - // Keep unrecognized data around. - // maybe in extensions, maybe in the unrecognized field. - z := m.offset(u.unrecognized).toBytes() - var emap map[int32]Extension - var e Extension - for _, r := range u.extensionRanges { - if uint64(r.Start) <= tag && tag <= uint64(r.End) { - if u.extensions.IsValid() { - mp := m.offset(u.extensions).toExtensions() - emap = mp.extensionsWrite() - e = emap[int32(tag)] - z = &e.enc - break - } - if u.oldExtensions.IsValid() { - p := m.offset(u.oldExtensions).toOldExtensions() - emap = *p - if emap == nil { - emap = map[int32]Extension{} - *p = emap - } - e = emap[int32(tag)] - z = &e.enc - break - } - panic("no extensions field available") - } - } - - // Use wire type to skip data. - var err error - b0 := b - b, err = skipField(b, wire) - if err != nil { - return err - } - *z = encodeVarint(*z, tag<<3|uint64(wire)) - *z = append(*z, b0[:len(b0)-len(b)]...) - - if emap != nil { - emap[int32(tag)] = e - } - } - if reqMask != u.reqMask && errLater == nil { - // A required field of this message is missing. - for _, n := range u.reqFields { - if reqMask&1 == 0 { - errLater = &RequiredNotSetError{n} - } - reqMask >>= 1 - } - } - return errLater -} - -// computeUnmarshalInfo fills in u with information for use -// in unmarshaling protocol buffers of type u.typ. -func (u *unmarshalInfo) computeUnmarshalInfo() { - u.lock.Lock() - defer u.lock.Unlock() - if u.initialized != 0 { - return - } - t := u.typ - n := t.NumField() - - // Set up the "not found" value for the unrecognized byte buffer. - // This is the default for proto3. - u.unrecognized = invalidField - u.extensions = invalidField - u.oldExtensions = invalidField - - // List of the generated type and offset for each oneof field. - type oneofField struct { - ityp reflect.Type // interface type of oneof field - field field // offset in containing message - } - var oneofFields []oneofField - - for i := 0; i < n; i++ { - f := t.Field(i) - if f.Name == "XXX_unrecognized" { - // The byte slice used to hold unrecognized input is special. - if f.Type != reflect.TypeOf(([]byte)(nil)) { - panic("bad type for XXX_unrecognized field: " + f.Type.Name()) - } - u.unrecognized = toField(&f) - continue - } - if f.Name == "XXX_InternalExtensions" { - // Ditto here. - if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { - panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) - } - u.extensions = toField(&f) - if f.Tag.Get("protobuf_messageset") == "1" { - u.isMessageSet = true - } - continue - } - if f.Name == "XXX_extensions" { - // An older form of the extensions field. - if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) { - panic("bad type for XXX_extensions field: " + f.Type.Name()) - } - u.oldExtensions = toField(&f) - continue - } - if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { - continue - } - - oneof := f.Tag.Get("protobuf_oneof") - if oneof != "" { - oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) - // The rest of oneof processing happens below. - continue - } - - tags := f.Tag.Get("protobuf") - tagArray := strings.Split(tags, ",") - if len(tagArray) < 2 { - panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) - } - tag, err := strconv.Atoi(tagArray[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tagArray[1]) - } - - name := "" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Extract unmarshaling function from the field (its type and tags). - unmarshal := fieldUnmarshaler(&f) - - // Required field? - var reqMask uint64 - if tagArray[2] == "req" { - bit := len(u.reqFields) - u.reqFields = append(u.reqFields, name) - reqMask = uint64(1) << uint(bit) - // TODO: if we have more than 64 required fields, we end up - // not verifying that all required fields are present. - // Fix this, perhaps using a count of required fields? - } - - // Store the info in the correct slot in the message. - u.setTag(tag, toField(&f), unmarshal, reqMask, name) - } - - // Find any types associated with oneof fields. - // TODO: XXX_OneofFuncs returns more info than we need. Get rid of some of it? - fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("XXX_OneofFuncs") - if fn.IsValid() { - res := fn.Call(nil)[3] // last return value from XXX_OneofFuncs: []interface{} - for i := res.Len() - 1; i >= 0; i-- { - v := res.Index(i) // interface{} - tptr := reflect.ValueOf(v.Interface()).Type() // *Msg_X - typ := tptr.Elem() // Msg_X - - f := typ.Field(0) // oneof implementers have one field - baseUnmarshal := fieldUnmarshaler(&f) - tags := strings.Split(f.Tag.Get("protobuf"), ",") - fieldNum, err := strconv.Atoi(tags[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tags[1]) - } - var name string - for _, tag := range tags { - if strings.HasPrefix(tag, "name=") { - name = strings.TrimPrefix(tag, "name=") - break - } - } - - // Find the oneof field that this struct implements. - // Might take O(n^2) to process all of the oneofs, but who cares. - for _, of := range oneofFields { - if tptr.Implements(of.ityp) { - // We have found the corresponding interface for this struct. - // That lets us know where this struct should be stored - // when we encounter it during unmarshaling. - unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) - u.setTag(fieldNum, of.field, unmarshal, 0, name) - } - } - } - } - - // Get extension ranges, if any. - fn = reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") - if fn.IsValid() { - if !u.extensions.IsValid() && !u.oldExtensions.IsValid() { - panic("a message with extensions, but no extensions field in " + t.Name()) - } - u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) - } - - // Explicitly disallow tag 0. This will ensure we flag an error - // when decoding a buffer of all zeros. Without this code, we - // would decode and skip an all-zero buffer of even length. - // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. - u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { - return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) - }, 0, "") - - // Set mask for required field check. - u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? - for len(u.dense) <= tag { - u.dense = append(u.dense, unmarshalFieldInfo{}) - } - u.dense[tag] = i - return - } - if u.sparse == nil { - u.sparse = map[uint64]unmarshalFieldInfo{} - } - u.sparse[uint64(tag)] = i -} - -// fieldUnmarshaler returns an unmarshaler for the given field. -func fieldUnmarshaler(f *reflect.StructField) unmarshaler { - if f.Type.Kind() == reflect.Map { - return makeUnmarshalMap(f) - } - return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) -} - -// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. -func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { - tagArray := strings.Split(tags, ",") - encoding := tagArray[0] - name := "unknown" - proto3 := false - validateUTF8 := true - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - if tag == "proto3" { - proto3 = true - } - } - validateUTF8 = validateUTF8 && proto3 - - // Figure out packaging (pointer, slice, or both) - slice := false - pointer := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - // We'll never have both pointer and slice for basic types. - if pointer && slice && t.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + t.Name()) - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return unmarshalBoolPtr - } - if slice { - return unmarshalBoolSlice - } - return unmarshalBoolValue - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixedS32Ptr - } - if slice { - return unmarshalFixedS32Slice - } - return unmarshalFixedS32Value - case "varint": - // this could be int32 or enum - if pointer { - return unmarshalInt32Ptr - } - if slice { - return unmarshalInt32Slice - } - return unmarshalInt32Value - case "zigzag32": - if pointer { - return unmarshalSint32Ptr - } - if slice { - return unmarshalSint32Slice - } - return unmarshalSint32Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixedS64Ptr - } - if slice { - return unmarshalFixedS64Slice - } - return unmarshalFixedS64Value - case "varint": - if pointer { - return unmarshalInt64Ptr - } - if slice { - return unmarshalInt64Slice - } - return unmarshalInt64Value - case "zigzag64": - if pointer { - return unmarshalSint64Ptr - } - if slice { - return unmarshalSint64Slice - } - return unmarshalSint64Value - } - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixed32Ptr - } - if slice { - return unmarshalFixed32Slice - } - return unmarshalFixed32Value - case "varint": - if pointer { - return unmarshalUint32Ptr - } - if slice { - return unmarshalUint32Slice - } - return unmarshalUint32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixed64Ptr - } - if slice { - return unmarshalFixed64Slice - } - return unmarshalFixed64Value - case "varint": - if pointer { - return unmarshalUint64Ptr - } - if slice { - return unmarshalUint64Slice - } - return unmarshalUint64Value - } - case reflect.Float32: - if pointer { - return unmarshalFloat32Ptr - } - if slice { - return unmarshalFloat32Slice - } - return unmarshalFloat32Value - case reflect.Float64: - if pointer { - return unmarshalFloat64Ptr - } - if slice { - return unmarshalFloat64Slice - } - return unmarshalFloat64Value - case reflect.Map: - panic("map type in typeUnmarshaler in " + t.Name()) - case reflect.Slice: - if pointer { - panic("bad pointer in slice case in " + t.Name()) - } - if slice { - return unmarshalBytesSlice - } - return unmarshalBytesValue - case reflect.String: - if validateUTF8 { - if pointer { - return unmarshalUTF8StringPtr - } - if slice { - return unmarshalUTF8StringSlice - } - return unmarshalUTF8StringValue - } - if pointer { - return unmarshalStringPtr - } - if slice { - return unmarshalStringSlice - } - return unmarshalStringValue - case reflect.Struct: - // message or group field - if !pointer { - panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding)) - } - switch encoding { - case "bytes": - if slice { - return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) - case "group": - if slice { - return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) - } - } - panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) -} - -// Below are all the unmarshalers for individual fields of various types. - -func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64() = v - return b, nil -} - -func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64() = v - return b, nil -} - -func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64() = v - return b, nil -} - -func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64Ptr() = &v - return b, nil -} - -func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - *f.toInt32() = v - return b, nil -} - -func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - *f.toInt32() = v - return b, nil -} - -func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32() = v - return b, nil -} - -func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32Ptr() = &v - return b, nil -} - -func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64() = v - return b[8:], nil -} - -func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64() = v - return b[8:], nil -} - -func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32() = v - return b[4:], nil -} - -func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32Ptr() = &v - return b[4:], nil -} - -func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - *f.toInt32() = v - return b[4:], nil -} - -func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.setInt32Ptr(v) - return b[4:], nil -} - -func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - return b[4:], nil -} - -func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - // Note: any length varint is allowed, even though any sane - // encoder will use one byte. - // See https://github.com/golang/protobuf/issues/76 - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - // TODO: check if x>1? Tests seem to indicate no. - v := x != 0 - *f.toBool() = v - return b[n:], nil -} - -func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - *f.toBoolPtr() = &v - return b[n:], nil -} - -func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - b = b[n:] - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - return b[n:], nil -} - -func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64() = v - return b[8:], nil -} - -func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64Ptr() = &v - return b[8:], nil -} - -func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32() = v - return b[4:], nil -} - -func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32Ptr() = &v - return b[4:], nil -} - -func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toString() = v - return b[x:], nil -} - -func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toStringPtr() = &v - return b[x:], nil -} - -func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - s := f.toStringSlice() - *s = append(*s, v) - return b[x:], nil -} - -func unmarshalUTF8StringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toString() = v - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -func unmarshalUTF8StringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toStringPtr() = &v - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -func unmarshalUTF8StringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - s := f.toStringSlice() - *s = append(*s, v) - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -var emptyBuf [0]byte - -func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // The use of append here is a trick which avoids the zeroing - // that would be required if we used a make/copy pair. - // We append to emptyBuf instead of nil because we want - // a non-nil result even when the length is 0. - v := append(emptyBuf[:], b[:x]...) - *f.toBytes() = v - return b[x:], nil -} - -func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := append(emptyBuf[:], b[:x]...) - s := f.toBytesSlice() - *s = append(*s, v) - return b[x:], nil -} - -func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // First read the message field to see if something is there. - // The semantics of multiple submessages are weird. Instead of - // the last one winning (as it is for all other fields), multiple - // submessages are merged. - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[x:], err - } -} - -func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[x:], err - } -} - -func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[y:], err - } -} - -func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[y:], err - } -} - -func makeUnmarshalMap(f *reflect.StructField) unmarshaler { - t := f.Type - kt := t.Key() - vt := t.Elem() - unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) - unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val")) - return func(b []byte, f pointer, w int) ([]byte, error) { - // The map entry is a submessage. Figure out how big it is. - if w != WireBytes { - return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - r := b[x:] // unused data to return - b = b[:x] // data for map entry - - // Note: we could use #keys * #values ~= 200 functions - // to do map decoding without reflection. Probably not worth it. - // Maps will be somewhat slow. Oh well. - - // Read key and value from data. - var nerr nonFatal - k := reflect.New(kt) - v := reflect.New(vt) - for len(b) > 0 { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - wire := int(x) & 7 - b = b[n:] - - var err error - switch x >> 3 { - case 1: - b, err = unmarshalKey(b, valToPointer(k), wire) - case 2: - b, err = unmarshalVal(b, valToPointer(v), wire) - default: - err = errInternalBadWireType // skip unknown tag - } - - if nerr.Merge(err) { - continue - } - if err != errInternalBadWireType { - return nil, err - } - - // Skip past unknown fields. - b, err = skipField(b, wire) - if err != nil { - return nil, err - } - } - - // Get map, allocate if needed. - m := f.asPointerTo(t).Elem() // an addressable map[K]T - if m.IsNil() { - m.Set(reflect.MakeMap(t)) - } - - // Insert into map. - m.SetMapIndex(k.Elem(), v.Elem()) - - return r, nerr.E - } -} - -// makeUnmarshalOneof makes an unmarshaler for oneof fields. -// for: -// message Msg { -// oneof F { -// int64 X = 1; -// float64 Y = 2; -// } -// } -// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). -// ityp is the interface type of the oneof field (e.g. isMsg_F). -// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). -// Note that this function will be called once for each case in the oneof. -func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { - sf := typ.Field(0) - field0 := toField(&sf) - return func(b []byte, f pointer, w int) ([]byte, error) { - // Allocate holder for value. - v := reflect.New(typ) - - // Unmarshal data into holder. - // We unmarshal into the first field of the holder object. - var err error - var nerr nonFatal - b, err = unmarshal(b, valToPointer(v).offset(field0), w) - if !nerr.Merge(err) { - return nil, err - } - - // Write pointer to holder into target field. - f.asPointerTo(ityp).Elem().Set(v) - - return b, nerr.E - } -} - -// Error used by decode internally. -var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") - -// skipField skips past a field of type wire and returns the remaining bytes. -func skipField(b []byte, wire int) ([]byte, error) { - switch wire { - case WireVarint: - _, k := decodeVarint(b) - if k == 0 { - return b, io.ErrUnexpectedEOF - } - b = b[k:] - case WireFixed32: - if len(b) < 4 { - return b, io.ErrUnexpectedEOF - } - b = b[4:] - case WireFixed64: - if len(b) < 8 { - return b, io.ErrUnexpectedEOF - } - b = b[8:] - case WireBytes: - m, k := decodeVarint(b) - if k == 0 || uint64(len(b)-k) < m { - return b, io.ErrUnexpectedEOF - } - b = b[uint64(k)+m:] - case WireStartGroup: - _, i := findEndGroup(b) - if i == -1 { - return b, io.ErrUnexpectedEOF - } - b = b[i:] - default: - return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) - } - return b, nil -} - -// findEndGroup finds the index of the next EndGroup tag. -// Groups may be nested, so the "next" EndGroup tag is the first -// unpaired EndGroup. -// findEndGroup returns the indexes of the start and end of the EndGroup tag. -// Returns (-1,-1) if it can't find one. -func findEndGroup(b []byte) (int, int) { - depth := 1 - i := 0 - for { - x, n := decodeVarint(b[i:]) - if n == 0 { - return -1, -1 - } - j := i - i += n - switch x & 7 { - case WireVarint: - _, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - case WireFixed32: - if len(b)-4 < i { - return -1, -1 - } - i += 4 - case WireFixed64: - if len(b)-8 < i { - return -1, -1 - } - i += 8 - case WireBytes: - m, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - if uint64(len(b)-i) < m { - return -1, -1 - } - i += int(m) - case WireStartGroup: - depth++ - case WireEndGroup: - depth-- - if depth == 0 { - return j, i - } - default: - return -1, -1 - } - } -} - -// encodeVarint appends a varint-encoded integer to b and returns the result. -func encodeVarint(b []byte, x uint64) []byte { - for x >= 1<<7 { - b = append(b, byte(x&0x7f|0x80)) - x >>= 7 - } - return append(b, byte(x)) -} - -// decodeVarint reads a varint-encoded integer from b. -// Returns the decoded integer and the number of bytes read. -// If there is an error, it returns 0,0. -func decodeVarint(b []byte) (uint64, int) { - var x, y uint64 - if len(b) == 0 { - goto bad - } - x = uint64(b[0]) - if x < 0x80 { - return x, 1 - } - x -= 0x80 - - if len(b) <= 1 { - goto bad - } - y = uint64(b[1]) - x += y << 7 - if y < 0x80 { - return x, 2 - } - x -= 0x80 << 7 - - if len(b) <= 2 { - goto bad - } - y = uint64(b[2]) - x += y << 14 - if y < 0x80 { - return x, 3 - } - x -= 0x80 << 14 - - if len(b) <= 3 { - goto bad - } - y = uint64(b[3]) - x += y << 21 - if y < 0x80 { - return x, 4 - } - x -= 0x80 << 21 - - if len(b) <= 4 { - goto bad - } - y = uint64(b[4]) - x += y << 28 - if y < 0x80 { - return x, 5 - } - x -= 0x80 << 28 - - if len(b) <= 5 { - goto bad - } - y = uint64(b[5]) - x += y << 35 - if y < 0x80 { - return x, 6 - } - x -= 0x80 << 35 - - if len(b) <= 6 { - goto bad - } - y = uint64(b[6]) - x += y << 42 - if y < 0x80 { - return x, 7 - } - x -= 0x80 << 42 - - if len(b) <= 7 { - goto bad - } - y = uint64(b[7]) - x += y << 49 - if y < 0x80 { - return x, 8 - } - x -= 0x80 << 49 - - if len(b) <= 8 { - goto bad - } - y = uint64(b[8]) - x += y << 56 - if y < 0x80 { - return x, 9 - } - x -= 0x80 << 56 - - if len(b) <= 9 { - goto bad - } - y = uint64(b[9]) - x += y << 63 - if y < 2 { - return x, 10 - } - -bad: - return 0, 0 -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/text.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/text.go deleted file mode 100644 index 035a15544..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,847 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for writing the text protocol buffer format. - -import ( - "bufio" - "bytes" - "encoding" - "errors" - "fmt" - "io" - "log" - "math" - "reflect" - "sort" - "strings" -) - -var ( - newline = []byte("\n") - spaces = []byte(" ") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Print("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// isAny reports whether sv is a google.protobuf.Any message -func isAny(sv reflect.Value) bool { - type wkt interface { - XXX_WellKnownType() string - } - t, ok := sv.Addr().Interface().(wkt) - return ok && t.XXX_WellKnownType() == "Any" -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { - turl := sv.FieldByName("TypeUrl") - val := sv.FieldByName("Value") - if !turl.IsValid() || !val.IsValid() { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - b, ok := val.Interface().([]byte) - if !ok { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - parts := strings.Split(turl.String(), "/") - mt := MessageType(parts[len(parts)-1]) - if mt == nil { - return false, nil - } - m := reflect.New(mt.Elem()) - if err := Unmarshal(b, m.Interface().(Message)); err != nil { - return false, nil - } - w.Write([]byte("[")) - u := turl.String() - if requiresQuotes(u) { - writeString(w, u) - } else { - w.Write([]byte(u)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.ind++ - } - if err := tm.writeStruct(w, m.Elem()); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.ind-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { - if tm.ExpandAny && isAny(sv) { - if canExpand, err := tm.writeProto3Any(w, sv); canExpand { - return err - } - } - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < sv.NumField(); i++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if name == "XXX_NoUnkeyedLiteral" { - continue - } - - if strings.HasPrefix(name, "XXX_") { - // There are two XXX_ fields: - // XXX_unrecognized []byte - // XXX_extensions map[int32]proto.Extension - // The first is handled here; - // the second is handled at the bottom of this function. - if name == "XXX_unrecognized" && !fv.IsNil() { - if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Field not filled in. This could be an optional field or - // a required field that wasn't filled in. Either way, there - // isn't anything we can show for it. - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - // Repeated field that is empty, or a bytes field that is unused. - continue - } - - if props.Repeated && fv.Kind() == reflect.Slice { - // Repeated field. - for j := 0; j < fv.Len(); j++ { - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - v := fv.Index(j) - if v.Kind() == reflect.Ptr && v.IsNil() { - // A nil message in a repeated field is not valid, - // but we can handle that more gracefully than panicking. - if _, err := w.Write([]byte("\n")); err != nil { - return err - } - continue - } - if err := tm.writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, key, props.MapKeyProp); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, val, props.MapValProp); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - // close struct - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { - // empty bytes field - continue - } - if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { - // proto3 non-repeated scalar field; skip if zero value - if isProto3Zero(fv) { - continue - } - } - - if fv.Kind() == reflect.Interface { - // Check if it is a oneof. - if st.Field(i).Tag.Get("protobuf_oneof") != "" { - // fv is nil, or holds a pointer to generated struct. - // That generated struct has exactly one field, - // which has a protobuf struct tag. - if fv.IsNil() { - continue - } - inner := fv.Elem().Elem() // interface -> *T -> T - tag := inner.Type().Field(0).Tag.Get("protobuf") - props = new(Properties) // Overwrite the outer props var, but not its pointee. - props.Parse(tag) - // Write the value in the oneof, not the oneof itself. - fv = inner.Field(0) - - // Special case to cope with malformed messages gracefully: - // If the value in the oneof is a nil pointer, don't panic - // in writeAny. - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Use errors.New so writeAny won't render quotes. - msg := errors.New("/* nil */") - fv = reflect.ValueOf(&msg).Elem() - } - } - } - - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - - // Enums have a String method, so writeAny will work fine. - if err := tm.writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if _, err := extendable(pv.Interface()); err == nil { - if err := tm.writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -// writeAny writes an arbitrary field. -func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - switch v.Kind() { - case reflect.Slice: - // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Bytes())); err != nil { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if v.CanAddr() { - // Calling v.Interface on a struct causes the reflect package to - // copy the entire struct. This is racy with the new Marshaler - // since we atomically update the XXX_sizecache. - // - // Thus, we retrieve a pointer to the struct if possible to avoid - // a race since v.Interface on the pointer doesn't copy the struct. - // - // If v is not addressable, then we are not worried about a race - // since it implies that the binary Marshaler cannot possibly be - // mutating this value. - v = v.Addr() - } - if etm, ok := v.Interface().(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = w.Write(text); err != nil { - return err - } - } else { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - if err := tm.writeStruct(w, v); err != nil { - return err - } - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep, _ := extendable(pv.Interface()) - - // Order the extensions by ID. - // This isn't strictly necessary, but it will give us - // canonical output, which will also make testing easier. - m, mu := ep.extensionsRead() - if m == nil { - return nil - } - mu.Lock() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - mu.Unlock() - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - if err := tm.writeExtension(w, desc.Name, pb); err != nil { - return err - } - } else { - v := reflect.ValueOf(pb) - for i := 0; i < v.Len(); i++ { - if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line). - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes a given protocol buffer in text format. -// The only errors returned are from w. -func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { - val := reflect.ValueOf(pb) - if pb == nil || val.IsNil() { - w.Write([]byte("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: tm.Compact, - } - - if etm, ok := pb.(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := tm.writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil -} - -// Text is the same as Marshal, but returns the string directly. -func (tm *TextMarshaler) Text(pb Message) string { - var buf bytes.Buffer - tm.Marshal(&buf, pb) - return buf.String() -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// TODO: consider removing some of the Marshal functions below. - -// MarshalText writes a given protocol buffer in text format. -// The only errors returned are from w. -func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } - -// MarshalTextString is the same as MarshalText, but returns the string directly. -func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } - -// CompactText writes a given protocol buffer in compact text format (one line). -func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/text_parser.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100644 index ec8f50bd5..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,884 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// Error string emitted when deserializing Any and fields are already set -const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") -) - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - ss := string(r) + s[:2] - s = s[2:] - i, err := strconv.ParseUint(ss, 8, 8) - if err != nil { - return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) - } - return string([]byte{byte(i)}), s, nil - case 'x', 'X', 'u', 'U': - var n int - switch r { - case 'x', 'X': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) - } - ss := s[:n] - s = s[n:] - i, err := strconv.ParseUint(ss, 16, 64) - if err != nil { - return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) - } - if r == 'x' || r == 'X' { - return string([]byte{byte(i)}), s, nil - } - if i > utf8.MaxRune { - return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) - } - return string(i), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -// Return a RequiredNotSetError indicating which required field was not set. -func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < st.NumField(); i++ { - if !isNil(sv.Field(i)) { - continue - } - - props := sprops.Prop[i] - if props.Required { - return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} - } - } - return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen -} - -// Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { - i, ok := sprops.decoderOrigNames[name] - if ok { - return i, sprops.Prop[i], true - } - return -1, nil, false -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - // Colon is optional when the field is a group or message. - needColon := true - switch props.Wire { - case "group": - needColon = false - case "bytes": - // A "bytes" field is either a message, a string, or a repeated field; - // those three become *T, *string and []T respectively, so we can check for - // this field being a pointer to a non-string. - if typ.Kind() == reflect.Ptr { - // *T or *string - if typ.Elem().Kind() == reflect.String { - break - } - } else if typ.Kind() == reflect.Slice { - // []T or []*T - if typ.Elem().Kind() != reflect.Ptr { - break - } - } else if typ.Kind() == reflect.String { - // The proto3 exception is for a string field, - // which requires a colon. - break - } - needColon = false - } - if needColon { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -func (p *textParser) readStruct(sv reflect.Value, terminator string) error { - st := sv.Type() - sprops := GetProperties(st) - reqCount := sprops.reqCount - var reqFieldErr error - fieldSet := make(map[string]bool) - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension or an Any. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - extName, err := p.consumeExtName() - if err != nil { - return err - } - - if s := strings.LastIndex(extName, "/"); s >= 0 { - // If it contains a slash, it's an Any type URL. - messageName := extName[s+1:] - mt := MessageType(messageName) - if mt == nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) - } - tok = p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - v := reflect.New(mt.Elem()) - if pe := p.readStruct(v.Elem(), terminator); pe != nil { - return pe - } - b, err := Marshal(v.Interface().(Message)) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", messageName, err) - } - if fieldSet["type_url"] { - return p.errorf(anyRepeatedlyUnpacked, "type_url") - } - if fieldSet["value"] { - return p.errorf(anyRepeatedlyUnpacked, "value") - } - sv.FieldByName("TypeUrl").SetString(extName) - sv.FieldByName("Value").SetBytes(b) - fieldSet["type_url"] = true - fieldSet["value"] = true - continue - } - - var desc *ExtensionDesc - // This could be faster, but it's functional. - // TODO: Do something smarter than a linear scan. - for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == extName { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", extName) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(Message) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := tok.value - var dst reflect.Value - fi, props, ok := structFieldByName(sprops, name) - if ok { - dst = sv.Field(fi) - } else if oop, ok := sprops.OneofTypes[name]; ok { - // It is a oneof. - props = oop.Prop - nv := reflect.New(oop.Type.Elem()) - dst = nv.Elem().Field(0) - field := sv.Field(oop.Field) - if !field.IsNil() { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) - } - field.Set(nv) - } - if !dst.IsValid() { - return p.errorf("unknown field name %q in %v", name, st) - } - - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. See b/28924776 for a time - // this went wrong. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.MapKeyProp); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - case "value": - if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.MapValProp); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - default: - p.back() - return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - if props.Required { - reqCount-- - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - return reqFieldErr -} - -// consumeExtName consumes extension name or expanded Any type URL and the -// following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - if p.done && tok.value != "]" { - return "", p.errorf("unclosed type_url or extension name") - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in readStruct to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // Repeated field. - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - err := p.readAny(fv.Index(fv.Len()-1), props) - if err != nil { - return err - } - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return nil - } - // One value of the repeated field. - p.back() - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - return p.readAny(fv.Index(fv.Len()-1), props) - case reflect.Bool: - // true/1/t/True or false/f/0/False. - switch tok.value { - case "true", "1", "t", "True": - fv.SetBool(true) - return nil - case "false", "0", "f", "False": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - return um.UnmarshalText([]byte(s)) - } - pb.Reset() - v := reflect.ValueOf(pb) - return newTextParser(s).readStruct(v.Elem(), "") -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/LICENSE b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/LICENSE deleted file mode 100644 index 8f71f43fe..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/attrmgr/attrmgr.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/attrmgr/attrmgr.go deleted file mode 100644 index 14e97e20f..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/attrmgr/attrmgr.go +++ /dev/null @@ -1,264 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/* - * The attrmgr package contains utilities for managing attributes. - * Attributes are added to an X509 certificate as an extension. - */ - -package attrmgr - -import ( - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/json" - "fmt" - - "github.com/golang/protobuf/proto" - "github.com/hyperledger/fabric/protos/msp" - "github.com/pkg/errors" -) - -var ( - // AttrOID is the ASN.1 object identifier for an attribute extension in an - // X509 certificate - AttrOID = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 7, 8, 1} - // AttrOIDString is the string version of AttrOID - AttrOIDString = "1.2.3.4.5.6.7.8.1" -) - -// Attribute is a name/value pair -type Attribute interface { - // GetName returns the name of the attribute - GetName() string - // GetValue returns the value of the attribute - GetValue() string -} - -// AttributeRequest is a request for an attribute -type AttributeRequest interface { - // GetName returns the name of an attribute - GetName() string - // IsRequired returns true if the attribute is required - IsRequired() bool -} - -// New constructs an attribute manager -func New() *Mgr { return &Mgr{} } - -// Mgr is the attribute manager and is the main object for this package -type Mgr struct{} - -// ProcessAttributeRequestsForCert add attributes to an X509 certificate, given -// attribute requests and attributes. -func (mgr *Mgr) ProcessAttributeRequestsForCert(requests []AttributeRequest, attributes []Attribute, cert *x509.Certificate) error { - attrs, err := mgr.ProcessAttributeRequests(requests, attributes) - if err != nil { - return err - } - return mgr.AddAttributesToCert(attrs, cert) -} - -// ProcessAttributeRequests takes an array of attribute requests and an identity's attributes -// and returns an Attributes object containing the requested attributes. -func (mgr *Mgr) ProcessAttributeRequests(requests []AttributeRequest, attributes []Attribute) (*Attributes, error) { - attrsMap := map[string]string{} - attrs := &Attributes{Attrs: attrsMap} - missingRequiredAttrs := []string{} - // For each of the attribute requests - for _, req := range requests { - // Get the attribute - name := req.GetName() - attr := getAttrByName(name, attributes) - if attr == nil { - if req.IsRequired() { - // Didn't find attribute and it was required; return error below - missingRequiredAttrs = append(missingRequiredAttrs, name) - } - // Skip attribute requests which aren't required - continue - } - attrsMap[name] = attr.GetValue() - } - if len(missingRequiredAttrs) > 0 { - return nil, errors.Errorf("The following required attributes are missing: %+v", - missingRequiredAttrs) - } - return attrs, nil -} - -// AddAttributesToCert adds public attribute info to an X509 certificate. -func (mgr *Mgr) AddAttributesToCert(attrs *Attributes, cert *x509.Certificate) error { - buf, err := json.Marshal(attrs) - if err != nil { - return errors.Wrap(err, "Failed to marshal attributes") - } - ext := pkix.Extension{ - Id: AttrOID, - Critical: false, - Value: buf, - } - cert.Extensions = append(cert.Extensions, ext) - return nil -} - -// GetAttributesFromCert gets the attributes from a certificate. -func (mgr *Mgr) GetAttributesFromCert(cert *x509.Certificate) (*Attributes, error) { - // Get certificate attributes from the certificate if it exists - buf, err := getAttributesFromCert(cert) - if err != nil { - return nil, err - } - // Unmarshal into attributes object - attrs := &Attributes{} - if buf != nil { - err := json.Unmarshal(buf, attrs) - if err != nil { - return nil, errors.Wrap(err, "Failed to unmarshal attributes from certificate") - } - } - return attrs, nil -} - -func (mgr *Mgr) GetAttributesFromIdemix(creator []byte) (*Attributes, error) { - if creator == nil { - return nil, errors.New("creator is nil") - } - - sid := &msp.SerializedIdentity{} - err := proto.Unmarshal(creator, sid) - if err != nil { - return nil, errors.Wrap(err, "failed to unmarshal transaction invoker's identity") - } - idemixID := &msp.SerializedIdemixIdentity{} - err = proto.Unmarshal(sid.IdBytes, idemixID) - if err != nil { - return nil, errors.Wrap(err, "failed to unmarshal transaction invoker's idemix identity") - } - // Unmarshal into attributes object - attrs := &Attributes{ - Attrs: make(map[string]string), - } - - ou := &msp.OrganizationUnit{} - err = proto.Unmarshal(idemixID.Ou, ou) - if err != nil { - return nil, errors.Wrap(err, "failed to unmarshal transaction invoker's ou") - } - attrs.Attrs["ou"] = ou.OrganizationalUnitIdentifier - - role := &msp.MSPRole{} - err = proto.Unmarshal(idemixID.Role, role) - if err != nil { - return nil, errors.Wrap(err, "failed to unmarshal transaction invoker's role") - } - var roleStr string - switch role.Role { - case 0: - roleStr = "member" - case 1: - roleStr = "admin" - case 2: - roleStr = "client" - case 3: - roleStr = "peer" - } - attrs.Attrs["role"] = roleStr - - return attrs, nil -} - -// Attributes contains attribute names and values -type Attributes struct { - Attrs map[string]string `json:"attrs"` -} - -// Names returns the names of the attributes -func (a *Attributes) Names() []string { - i := 0 - names := make([]string, len(a.Attrs)) - for name := range a.Attrs { - names[i] = name - i++ - } - return names -} - -// Contains returns true if the named attribute is found -func (a *Attributes) Contains(name string) bool { - _, ok := a.Attrs[name] - return ok -} - -// Value returns an attribute's value -func (a *Attributes) Value(name string) (string, bool, error) { - attr, ok := a.Attrs[name] - return attr, ok, nil -} - -// True returns nil if the value of attribute 'name' is true; -// otherwise, an appropriate error is returned. -func (a *Attributes) True(name string) error { - val, ok, err := a.Value(name) - if err != nil { - return err - } - if !ok { - return fmt.Errorf("Attribute '%s' was not found", name) - } - if val != "true" { - return fmt.Errorf("Attribute '%s' is not true", name) - } - return nil -} - -// Get the attribute info from a certificate extension, or return nil if not found -func getAttributesFromCert(cert *x509.Certificate) ([]byte, error) { - for _, ext := range cert.Extensions { - if isAttrOID(ext.Id) { - return ext.Value, nil - } - } - return nil, nil -} - -// Is the object ID equal to the attribute info object ID? -func isAttrOID(oid asn1.ObjectIdentifier) bool { - if len(oid) != len(AttrOID) { - return false - } - for idx, val := range oid { - if val != AttrOID[idx] { - return false - } - } - return true -} - -// Get an attribute from 'attrs' by its name, or nil if not found -func getAttrByName(name string, attrs []Attribute) Attribute { - for _, attr := range attrs { - if attr.GetName() == name { - return attr - } - } - return nil -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/cid/README.md b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/cid/README.md deleted file mode 100644 index bd3f667a8..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/cid/README.md +++ /dev/null @@ -1,217 +0,0 @@ - - - -# Client Identity Chaincode Library - -The client identity chaincode library enables you to write chaincode which -makes access control decisions based on the identity of the client -(i.e. the invoker of the chaincode). In particular, you may make access -control decisions based on either or both of the following associated with -the client: - -* the client identity's MSP (Membership Service Provider) ID -* an attribute associated with the client identity - -Attributes are simply name and value pairs associated with an identity. -For example, `email=me@gmail.com` indicates an identity has the `email` -attribute with a value of `me@gmail.com`. - - -## Using the client identity chaincode library - -This section describes how to use the client identity chaincode library. - -All code samples below assume two things: -1. The type of the `stub` variable is `ChaincodeStubInterface` as passed - to your chaincode. -2. You have added the following import statement to your chaincode. - ``` - import "github.com/hyperledger/fabric/core/chaincode/lib/cid" - ``` -#### Getting the client's ID - -The following demonstrates how to get an ID for the client which is guaranteed -to be unique within the MSP: - -``` -id, err := cid.GetID(stub) -``` - -#### Getting the MSP ID - -The following demonstrates how to get the MSP ID of the client's identity: - -``` -mspid, err := cid.GetMSPID(stub) -``` - -#### Getting an attribute value - -The following demonstrates how to get the value of the *attr1* attribute: - -``` -val, ok, err := cid.GetAttributeValue(stub, "attr1") -if err != nil { - // There was an error trying to retrieve the attribute -} -if !ok { - // The client identity does not possess the attribute -} -// Do something with the value of 'val' -``` - -#### Asserting an attribute value - -Often all you want to do is to make an access control decision based on the value -of an attribute, i.e. to assert the value of an attribute. For example, the following -will return an error if the client does not have the `myapp.admin` attribute -with a value of `true`: - -``` -err := cid.AssertAttributeValue(stub, "myapp.admin", "true") -if err != nil { - // Return an error -} -``` - -This is effectively using attributes to implement role-based access control, -or RBAC for short. - -#### Getting the client's X509 certificate - -The following demonstrates how to get the X509 certificate of the client, or -nil if the client's identity was not based on an X509 certificate: - -``` -cert, err := cid.GetX509Certificate(stub) -``` - -Note that both `cert` and `err` may be nil as will be the case if the identity -is not using an X509 certificate. - -#### Performing multiple operations more efficiently - -Sometimes you may need to perform multiple operations in order to make an access -decision. For example, the following demonstrates how to grant access to -identities with MSP *org1MSP* and *attr1* OR with MSP *org1MSP* and *attr2*. - -``` -// Get the client ID object -id, err := cid.New(stub) -if err != nil { - // Handle error -} -mspid, err := id.GetMSPID() -if err != nil { - // Handle error -} -switch mspid { - case "org1MSP": - err = id.AssertAttributeValue("attr1", "true") - case "org2MSP": - err = id.AssertAttributeValue("attr2", "true") - default: - err = errors.New("Wrong MSP") -} -``` -Although it is not required, it is more efficient to make the `cid.New` call -to get the ClientIdentity object if you need to perform multiple operations, -as demonstrated above. - -## Adding Attributes to Identities - -This section describes how to add custom attributes to certificates when -using Hyperledger Fabric CA as well as when using an external CA. - -#### Managing attributes with Fabric CA - -There are two methods of adding attributes to an enrollment certificate -with fabric-ca: - - 1. When you register an identity, you can specify that an enrollment certificate - issued for the identity should by default contain an attribute. This behavior - can be overridden at enrollment time, but this is useful for establishing - default behavior and, assuming registration occurs outside of your application, - does not require any application change. - - The following shows how to register *user1* with two attributes: - *app1Admin* and *email*. - The ":ecert" suffix causes the *appAdmin* attribute to be inserted into user1's - enrollment certificate by default. The *email* attribute is not added - to the enrollment certificate by default. - - ``` - fabric-ca-client register --id.name user1 --id.secret user1pw --id.type user --id.affiliation org1 --id.attrs 'app1Admin=true:ecert,email=user1@gmail.com' - ``` - - 2. When you enroll an identity, you may request that one or more attributes - be added to the certificate. - For each attribute requested, you may specify whether the attribute is - optional or not. If it is not optional but does not exist for the identity, - enrollment fails. - - The following shows how to enroll *user1* with the *email* attribute, - without the *app1Admin* attribute and optionally with the *phone* attribute - (if the user possesses *phone* attribute). - ``` - fabric-ca-client enroll -u http://user1:user1pw@localhost:7054 --enrollment.attrs "email,phone:opt" - ``` -#### Attribute format in a certificate - -Attributes are stored inside an X509 certificate as an extension with an -ASN.1 OID (Abstract Syntax Notation Object IDentifier) -of `1.2.3.4.5.6.7.8.1`. The value of the extension is a JSON string of the -form `{"attrs":{: 0 { - s += "," - } - for j, tv := range rdn { - if j > 0 { - s += "+" - } - typeString := tv.Type.String() - typeName, ok := attributeTypeNames[typeString] - if !ok { - derBytes, err := asn1.Marshal(tv.Value) - if err == nil { - s += typeString + "=#" + hex.EncodeToString(derBytes) - continue // No value escaping necessary. - } - typeName = typeString - } - valueString := fmt.Sprint(tv.Value) - escaped := "" - begin := 0 - for idx, c := range valueString { - if (idx == 0 && (c == ' ' || c == '#')) || - (idx == len(valueString)-1 && c == ' ') { - escaped += valueString[begin:idx] - escaped += "\\" + string(c) - begin = idx + 1 - continue - } - switch c { - case ',', '+', '"', '\\', '<', '>', ';': - escaped += valueString[begin:idx] - escaped += "\\" + string(c) - begin = idx + 1 - } - } - escaped += valueString[begin:] - s += typeName + "=" + escaped - } - } - return s -} - -var attributeTypeNames = map[string]string{ - "2.5.4.6": "C", - "2.5.4.10": "O", - "2.5.4.11": "OU", - "2.5.4.3": "CN", - "2.5.4.5": "SERIALNUMBER", - "2.5.4.7": "L", - "2.5.4.8": "ST", - "2.5.4.9": "STREET", - "2.5.4.17": "POSTALCODE", -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/cid/interfaces.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/cid/interfaces.go deleted file mode 100644 index 27b021f61..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/core/chaincode/shim/ext/cid/interfaces.go +++ /dev/null @@ -1,59 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package cid - -import "crypto/x509" - -// ChaincodeStubInterface is used by deployable chaincode apps to get identity -// of the agent (or user) submitting the transaction. -type ChaincodeStubInterface interface { - // GetCreator returns `SignatureHeader.Creator` (e.g. an identity) - // of the `SignedProposal`. This is the identity of the agent (or user) - // submitting the transaction. - GetCreator() ([]byte, error) -} - -// ClientIdentity represents information about the identity that submitted the -// transaction -type ClientIdentity interface { - - // GetID returns the ID associated with the invoking identity. This ID - // is guaranteed to be unique within the MSP. - GetID() (string, error) - - // Return the MSP ID of the client - GetMSPID() (string, error) - - // GetAttributeValue returns the value of the client's attribute named `attrName`. - // If the client possesses the attribute, `found` is true and `value` equals the - // value of the attribute. - // If the client does not possess the attribute, `found` is false and `value` - // equals "". - GetAttributeValue(attrName string) (value string, found bool, err error) - - // AssertAttributeValue verifies that the client has the attribute named `attrName` - // with a value of `attrValue`; otherwise, an error is returned. - AssertAttributeValue(attrName, attrValue string) error - - // GetX509Certificate returns the X509 certificate associated with the client, - // or nil if it was not identified by an X509 certificate. - GetX509Certificate() (*x509.Certificate, error) -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/identities.pb.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/identities.pb.go deleted file mode 100644 index de1435ebe..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/identities.pb.go +++ /dev/null @@ -1,183 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: msp/identities.proto - -package msp // import "github.com/hyperledger/fabric/protos/msp" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// This struct represents an Identity -// (with its MSP identifier) to be used -// to serialize it and deserialize it -type SerializedIdentity struct { - // The identifier of the associated membership service provider - Mspid string `protobuf:"bytes,1,opt,name=mspid,proto3" json:"mspid,omitempty"` - // the Identity, serialized according to the rules of its MPS - IdBytes []byte `protobuf:"bytes,2,opt,name=id_bytes,json=idBytes,proto3" json:"id_bytes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SerializedIdentity) Reset() { *m = SerializedIdentity{} } -func (m *SerializedIdentity) String() string { return proto.CompactTextString(m) } -func (*SerializedIdentity) ProtoMessage() {} -func (*SerializedIdentity) Descriptor() ([]byte, []int) { - return fileDescriptor_identities_8fa8af3e5bf2070a, []int{0} -} -func (m *SerializedIdentity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SerializedIdentity.Unmarshal(m, b) -} -func (m *SerializedIdentity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SerializedIdentity.Marshal(b, m, deterministic) -} -func (dst *SerializedIdentity) XXX_Merge(src proto.Message) { - xxx_messageInfo_SerializedIdentity.Merge(dst, src) -} -func (m *SerializedIdentity) XXX_Size() int { - return xxx_messageInfo_SerializedIdentity.Size(m) -} -func (m *SerializedIdentity) XXX_DiscardUnknown() { - xxx_messageInfo_SerializedIdentity.DiscardUnknown(m) -} - -var xxx_messageInfo_SerializedIdentity proto.InternalMessageInfo - -func (m *SerializedIdentity) GetMspid() string { - if m != nil { - return m.Mspid - } - return "" -} - -func (m *SerializedIdentity) GetIdBytes() []byte { - if m != nil { - return m.IdBytes - } - return nil -} - -// This struct represents an Idemix Identity -// to be used to serialize it and deserialize it. -// The IdemixMSP will first serialize an idemix identity to bytes using -// this proto, and then uses these bytes as id_bytes in SerializedIdentity -type SerializedIdemixIdentity struct { - // nym_x is the X-component of the pseudonym elliptic curve point. - // It is a []byte representation of an amcl.BIG - // The pseudonym can be seen as a public key of the identity, it is used to verify signatures. - NymX []byte `protobuf:"bytes,1,opt,name=nym_x,json=nymX,proto3" json:"nym_x,omitempty"` - // nym_y is the Y-component of the pseudonym elliptic curve point. - // It is a []byte representation of an amcl.BIG - // The pseudonym can be seen as a public key of the identity, it is used to verify signatures. - NymY []byte `protobuf:"bytes,2,opt,name=nym_y,json=nymY,proto3" json:"nym_y,omitempty"` - // ou contains the organizational unit of the idemix identity - Ou []byte `protobuf:"bytes,3,opt,name=ou,proto3" json:"ou,omitempty"` - // role contains the role of this identity (e.g., ADMIN or MEMBER) - Role []byte `protobuf:"bytes,4,opt,name=role,proto3" json:"role,omitempty"` - // proof contains the cryptographic evidence that this identity is valid - Proof []byte `protobuf:"bytes,5,opt,name=proof,proto3" json:"proof,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SerializedIdemixIdentity) Reset() { *m = SerializedIdemixIdentity{} } -func (m *SerializedIdemixIdentity) String() string { return proto.CompactTextString(m) } -func (*SerializedIdemixIdentity) ProtoMessage() {} -func (*SerializedIdemixIdentity) Descriptor() ([]byte, []int) { - return fileDescriptor_identities_8fa8af3e5bf2070a, []int{1} -} -func (m *SerializedIdemixIdentity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SerializedIdemixIdentity.Unmarshal(m, b) -} -func (m *SerializedIdemixIdentity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SerializedIdemixIdentity.Marshal(b, m, deterministic) -} -func (dst *SerializedIdemixIdentity) XXX_Merge(src proto.Message) { - xxx_messageInfo_SerializedIdemixIdentity.Merge(dst, src) -} -func (m *SerializedIdemixIdentity) XXX_Size() int { - return xxx_messageInfo_SerializedIdemixIdentity.Size(m) -} -func (m *SerializedIdemixIdentity) XXX_DiscardUnknown() { - xxx_messageInfo_SerializedIdemixIdentity.DiscardUnknown(m) -} - -var xxx_messageInfo_SerializedIdemixIdentity proto.InternalMessageInfo - -func (m *SerializedIdemixIdentity) GetNymX() []byte { - if m != nil { - return m.NymX - } - return nil -} - -func (m *SerializedIdemixIdentity) GetNymY() []byte { - if m != nil { - return m.NymY - } - return nil -} - -func (m *SerializedIdemixIdentity) GetOu() []byte { - if m != nil { - return m.Ou - } - return nil -} - -func (m *SerializedIdemixIdentity) GetRole() []byte { - if m != nil { - return m.Role - } - return nil -} - -func (m *SerializedIdemixIdentity) GetProof() []byte { - if m != nil { - return m.Proof - } - return nil -} - -func init() { - proto.RegisterType((*SerializedIdentity)(nil), "msp.SerializedIdentity") - proto.RegisterType((*SerializedIdemixIdentity)(nil), "msp.SerializedIdemixIdentity") -} - -func init() { proto.RegisterFile("msp/identities.proto", fileDescriptor_identities_8fa8af3e5bf2070a) } - -var fileDescriptor_identities_8fa8af3e5bf2070a = []byte{ - // 238 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x54, 0x8f, 0x3f, 0x4f, 0xc3, 0x30, - 0x10, 0x47, 0x95, 0x34, 0xe1, 0x8f, 0x55, 0x31, 0x98, 0x0e, 0x66, 0x2b, 0x9d, 0x32, 0xc5, 0x03, - 0xdf, 0xa0, 0x12, 0x03, 0x03, 0x4b, 0x58, 0x80, 0xa5, 0x6a, 0xea, 0x6b, 0x7a, 0x52, 0x2e, 0x67, - 0xd9, 0x8e, 0x54, 0x33, 0xf0, 0xd9, 0x51, 0x62, 0x40, 0xb0, 0xdd, 0xef, 0xe9, 0xe9, 0xc9, 0x16, - 0x2b, 0xf2, 0x56, 0xa3, 0x81, 0x21, 0x60, 0x40, 0xf0, 0xb5, 0x75, 0x1c, 0x58, 0x2e, 0xc8, 0xdb, - 0xcd, 0xa3, 0x90, 0x2f, 0xe0, 0x70, 0xdf, 0xe3, 0x07, 0x98, 0xa7, 0xa4, 0x44, 0xb9, 0x12, 0x25, - 0x79, 0x8b, 0x46, 0x65, 0xeb, 0xac, 0xba, 0x6e, 0xd2, 0x90, 0x77, 0xe2, 0x0a, 0xcd, 0xae, 0x8d, - 0x01, 0xbc, 0xca, 0xd7, 0x59, 0xb5, 0x6c, 0x2e, 0xd1, 0x6c, 0xa7, 0xb9, 0xf9, 0x14, 0xea, 0x5f, - 0x86, 0xf0, 0xfc, 0x1b, 0xbb, 0x15, 0xe5, 0x10, 0x69, 0x77, 0x9e, 0x63, 0xcb, 0xa6, 0x18, 0x22, - 0xbd, 0xfe, 0xc0, 0xf8, 0x1d, 0x9a, 0xe0, 0x9b, 0xbc, 0x11, 0x39, 0x8f, 0x6a, 0x31, 0x93, 0x9c, - 0x47, 0x29, 0x45, 0xe1, 0xb8, 0x07, 0x55, 0x24, 0x67, 0xba, 0xa7, 0xa7, 0x59, 0xc7, 0x7c, 0x54, - 0xe5, 0x0c, 0xd3, 0xd8, 0x3e, 0x8b, 0x7b, 0x76, 0x5d, 0x7d, 0x8a, 0x16, 0x5c, 0x0f, 0xa6, 0x03, - 0x57, 0x1f, 0xf7, 0xad, 0xc3, 0x43, 0xfa, 0xab, 0xaf, 0xc9, 0xdb, 0xf7, 0xaa, 0xc3, 0x70, 0x1a, - 0xdb, 0xfa, 0xc0, 0xa4, 0xff, 0x98, 0x3a, 0x99, 0x3a, 0x99, 0x9a, 0xbc, 0x6d, 0x2f, 0xe6, 0xfb, - 0xe1, 0x2b, 0x00, 0x00, 0xff, 0xff, 0x13, 0xdc, 0xc8, 0x62, 0x39, 0x01, 0x00, 0x00, -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/identities.proto b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/identities.proto deleted file mode 100644 index fef457c85..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/identities.proto +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - - -syntax = "proto3"; - -option go_package = "github.com/hyperledger/fabric/protos/msp"; -option java_package = "org.hyperledger.fabric.protos.msp"; - -package msp; - -// This struct represents an Identity -// (with its MSP identifier) to be used -// to serialize it and deserialize it -message SerializedIdentity { - // The identifier of the associated membership service provider - string mspid = 1; - - // the Identity, serialized according to the rules of its MPS - bytes id_bytes = 2; -} - -// This struct represents an Idemix Identity -// to be used to serialize it and deserialize it. -// The IdemixMSP will first serialize an idemix identity to bytes using -// this proto, and then uses these bytes as id_bytes in SerializedIdentity -message SerializedIdemixIdentity { - // nym_x is the X-component of the pseudonym elliptic curve point. - // It is a []byte representation of an amcl.BIG - // The pseudonym can be seen as a public key of the identity, it is used to verify signatures. - bytes nym_x = 1; - - // nym_y is the Y-component of the pseudonym elliptic curve point. - // It is a []byte representation of an amcl.BIG - // The pseudonym can be seen as a public key of the identity, it is used to verify signatures. - bytes nym_y = 2; - - // ou contains the organizational unit of the idemix identity - bytes ou = 3; - - // role contains the role of this identity (e.g., ADMIN or MEMBER) - bytes role = 4; - - // proof contains the cryptographic evidence that this identity is valid - bytes proof = 5; -} \ No newline at end of file diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.go deleted file mode 100644 index b8e9bb5ae..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.go +++ /dev/null @@ -1,45 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package msp - -import ( - "fmt" - - "github.com/golang/protobuf/proto" -) - -func (mc *MSPConfig) VariablyOpaqueFields() []string { - return []string{"config"} -} - -func (mc *MSPConfig) VariablyOpaqueFieldProto(name string) (proto.Message, error) { - if name != mc.VariablyOpaqueFields()[0] { - return nil, fmt.Errorf("not a marshaled field: %s", name) - } - switch mc.Type { - case 0: - return &FabricMSPConfig{}, nil - case 1: - return &IdemixMSPConfig{}, nil - default: - return nil, fmt.Errorf("unable to decode MSP type: %v", mc.Type) - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.pb.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.pb.go deleted file mode 100644 index bfe7e1a5a..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.pb.go +++ /dev/null @@ -1,747 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: msp/msp_config.proto - -package msp // import "github.com/hyperledger/fabric/protos/msp" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// MSPConfig collects all the configuration information for -// an MSP. The Config field should be unmarshalled in a way -// that depends on the Type -type MSPConfig struct { - // Type holds the type of the MSP; the default one would - // be of type FABRIC implementing an X.509 based provider - Type int32 `protobuf:"varint,1,opt,name=type,proto3" json:"type,omitempty"` - // Config is MSP dependent configuration info - Config []byte `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MSPConfig) Reset() { *m = MSPConfig{} } -func (m *MSPConfig) String() string { return proto.CompactTextString(m) } -func (*MSPConfig) ProtoMessage() {} -func (*MSPConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{0} -} -func (m *MSPConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MSPConfig.Unmarshal(m, b) -} -func (m *MSPConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MSPConfig.Marshal(b, m, deterministic) -} -func (dst *MSPConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_MSPConfig.Merge(dst, src) -} -func (m *MSPConfig) XXX_Size() int { - return xxx_messageInfo_MSPConfig.Size(m) -} -func (m *MSPConfig) XXX_DiscardUnknown() { - xxx_messageInfo_MSPConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_MSPConfig proto.InternalMessageInfo - -func (m *MSPConfig) GetType() int32 { - if m != nil { - return m.Type - } - return 0 -} - -func (m *MSPConfig) GetConfig() []byte { - if m != nil { - return m.Config - } - return nil -} - -// FabricMSPConfig collects all the configuration information for -// a Fabric MSP. -// Here we assume a default certificate validation policy, where -// any certificate signed by any of the listed rootCA certs would -// be considered as valid under this MSP. -// This MSP may or may not come with a signing identity. If it does, -// it can also issue signing identities. If it does not, it can only -// be used to validate and verify certificates. -type FabricMSPConfig struct { - // Name holds the identifier of the MSP; MSP identifier - // is chosen by the application that governs this MSP. - // For example, and assuming the default implementation of MSP, - // that is X.509-based and considers a single Issuer, - // this can refer to the Subject OU field or the Issuer OU field. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // List of root certificates trusted by this MSP - // they are used upon certificate validation (see - // comment for IntermediateCerts below) - RootCerts [][]byte `protobuf:"bytes,2,rep,name=root_certs,json=rootCerts,proto3" json:"root_certs,omitempty"` - // List of intermediate certificates trusted by this MSP; - // they are used upon certificate validation as follows: - // validation attempts to build a path from the certificate - // to be validated (which is at one end of the path) and - // one of the certs in the RootCerts field (which is at - // the other end of the path). If the path is longer than - // 2, certificates in the middle are searched within the - // IntermediateCerts pool - IntermediateCerts [][]byte `protobuf:"bytes,3,rep,name=intermediate_certs,json=intermediateCerts,proto3" json:"intermediate_certs,omitempty"` - // Identity denoting the administrator of this MSP - Admins [][]byte `protobuf:"bytes,4,rep,name=admins,proto3" json:"admins,omitempty"` - // Identity revocation list - RevocationList [][]byte `protobuf:"bytes,5,rep,name=revocation_list,json=revocationList,proto3" json:"revocation_list,omitempty"` - // SigningIdentity holds information on the signing identity - // this peer is to use, and which is to be imported by the - // MSP defined before - SigningIdentity *SigningIdentityInfo `protobuf:"bytes,6,opt,name=signing_identity,json=signingIdentity,proto3" json:"signing_identity,omitempty"` - // OrganizationalUnitIdentifiers holds one or more - // fabric organizational unit identifiers that belong to - // this MSP configuration - OrganizationalUnitIdentifiers []*FabricOUIdentifier `protobuf:"bytes,7,rep,name=organizational_unit_identifiers,json=organizationalUnitIdentifiers,proto3" json:"organizational_unit_identifiers,omitempty"` - // FabricCryptoConfig contains the configuration parameters - // for the cryptographic algorithms used by this MSP - CryptoConfig *FabricCryptoConfig `protobuf:"bytes,8,opt,name=crypto_config,json=cryptoConfig,proto3" json:"crypto_config,omitempty"` - // List of TLS root certificates trusted by this MSP. - // They are returned by GetTLSRootCerts. - TlsRootCerts [][]byte `protobuf:"bytes,9,rep,name=tls_root_certs,json=tlsRootCerts,proto3" json:"tls_root_certs,omitempty"` - // List of TLS intermediate certificates trusted by this MSP; - // They are returned by GetTLSIntermediateCerts. - TlsIntermediateCerts [][]byte `protobuf:"bytes,10,rep,name=tls_intermediate_certs,json=tlsIntermediateCerts,proto3" json:"tls_intermediate_certs,omitempty"` - // fabric_node_ous contains the configuration to distinguish clients from peers from orderers - // based on the OUs. - FabricNodeOus *FabricNodeOUs `protobuf:"bytes,11,opt,name=fabric_node_ous,json=fabricNodeOus,proto3" json:"fabric_node_ous,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FabricMSPConfig) Reset() { *m = FabricMSPConfig{} } -func (m *FabricMSPConfig) String() string { return proto.CompactTextString(m) } -func (*FabricMSPConfig) ProtoMessage() {} -func (*FabricMSPConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{1} -} -func (m *FabricMSPConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FabricMSPConfig.Unmarshal(m, b) -} -func (m *FabricMSPConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FabricMSPConfig.Marshal(b, m, deterministic) -} -func (dst *FabricMSPConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_FabricMSPConfig.Merge(dst, src) -} -func (m *FabricMSPConfig) XXX_Size() int { - return xxx_messageInfo_FabricMSPConfig.Size(m) -} -func (m *FabricMSPConfig) XXX_DiscardUnknown() { - xxx_messageInfo_FabricMSPConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_FabricMSPConfig proto.InternalMessageInfo - -func (m *FabricMSPConfig) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *FabricMSPConfig) GetRootCerts() [][]byte { - if m != nil { - return m.RootCerts - } - return nil -} - -func (m *FabricMSPConfig) GetIntermediateCerts() [][]byte { - if m != nil { - return m.IntermediateCerts - } - return nil -} - -func (m *FabricMSPConfig) GetAdmins() [][]byte { - if m != nil { - return m.Admins - } - return nil -} - -func (m *FabricMSPConfig) GetRevocationList() [][]byte { - if m != nil { - return m.RevocationList - } - return nil -} - -func (m *FabricMSPConfig) GetSigningIdentity() *SigningIdentityInfo { - if m != nil { - return m.SigningIdentity - } - return nil -} - -func (m *FabricMSPConfig) GetOrganizationalUnitIdentifiers() []*FabricOUIdentifier { - if m != nil { - return m.OrganizationalUnitIdentifiers - } - return nil -} - -func (m *FabricMSPConfig) GetCryptoConfig() *FabricCryptoConfig { - if m != nil { - return m.CryptoConfig - } - return nil -} - -func (m *FabricMSPConfig) GetTlsRootCerts() [][]byte { - if m != nil { - return m.TlsRootCerts - } - return nil -} - -func (m *FabricMSPConfig) GetTlsIntermediateCerts() [][]byte { - if m != nil { - return m.TlsIntermediateCerts - } - return nil -} - -func (m *FabricMSPConfig) GetFabricNodeOus() *FabricNodeOUs { - if m != nil { - return m.FabricNodeOus - } - return nil -} - -// FabricCryptoConfig contains configuration parameters -// for the cryptographic algorithms used by the MSP -// this configuration refers to -type FabricCryptoConfig struct { - // SignatureHashFamily is a string representing the hash family to be used - // during sign and verify operations. - // Allowed values are "SHA2" and "SHA3". - SignatureHashFamily string `protobuf:"bytes,1,opt,name=signature_hash_family,json=signatureHashFamily,proto3" json:"signature_hash_family,omitempty"` - // IdentityIdentifierHashFunction is a string representing the hash function - // to be used during the computation of the identity identifier of an MSP identity. - // Allowed values are "SHA256", "SHA384" and "SHA3_256", "SHA3_384". - IdentityIdentifierHashFunction string `protobuf:"bytes,2,opt,name=identity_identifier_hash_function,json=identityIdentifierHashFunction,proto3" json:"identity_identifier_hash_function,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FabricCryptoConfig) Reset() { *m = FabricCryptoConfig{} } -func (m *FabricCryptoConfig) String() string { return proto.CompactTextString(m) } -func (*FabricCryptoConfig) ProtoMessage() {} -func (*FabricCryptoConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{2} -} -func (m *FabricCryptoConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FabricCryptoConfig.Unmarshal(m, b) -} -func (m *FabricCryptoConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FabricCryptoConfig.Marshal(b, m, deterministic) -} -func (dst *FabricCryptoConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_FabricCryptoConfig.Merge(dst, src) -} -func (m *FabricCryptoConfig) XXX_Size() int { - return xxx_messageInfo_FabricCryptoConfig.Size(m) -} -func (m *FabricCryptoConfig) XXX_DiscardUnknown() { - xxx_messageInfo_FabricCryptoConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_FabricCryptoConfig proto.InternalMessageInfo - -func (m *FabricCryptoConfig) GetSignatureHashFamily() string { - if m != nil { - return m.SignatureHashFamily - } - return "" -} - -func (m *FabricCryptoConfig) GetIdentityIdentifierHashFunction() string { - if m != nil { - return m.IdentityIdentifierHashFunction - } - return "" -} - -// IdemixMSPConfig collects all the configuration information for -// an Idemix MSP. -type IdemixMSPConfig struct { - // Name holds the identifier of the MSP - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // ipk represents the (serialized) issuer public key - Ipk []byte `protobuf:"bytes,2,opt,name=ipk,proto3" json:"ipk,omitempty"` - // signer may contain crypto material to configure a default signer - Signer *IdemixMSPSignerConfig `protobuf:"bytes,3,opt,name=signer,proto3" json:"signer,omitempty"` - // revocation_pk is the public key used for revocation of credentials - RevocationPk []byte `protobuf:"bytes,4,opt,name=revocation_pk,json=revocationPk,proto3" json:"revocation_pk,omitempty"` - // epoch represents the current epoch (time interval) used for revocation - Epoch int64 `protobuf:"varint,5,opt,name=epoch,proto3" json:"epoch,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *IdemixMSPConfig) Reset() { *m = IdemixMSPConfig{} } -func (m *IdemixMSPConfig) String() string { return proto.CompactTextString(m) } -func (*IdemixMSPConfig) ProtoMessage() {} -func (*IdemixMSPConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{3} -} -func (m *IdemixMSPConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_IdemixMSPConfig.Unmarshal(m, b) -} -func (m *IdemixMSPConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_IdemixMSPConfig.Marshal(b, m, deterministic) -} -func (dst *IdemixMSPConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_IdemixMSPConfig.Merge(dst, src) -} -func (m *IdemixMSPConfig) XXX_Size() int { - return xxx_messageInfo_IdemixMSPConfig.Size(m) -} -func (m *IdemixMSPConfig) XXX_DiscardUnknown() { - xxx_messageInfo_IdemixMSPConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_IdemixMSPConfig proto.InternalMessageInfo - -func (m *IdemixMSPConfig) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *IdemixMSPConfig) GetIpk() []byte { - if m != nil { - return m.Ipk - } - return nil -} - -func (m *IdemixMSPConfig) GetSigner() *IdemixMSPSignerConfig { - if m != nil { - return m.Signer - } - return nil -} - -func (m *IdemixMSPConfig) GetRevocationPk() []byte { - if m != nil { - return m.RevocationPk - } - return nil -} - -func (m *IdemixMSPConfig) GetEpoch() int64 { - if m != nil { - return m.Epoch - } - return 0 -} - -// IdemixMSPSIgnerConfig contains the crypto material to set up an idemix signing identity -type IdemixMSPSignerConfig struct { - // cred represents the serialized idemix credential of the default signer - Cred []byte `protobuf:"bytes,1,opt,name=cred,proto3" json:"cred,omitempty"` - // sk is the secret key of the default signer, corresponding to credential Cred - Sk []byte `protobuf:"bytes,2,opt,name=sk,proto3" json:"sk,omitempty"` - // organizational_unit_identifier defines the organizational unit the default signer is in - OrganizationalUnitIdentifier string `protobuf:"bytes,3,opt,name=organizational_unit_identifier,json=organizationalUnitIdentifier,proto3" json:"organizational_unit_identifier,omitempty"` - // role defines whether the default signer is admin, peer, member or client - Role int32 `protobuf:"varint,4,opt,name=role,proto3" json:"role,omitempty"` - // enrollment_id contains the enrollment id of this signer - EnrollmentId string `protobuf:"bytes,5,opt,name=enrollment_id,json=enrollmentId,proto3" json:"enrollment_id,omitempty"` - // credential_revocation_information contains a serialized CredentialRevocationInformation - CredentialRevocationInformation []byte `protobuf:"bytes,6,opt,name=credential_revocation_information,json=credentialRevocationInformation,proto3" json:"credential_revocation_information,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *IdemixMSPSignerConfig) Reset() { *m = IdemixMSPSignerConfig{} } -func (m *IdemixMSPSignerConfig) String() string { return proto.CompactTextString(m) } -func (*IdemixMSPSignerConfig) ProtoMessage() {} -func (*IdemixMSPSignerConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{4} -} -func (m *IdemixMSPSignerConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_IdemixMSPSignerConfig.Unmarshal(m, b) -} -func (m *IdemixMSPSignerConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_IdemixMSPSignerConfig.Marshal(b, m, deterministic) -} -func (dst *IdemixMSPSignerConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_IdemixMSPSignerConfig.Merge(dst, src) -} -func (m *IdemixMSPSignerConfig) XXX_Size() int { - return xxx_messageInfo_IdemixMSPSignerConfig.Size(m) -} -func (m *IdemixMSPSignerConfig) XXX_DiscardUnknown() { - xxx_messageInfo_IdemixMSPSignerConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_IdemixMSPSignerConfig proto.InternalMessageInfo - -func (m *IdemixMSPSignerConfig) GetCred() []byte { - if m != nil { - return m.Cred - } - return nil -} - -func (m *IdemixMSPSignerConfig) GetSk() []byte { - if m != nil { - return m.Sk - } - return nil -} - -func (m *IdemixMSPSignerConfig) GetOrganizationalUnitIdentifier() string { - if m != nil { - return m.OrganizationalUnitIdentifier - } - return "" -} - -func (m *IdemixMSPSignerConfig) GetRole() int32 { - if m != nil { - return m.Role - } - return 0 -} - -func (m *IdemixMSPSignerConfig) GetEnrollmentId() string { - if m != nil { - return m.EnrollmentId - } - return "" -} - -func (m *IdemixMSPSignerConfig) GetCredentialRevocationInformation() []byte { - if m != nil { - return m.CredentialRevocationInformation - } - return nil -} - -// SigningIdentityInfo represents the configuration information -// related to the signing identity the peer is to use for generating -// endorsements -type SigningIdentityInfo struct { - // PublicSigner carries the public information of the signing - // identity. For an X.509 provider this would be represented by - // an X.509 certificate - PublicSigner []byte `protobuf:"bytes,1,opt,name=public_signer,json=publicSigner,proto3" json:"public_signer,omitempty"` - // PrivateSigner denotes a reference to the private key of the - // peer's signing identity - PrivateSigner *KeyInfo `protobuf:"bytes,2,opt,name=private_signer,json=privateSigner,proto3" json:"private_signer,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SigningIdentityInfo) Reset() { *m = SigningIdentityInfo{} } -func (m *SigningIdentityInfo) String() string { return proto.CompactTextString(m) } -func (*SigningIdentityInfo) ProtoMessage() {} -func (*SigningIdentityInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{5} -} -func (m *SigningIdentityInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SigningIdentityInfo.Unmarshal(m, b) -} -func (m *SigningIdentityInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SigningIdentityInfo.Marshal(b, m, deterministic) -} -func (dst *SigningIdentityInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_SigningIdentityInfo.Merge(dst, src) -} -func (m *SigningIdentityInfo) XXX_Size() int { - return xxx_messageInfo_SigningIdentityInfo.Size(m) -} -func (m *SigningIdentityInfo) XXX_DiscardUnknown() { - xxx_messageInfo_SigningIdentityInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_SigningIdentityInfo proto.InternalMessageInfo - -func (m *SigningIdentityInfo) GetPublicSigner() []byte { - if m != nil { - return m.PublicSigner - } - return nil -} - -func (m *SigningIdentityInfo) GetPrivateSigner() *KeyInfo { - if m != nil { - return m.PrivateSigner - } - return nil -} - -// KeyInfo represents a (secret) key that is either already stored -// in the bccsp/keystore or key material to be imported to the -// bccsp key-store. In later versions it may contain also a -// keystore identifier -type KeyInfo struct { - // Identifier of the key inside the default keystore; this for - // the case of Software BCCSP as well as the HSM BCCSP would be - // the SKI of the key - KeyIdentifier string `protobuf:"bytes,1,opt,name=key_identifier,json=keyIdentifier,proto3" json:"key_identifier,omitempty"` - // KeyMaterial (optional) for the key to be imported; this is - // properly encoded key bytes, prefixed by the type of the key - KeyMaterial []byte `protobuf:"bytes,2,opt,name=key_material,json=keyMaterial,proto3" json:"key_material,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *KeyInfo) Reset() { *m = KeyInfo{} } -func (m *KeyInfo) String() string { return proto.CompactTextString(m) } -func (*KeyInfo) ProtoMessage() {} -func (*KeyInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{6} -} -func (m *KeyInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_KeyInfo.Unmarshal(m, b) -} -func (m *KeyInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_KeyInfo.Marshal(b, m, deterministic) -} -func (dst *KeyInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_KeyInfo.Merge(dst, src) -} -func (m *KeyInfo) XXX_Size() int { - return xxx_messageInfo_KeyInfo.Size(m) -} -func (m *KeyInfo) XXX_DiscardUnknown() { - xxx_messageInfo_KeyInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_KeyInfo proto.InternalMessageInfo - -func (m *KeyInfo) GetKeyIdentifier() string { - if m != nil { - return m.KeyIdentifier - } - return "" -} - -func (m *KeyInfo) GetKeyMaterial() []byte { - if m != nil { - return m.KeyMaterial - } - return nil -} - -// FabricOUIdentifier represents an organizational unit and -// its related chain of trust identifier. -type FabricOUIdentifier struct { - // Certificate represents the second certificate in a certification chain. - // (Notice that the first certificate in a certification chain is supposed - // to be the certificate of an identity). - // It must correspond to the certificate of root or intermediate CA - // recognized by the MSP this message belongs to. - // Starting from this certificate, a certification chain is computed - // and bound to the OrganizationUnitIdentifier specified - Certificate []byte `protobuf:"bytes,1,opt,name=certificate,proto3" json:"certificate,omitempty"` - // OrganizationUnitIdentifier defines the organizational unit under the - // MSP identified with MSPIdentifier - OrganizationalUnitIdentifier string `protobuf:"bytes,2,opt,name=organizational_unit_identifier,json=organizationalUnitIdentifier,proto3" json:"organizational_unit_identifier,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FabricOUIdentifier) Reset() { *m = FabricOUIdentifier{} } -func (m *FabricOUIdentifier) String() string { return proto.CompactTextString(m) } -func (*FabricOUIdentifier) ProtoMessage() {} -func (*FabricOUIdentifier) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{7} -} -func (m *FabricOUIdentifier) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FabricOUIdentifier.Unmarshal(m, b) -} -func (m *FabricOUIdentifier) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FabricOUIdentifier.Marshal(b, m, deterministic) -} -func (dst *FabricOUIdentifier) XXX_Merge(src proto.Message) { - xxx_messageInfo_FabricOUIdentifier.Merge(dst, src) -} -func (m *FabricOUIdentifier) XXX_Size() int { - return xxx_messageInfo_FabricOUIdentifier.Size(m) -} -func (m *FabricOUIdentifier) XXX_DiscardUnknown() { - xxx_messageInfo_FabricOUIdentifier.DiscardUnknown(m) -} - -var xxx_messageInfo_FabricOUIdentifier proto.InternalMessageInfo - -func (m *FabricOUIdentifier) GetCertificate() []byte { - if m != nil { - return m.Certificate - } - return nil -} - -func (m *FabricOUIdentifier) GetOrganizationalUnitIdentifier() string { - if m != nil { - return m.OrganizationalUnitIdentifier - } - return "" -} - -// FabricNodeOUs contains configuration to tell apart clients from peers from orderers -// based on OUs. If NodeOUs recognition is enabled then an msp identity -// that does not contain any of the specified OU will be considered invalid. -type FabricNodeOUs struct { - // If true then an msp identity that does not contain any of the specified OU will be considered invalid. - Enable bool `protobuf:"varint,1,opt,name=enable,proto3" json:"enable,omitempty"` - // OU Identifier of the clients - ClientOuIdentifier *FabricOUIdentifier `protobuf:"bytes,2,opt,name=client_ou_identifier,json=clientOuIdentifier,proto3" json:"client_ou_identifier,omitempty"` - // OU Identifier of the peers - PeerOuIdentifier *FabricOUIdentifier `protobuf:"bytes,3,opt,name=peer_ou_identifier,json=peerOuIdentifier,proto3" json:"peer_ou_identifier,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FabricNodeOUs) Reset() { *m = FabricNodeOUs{} } -func (m *FabricNodeOUs) String() string { return proto.CompactTextString(m) } -func (*FabricNodeOUs) ProtoMessage() {} -func (*FabricNodeOUs) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_config_e749e5bd1d6d997b, []int{8} -} -func (m *FabricNodeOUs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FabricNodeOUs.Unmarshal(m, b) -} -func (m *FabricNodeOUs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FabricNodeOUs.Marshal(b, m, deterministic) -} -func (dst *FabricNodeOUs) XXX_Merge(src proto.Message) { - xxx_messageInfo_FabricNodeOUs.Merge(dst, src) -} -func (m *FabricNodeOUs) XXX_Size() int { - return xxx_messageInfo_FabricNodeOUs.Size(m) -} -func (m *FabricNodeOUs) XXX_DiscardUnknown() { - xxx_messageInfo_FabricNodeOUs.DiscardUnknown(m) -} - -var xxx_messageInfo_FabricNodeOUs proto.InternalMessageInfo - -func (m *FabricNodeOUs) GetEnable() bool { - if m != nil { - return m.Enable - } - return false -} - -func (m *FabricNodeOUs) GetClientOuIdentifier() *FabricOUIdentifier { - if m != nil { - return m.ClientOuIdentifier - } - return nil -} - -func (m *FabricNodeOUs) GetPeerOuIdentifier() *FabricOUIdentifier { - if m != nil { - return m.PeerOuIdentifier - } - return nil -} - -func init() { - proto.RegisterType((*MSPConfig)(nil), "msp.MSPConfig") - proto.RegisterType((*FabricMSPConfig)(nil), "msp.FabricMSPConfig") - proto.RegisterType((*FabricCryptoConfig)(nil), "msp.FabricCryptoConfig") - proto.RegisterType((*IdemixMSPConfig)(nil), "msp.IdemixMSPConfig") - proto.RegisterType((*IdemixMSPSignerConfig)(nil), "msp.IdemixMSPSignerConfig") - proto.RegisterType((*SigningIdentityInfo)(nil), "msp.SigningIdentityInfo") - proto.RegisterType((*KeyInfo)(nil), "msp.KeyInfo") - proto.RegisterType((*FabricOUIdentifier)(nil), "msp.FabricOUIdentifier") - proto.RegisterType((*FabricNodeOUs)(nil), "msp.FabricNodeOUs") -} - -func init() { proto.RegisterFile("msp/msp_config.proto", fileDescriptor_msp_config_e749e5bd1d6d997b) } - -var fileDescriptor_msp_config_e749e5bd1d6d997b = []byte{ - // 847 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0x5f, 0x6f, 0xe3, 0x44, - 0x10, 0x57, 0x92, 0x26, 0x77, 0x99, 0x38, 0x49, 0xd9, 0xeb, 0x15, 0x0b, 0x71, 0x77, 0xa9, 0x01, - 0x91, 0x17, 0x52, 0xa9, 0x87, 0x84, 0x84, 0x78, 0xba, 0xc2, 0x09, 0x03, 0xa5, 0xd5, 0x56, 0x7d, - 0xe1, 0xc5, 0xda, 0xd8, 0x9b, 0x64, 0x65, 0x7b, 0xd7, 0xda, 0x5d, 0x9f, 0x08, 0xe2, 0x99, 0x2f, - 0xc0, 0x77, 0xe0, 0x99, 0x57, 0xbe, 0x1d, 0xda, 0x3f, 0x8d, 0x9d, 0x6b, 0x15, 0x78, 0x9b, 0x9d, - 0xf9, 0xcd, 0xcf, 0xb3, 0xbf, 0x99, 0x59, 0xc3, 0x49, 0xa9, 0xaa, 0xf3, 0x52, 0x55, 0x49, 0x2a, - 0xf8, 0x8a, 0xad, 0x17, 0x95, 0x14, 0x5a, 0xa0, 0x5e, 0xa9, 0xaa, 0xe8, 0x2b, 0x18, 0x5e, 0xdd, - 0xde, 0x5c, 0x5a, 0x3f, 0x42, 0x70, 0xa4, 0xb7, 0x15, 0x0d, 0x3b, 0xb3, 0xce, 0xbc, 0x8f, 0xad, - 0x8d, 0x4e, 0x61, 0xe0, 0xb2, 0xc2, 0xee, 0xac, 0x33, 0x0f, 0xb0, 0x3f, 0x45, 0x7f, 0x1f, 0xc1, - 0xf4, 0x2d, 0x59, 0x4a, 0x96, 0xee, 0xe5, 0x73, 0x52, 0xba, 0xfc, 0x21, 0xb6, 0x36, 0x7a, 0x01, - 0x20, 0x85, 0xd0, 0x49, 0x4a, 0xa5, 0x56, 0x61, 0x77, 0xd6, 0x9b, 0x07, 0x78, 0x68, 0x3c, 0x97, - 0xc6, 0x81, 0xbe, 0x00, 0xc4, 0xb8, 0xa6, 0xb2, 0xa4, 0x19, 0x23, 0x9a, 0x7a, 0x58, 0xcf, 0xc2, - 0x3e, 0x68, 0x47, 0x1c, 0xfc, 0x14, 0x06, 0x24, 0x2b, 0x19, 0x57, 0xe1, 0x91, 0x85, 0xf8, 0x13, - 0xfa, 0x1c, 0xa6, 0x92, 0xbe, 0x13, 0x29, 0xd1, 0x4c, 0xf0, 0xa4, 0x60, 0x4a, 0x87, 0x7d, 0x0b, - 0x98, 0x34, 0xee, 0x9f, 0x98, 0xd2, 0xe8, 0x12, 0x8e, 0x15, 0x5b, 0x73, 0xc6, 0xd7, 0x09, 0xcb, - 0x28, 0xd7, 0x4c, 0x6f, 0xc3, 0xc1, 0xac, 0x33, 0x1f, 0x5d, 0x84, 0x8b, 0x52, 0x55, 0x8b, 0x5b, - 0x17, 0x8c, 0x7d, 0x2c, 0xe6, 0x2b, 0x81, 0xa7, 0x6a, 0xdf, 0x89, 0x12, 0x78, 0x25, 0xe4, 0x9a, - 0x70, 0xf6, 0x9b, 0x25, 0x26, 0x45, 0x52, 0x73, 0xa6, 0x3d, 0xe1, 0x8a, 0x51, 0xa9, 0xc2, 0x27, - 0xb3, 0xde, 0x7c, 0x74, 0xf1, 0xa1, 0xe5, 0x74, 0x32, 0x5d, 0xdf, 0xc5, 0xbb, 0x38, 0x7e, 0xb1, - 0x9f, 0x7f, 0xc7, 0x99, 0x6e, 0xa2, 0x0a, 0x7d, 0x03, 0xe3, 0x54, 0x6e, 0x2b, 0x2d, 0x7c, 0xc7, - 0xc2, 0xa7, 0xb6, 0xc4, 0x36, 0xdd, 0xa5, 0x8d, 0x3b, 0xe1, 0x71, 0x90, 0xb6, 0x4e, 0xe8, 0x53, - 0x98, 0xe8, 0x42, 0x25, 0x2d, 0xd9, 0x87, 0x56, 0x8b, 0x40, 0x17, 0x0a, 0xef, 0x94, 0xff, 0x12, - 0x4e, 0x0d, 0xea, 0x11, 0xf5, 0xc1, 0xa2, 0x4f, 0x74, 0xa1, 0xe2, 0x07, 0x0d, 0xf8, 0x1a, 0xa6, - 0x2b, 0xfb, 0xfd, 0x84, 0x8b, 0x8c, 0x26, 0xa2, 0x56, 0xe1, 0xc8, 0xd6, 0x86, 0x5a, 0xb5, 0xfd, - 0x2c, 0x32, 0x7a, 0x7d, 0xa7, 0xf0, 0x78, 0xd5, 0x1c, 0x6b, 0x15, 0xfd, 0xd9, 0x01, 0xf4, 0xb0, - 0x78, 0x74, 0x01, 0xcf, 0x8d, 0xc0, 0x44, 0xd7, 0x92, 0x26, 0x1b, 0xa2, 0x36, 0xc9, 0x8a, 0x94, - 0xac, 0xd8, 0xfa, 0x31, 0x7a, 0xb6, 0x0b, 0x7e, 0x4f, 0xd4, 0xe6, 0xad, 0x0d, 0xa1, 0x18, 0xce, - 0xee, 0xdb, 0xd7, 0x92, 0xdd, 0x67, 0xd7, 0x3c, 0x35, 0xb2, 0xda, 0x81, 0x1d, 0xe2, 0x97, 0xf7, - 0xc0, 0x46, 0x60, 0x4b, 0xe4, 0x51, 0xd1, 0x5f, 0x1d, 0x98, 0xc6, 0x19, 0x2d, 0xd9, 0xaf, 0x87, - 0x07, 0xf9, 0x18, 0x7a, 0xac, 0xca, 0xfd, 0x16, 0x18, 0x13, 0x5d, 0xc0, 0xc0, 0xd4, 0x46, 0x65, - 0xd8, 0xb3, 0x12, 0x7c, 0x64, 0x25, 0xd8, 0x71, 0xdd, 0xda, 0x98, 0xef, 0x90, 0x47, 0xa2, 0x4f, - 0x60, 0xdc, 0x1a, 0xd4, 0x2a, 0x0f, 0x8f, 0x2c, 0x5f, 0xd0, 0x38, 0x6f, 0x72, 0x74, 0x02, 0x7d, - 0x5a, 0x89, 0x74, 0x13, 0xf6, 0x67, 0x9d, 0x79, 0x0f, 0xbb, 0x43, 0xf4, 0x47, 0x17, 0x9e, 0x3f, - 0x4a, 0x6e, 0xca, 0x4d, 0x25, 0xcd, 0x6c, 0xb9, 0x01, 0xb6, 0x36, 0x9a, 0x40, 0x57, 0xdd, 0x57, - 0xdb, 0x55, 0x39, 0xfa, 0x16, 0x5e, 0x1e, 0x9e, 0x59, 0x7b, 0x89, 0x21, 0xfe, 0xf8, 0xd0, 0x64, - 0x9a, 0x2f, 0x49, 0x51, 0x50, 0x5b, 0x75, 0x1f, 0x5b, 0xdb, 0x5c, 0x89, 0x72, 0x29, 0x8a, 0xa2, - 0xa4, 0xdc, 0x10, 0xda, 0xaa, 0x87, 0x38, 0x68, 0x9c, 0x71, 0x86, 0x7e, 0x80, 0x33, 0x53, 0x96, - 0x21, 0x22, 0x45, 0xd2, 0x92, 0x80, 0xf1, 0x95, 0x90, 0xa5, 0xb5, 0xed, 0x22, 0x06, 0xf8, 0x55, - 0x03, 0xc4, 0x3b, 0x5c, 0xdc, 0xc0, 0x22, 0x01, 0xcf, 0x1e, 0x59, 0x53, 0x53, 0x47, 0x55, 0x2f, - 0x0b, 0x96, 0x26, 0xbe, 0x2b, 0x4e, 0x8e, 0xc0, 0x39, 0x9d, 0x60, 0xe8, 0x35, 0x4c, 0x2a, 0xc9, - 0xde, 0x99, 0x61, 0xf7, 0xa8, 0xae, 0xed, 0x5d, 0x60, 0x7b, 0xf7, 0x23, 0x75, 0x1b, 0x3f, 0xf6, - 0x18, 0x97, 0x14, 0xdd, 0xc2, 0x13, 0x1f, 0x41, 0x9f, 0xc1, 0x24, 0xa7, 0xed, 0x99, 0xf3, 0x33, - 0x32, 0xce, 0x69, 0x6b, 0xc0, 0xd0, 0x19, 0x04, 0x06, 0x56, 0x12, 0x4d, 0x25, 0x23, 0x85, 0xef, - 0xc3, 0x28, 0xa7, 0xdb, 0x2b, 0xef, 0x8a, 0x7e, 0xbf, 0x5f, 0x86, 0xf6, 0xc3, 0x80, 0x66, 0x30, - 0x32, 0x4b, 0xc8, 0x56, 0x2c, 0x25, 0x9a, 0xfa, 0x2b, 0xb4, 0x5d, 0xff, 0xa3, 0x91, 0xdd, 0xff, - 0x6e, 0x64, 0xf4, 0x4f, 0x07, 0xc6, 0x7b, 0xcb, 0x6a, 0x9e, 0x56, 0xca, 0xc9, 0xb2, 0x70, 0x1f, - 0x7d, 0x8a, 0xfd, 0x09, 0xc5, 0x70, 0x92, 0x16, 0xcc, 0xb4, 0x56, 0xd4, 0xef, 0x7f, 0xe5, 0xc0, - 0x0b, 0x87, 0x5c, 0xd2, 0x75, 0xdd, 0xba, 0xdc, 0x77, 0x80, 0x2a, 0x4a, 0xe5, 0x7b, 0x44, 0xbd, - 0xc3, 0x44, 0xc7, 0x26, 0xa5, 0x4d, 0xf3, 0x26, 0x81, 0x33, 0x21, 0xd7, 0x8b, 0xcd, 0xb6, 0xa2, - 0xb2, 0xa0, 0xd9, 0x9a, 0xca, 0x85, 0x7b, 0x68, 0xdc, 0x8f, 0x4d, 0x19, 0xa6, 0x37, 0xc7, 0x57, - 0xaa, 0x72, 0xeb, 0x71, 0x43, 0xd2, 0x9c, 0xac, 0xe9, 0x2f, 0xf3, 0x35, 0xd3, 0x9b, 0x7a, 0xb9, - 0x48, 0x45, 0x79, 0xde, 0xca, 0x3d, 0x77, 0xb9, 0xe7, 0x2e, 0xd7, 0xfc, 0x26, 0x97, 0x03, 0x6b, - 0xbf, 0xfe, 0x37, 0x00, 0x00, 0xff, 0xff, 0x54, 0x67, 0x46, 0xdb, 0x38, 0x07, 0x00, 0x00, -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.proto b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.proto deleted file mode 100644 index 542f06d82..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_config.proto +++ /dev/null @@ -1,208 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -syntax = "proto3"; - -option go_package = "github.com/hyperledger/fabric/protos/msp"; -option java_package = "org.hyperledger.fabric.protos.msp"; -option java_outer_classname = "MspConfigPackage"; - -package msp; - -// MSPConfig collects all the configuration information for -// an MSP. The Config field should be unmarshalled in a way -// that depends on the Type -message MSPConfig { - // Type holds the type of the MSP; the default one would - // be of type FABRIC implementing an X.509 based provider - int32 type = 1; - - // Config is MSP dependent configuration info - bytes config = 2; -} - -// FabricMSPConfig collects all the configuration information for -// a Fabric MSP. -// Here we assume a default certificate validation policy, where -// any certificate signed by any of the listed rootCA certs would -// be considered as valid under this MSP. -// This MSP may or may not come with a signing identity. If it does, -// it can also issue signing identities. If it does not, it can only -// be used to validate and verify certificates. -message FabricMSPConfig { - // Name holds the identifier of the MSP; MSP identifier - // is chosen by the application that governs this MSP. - // For example, and assuming the default implementation of MSP, - // that is X.509-based and considers a single Issuer, - // this can refer to the Subject OU field or the Issuer OU field. - string name = 1; - - // List of root certificates trusted by this MSP - // they are used upon certificate validation (see - // comment for IntermediateCerts below) - repeated bytes root_certs = 2; - - // List of intermediate certificates trusted by this MSP; - // they are used upon certificate validation as follows: - // validation attempts to build a path from the certificate - // to be validated (which is at one end of the path) and - // one of the certs in the RootCerts field (which is at - // the other end of the path). If the path is longer than - // 2, certificates in the middle are searched within the - // IntermediateCerts pool - repeated bytes intermediate_certs = 3; - - // Identity denoting the administrator of this MSP - repeated bytes admins = 4; - - // Identity revocation list - repeated bytes revocation_list = 5; - - // SigningIdentity holds information on the signing identity - // this peer is to use, and which is to be imported by the - // MSP defined before - SigningIdentityInfo signing_identity = 6; - - // OrganizationalUnitIdentifiers holds one or more - // fabric organizational unit identifiers that belong to - // this MSP configuration - repeated FabricOUIdentifier organizational_unit_identifiers = 7; - - // FabricCryptoConfig contains the configuration parameters - // for the cryptographic algorithms used by this MSP - FabricCryptoConfig crypto_config = 8; - - // List of TLS root certificates trusted by this MSP. - // They are returned by GetTLSRootCerts. - repeated bytes tls_root_certs = 9; - - // List of TLS intermediate certificates trusted by this MSP; - // They are returned by GetTLSIntermediateCerts. - repeated bytes tls_intermediate_certs = 10; - - // fabric_node_ous contains the configuration to distinguish clients from peers from orderers - // based on the OUs. - FabricNodeOUs fabric_node_ous = 11; -} - -// FabricCryptoConfig contains configuration parameters -// for the cryptographic algorithms used by the MSP -// this configuration refers to -message FabricCryptoConfig { - - // SignatureHashFamily is a string representing the hash family to be used - // during sign and verify operations. - // Allowed values are "SHA2" and "SHA3". - string signature_hash_family = 1; - - // IdentityIdentifierHashFunction is a string representing the hash function - // to be used during the computation of the identity identifier of an MSP identity. - // Allowed values are "SHA256", "SHA384" and "SHA3_256", "SHA3_384". - string identity_identifier_hash_function = 2; - -} - -// IdemixMSPConfig collects all the configuration information for -// an Idemix MSP. -message IdemixMSPConfig { - // Name holds the identifier of the MSP - string name = 1; - - // ipk represents the (serialized) issuer public key - bytes ipk = 2; - - // signer may contain crypto material to configure a default signer - IdemixMSPSignerConfig signer = 3; - - // revocation_pk is the public key used for revocation of credentials - bytes revocation_pk = 4; - - // epoch represents the current epoch (time interval) used for revocation - int64 epoch = 5; -} - -// IdemixMSPSIgnerConfig contains the crypto material to set up an idemix signing identity -message IdemixMSPSignerConfig { - // cred represents the serialized idemix credential of the default signer - bytes cred = 1; - - // sk is the secret key of the default signer, corresponding to credential Cred - bytes sk = 2; - - // organizational_unit_identifier defines the organizational unit the default signer is in - string organizational_unit_identifier = 3; - - // role defines whether the default signer is admin, peer, member or client - int32 role = 4; - - // enrollment_id contains the enrollment id of this signer - string enrollment_id = 5; - - // credential_revocation_information contains a serialized CredentialRevocationInformation - bytes credential_revocation_information = 6; -} - -// SigningIdentityInfo represents the configuration information -// related to the signing identity the peer is to use for generating -// endorsements -message SigningIdentityInfo { - // PublicSigner carries the public information of the signing - // identity. For an X.509 provider this would be represented by - // an X.509 certificate - bytes public_signer = 1; - - // PrivateSigner denotes a reference to the private key of the - // peer's signing identity - KeyInfo private_signer = 2; -} - -// KeyInfo represents a (secret) key that is either already stored -// in the bccsp/keystore or key material to be imported to the -// bccsp key-store. In later versions it may contain also a -// keystore identifier -message KeyInfo { - // Identifier of the key inside the default keystore; this for - // the case of Software BCCSP as well as the HSM BCCSP would be - // the SKI of the key - string key_identifier = 1; - - // KeyMaterial (optional) for the key to be imported; this is - // properly encoded key bytes, prefixed by the type of the key - bytes key_material = 2; -} - -// FabricOUIdentifier represents an organizational unit and -// its related chain of trust identifier. -message FabricOUIdentifier { - - // Certificate represents the second certificate in a certification chain. - // (Notice that the first certificate in a certification chain is supposed - // to be the certificate of an identity). - // It must correspond to the certificate of root or intermediate CA - // recognized by the MSP this message belongs to. - // Starting from this certificate, a certification chain is computed - // and bound to the OrganizationUnitIdentifier specified - bytes certificate = 1; - - // OrganizationUnitIdentifier defines the organizational unit under the - // MSP identified with MSPIdentifier - string organizational_unit_identifier = 2; -} - -// FabricNodeOUs contains configuration to tell apart clients from peers from orderers -// based on OUs. If NodeOUs recognition is enabled then an msp identity -// that does not contain any of the specified OU will be considered invalid. -message FabricNodeOUs { - // If true then an msp identity that does not contain any of the specified OU will be considered invalid. - bool enable = 1; - - // OU Identifier of the clients - FabricOUIdentifier client_ou_identifier = 2; - - // OU Identifier of the peers - FabricOUIdentifier peer_ou_identifier = 3; - -} \ No newline at end of file diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.go deleted file mode 100644 index 608d68586..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package msp - -import ( - "fmt" - - "github.com/golang/protobuf/proto" -) - -func (mp *MSPPrincipal) VariablyOpaqueFields() []string { - return []string{"principal"} -} - -func (mp *MSPPrincipal) VariablyOpaqueFieldProto(name string) (proto.Message, error) { - if name != mp.VariablyOpaqueFields()[0] { - return nil, fmt.Errorf("not a marshaled field: %s", name) - } - switch mp.PrincipalClassification { - case MSPPrincipal_ROLE: - return &MSPRole{}, nil - case MSPPrincipal_ORGANIZATION_UNIT: - return &OrganizationUnit{}, nil - case MSPPrincipal_IDENTITY: - return nil, fmt.Errorf("unable to decode MSP type IDENTITY until the protos are fixed to include the IDENTITY proto in protos/msp") - default: - return nil, fmt.Errorf("unable to decode MSP type: %v", mp.PrincipalClassification) - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.pb.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.pb.go deleted file mode 100644 index 24fe3c4db..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.pb.go +++ /dev/null @@ -1,441 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: msp/msp_principal.proto - -package msp // import "github.com/hyperledger/fabric/protos/msp" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type MSPPrincipal_Classification int32 - -const ( - MSPPrincipal_ROLE MSPPrincipal_Classification = 0 - // one of a member of MSP network, and the one of an - // administrator of an MSP network - MSPPrincipal_ORGANIZATION_UNIT MSPPrincipal_Classification = 1 - // groupping of entities, per MSP affiliation - // E.g., this can well be represented by an MSP's - // Organization unit - MSPPrincipal_IDENTITY MSPPrincipal_Classification = 2 - // identity - MSPPrincipal_ANONYMITY MSPPrincipal_Classification = 3 - // an identity to be anonymous or nominal. - MSPPrincipal_COMBINED MSPPrincipal_Classification = 4 -) - -var MSPPrincipal_Classification_name = map[int32]string{ - 0: "ROLE", - 1: "ORGANIZATION_UNIT", - 2: "IDENTITY", - 3: "ANONYMITY", - 4: "COMBINED", -} -var MSPPrincipal_Classification_value = map[string]int32{ - "ROLE": 0, - "ORGANIZATION_UNIT": 1, - "IDENTITY": 2, - "ANONYMITY": 3, - "COMBINED": 4, -} - -func (x MSPPrincipal_Classification) String() string { - return proto.EnumName(MSPPrincipal_Classification_name, int32(x)) -} -func (MSPPrincipal_Classification) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_msp_principal_9016cf1a8a7156cd, []int{0, 0} -} - -type MSPRole_MSPRoleType int32 - -const ( - MSPRole_MEMBER MSPRole_MSPRoleType = 0 - MSPRole_ADMIN MSPRole_MSPRoleType = 1 - MSPRole_CLIENT MSPRole_MSPRoleType = 2 - MSPRole_PEER MSPRole_MSPRoleType = 3 -) - -var MSPRole_MSPRoleType_name = map[int32]string{ - 0: "MEMBER", - 1: "ADMIN", - 2: "CLIENT", - 3: "PEER", -} -var MSPRole_MSPRoleType_value = map[string]int32{ - "MEMBER": 0, - "ADMIN": 1, - "CLIENT": 2, - "PEER": 3, -} - -func (x MSPRole_MSPRoleType) String() string { - return proto.EnumName(MSPRole_MSPRoleType_name, int32(x)) -} -func (MSPRole_MSPRoleType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_msp_principal_9016cf1a8a7156cd, []int{2, 0} -} - -type MSPIdentityAnonymity_MSPIdentityAnonymityType int32 - -const ( - MSPIdentityAnonymity_NOMINAL MSPIdentityAnonymity_MSPIdentityAnonymityType = 0 - MSPIdentityAnonymity_ANONYMOUS MSPIdentityAnonymity_MSPIdentityAnonymityType = 1 -) - -var MSPIdentityAnonymity_MSPIdentityAnonymityType_name = map[int32]string{ - 0: "NOMINAL", - 1: "ANONYMOUS", -} -var MSPIdentityAnonymity_MSPIdentityAnonymityType_value = map[string]int32{ - "NOMINAL": 0, - "ANONYMOUS": 1, -} - -func (x MSPIdentityAnonymity_MSPIdentityAnonymityType) String() string { - return proto.EnumName(MSPIdentityAnonymity_MSPIdentityAnonymityType_name, int32(x)) -} -func (MSPIdentityAnonymity_MSPIdentityAnonymityType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_msp_principal_9016cf1a8a7156cd, []int{3, 0} -} - -// MSPPrincipal aims to represent an MSP-centric set of identities. -// In particular, this structure allows for definition of -// - a group of identities that are member of the same MSP -// - a group of identities that are member of the same organization unit -// in the same MSP -// - a group of identities that are administering a specific MSP -// - a specific identity -// Expressing these groups is done given two fields of the fields below -// - Classification, that defines the type of classification of identities -// in an MSP this principal would be defined on; Classification can take -// three values: -// (i) ByMSPRole: that represents a classification of identities within -// MSP based on one of the two pre-defined MSP rules, "member" and "admin" -// (ii) ByOrganizationUnit: that represents a classification of identities -// within MSP based on the organization unit an identity belongs to -// (iii)ByIdentity that denotes that MSPPrincipal is mapped to a single -// identity/certificate; this would mean that the Principal bytes -// message -type MSPPrincipal struct { - // Classification describes the way that one should process - // Principal. An Classification value of "ByOrganizationUnit" reflects - // that "Principal" contains the name of an organization this MSP - // handles. A Classification value "ByIdentity" means that - // "Principal" contains a specific identity. Default value - // denotes that Principal contains one of the groups by - // default supported by all MSPs ("admin" or "member"). - PrincipalClassification MSPPrincipal_Classification `protobuf:"varint,1,opt,name=principal_classification,json=principalClassification,proto3,enum=common.MSPPrincipal_Classification" json:"principal_classification,omitempty"` - // Principal completes the policy principal definition. For the default - // principal types, Principal can be either "Admin" or "Member". - // For the ByOrganizationUnit/ByIdentity values of Classification, - // PolicyPrincipal acquires its value from an organization unit or - // identity, respectively. - // For the Combined Classification type, the Principal is a marshalled - // CombinedPrincipal. - Principal []byte `protobuf:"bytes,2,opt,name=principal,proto3" json:"principal,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MSPPrincipal) Reset() { *m = MSPPrincipal{} } -func (m *MSPPrincipal) String() string { return proto.CompactTextString(m) } -func (*MSPPrincipal) ProtoMessage() {} -func (*MSPPrincipal) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_principal_9016cf1a8a7156cd, []int{0} -} -func (m *MSPPrincipal) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MSPPrincipal.Unmarshal(m, b) -} -func (m *MSPPrincipal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MSPPrincipal.Marshal(b, m, deterministic) -} -func (dst *MSPPrincipal) XXX_Merge(src proto.Message) { - xxx_messageInfo_MSPPrincipal.Merge(dst, src) -} -func (m *MSPPrincipal) XXX_Size() int { - return xxx_messageInfo_MSPPrincipal.Size(m) -} -func (m *MSPPrincipal) XXX_DiscardUnknown() { - xxx_messageInfo_MSPPrincipal.DiscardUnknown(m) -} - -var xxx_messageInfo_MSPPrincipal proto.InternalMessageInfo - -func (m *MSPPrincipal) GetPrincipalClassification() MSPPrincipal_Classification { - if m != nil { - return m.PrincipalClassification - } - return MSPPrincipal_ROLE -} - -func (m *MSPPrincipal) GetPrincipal() []byte { - if m != nil { - return m.Principal - } - return nil -} - -// OrganizationUnit governs the organization of the Principal -// field of a policy principal when a specific organization unity members -// are to be defined within a policy principal. -type OrganizationUnit struct { - // MSPIdentifier represents the identifier of the MSP this organization unit - // refers to - MspIdentifier string `protobuf:"bytes,1,opt,name=msp_identifier,json=mspIdentifier,proto3" json:"msp_identifier,omitempty"` - // OrganizationUnitIdentifier defines the organizational unit under the - // MSP identified with MSPIdentifier - OrganizationalUnitIdentifier string `protobuf:"bytes,2,opt,name=organizational_unit_identifier,json=organizationalUnitIdentifier,proto3" json:"organizational_unit_identifier,omitempty"` - // CertifiersIdentifier is the hash of certificates chain of trust - // related to this organizational unit - CertifiersIdentifier []byte `protobuf:"bytes,3,opt,name=certifiers_identifier,json=certifiersIdentifier,proto3" json:"certifiers_identifier,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OrganizationUnit) Reset() { *m = OrganizationUnit{} } -func (m *OrganizationUnit) String() string { return proto.CompactTextString(m) } -func (*OrganizationUnit) ProtoMessage() {} -func (*OrganizationUnit) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_principal_9016cf1a8a7156cd, []int{1} -} -func (m *OrganizationUnit) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OrganizationUnit.Unmarshal(m, b) -} -func (m *OrganizationUnit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OrganizationUnit.Marshal(b, m, deterministic) -} -func (dst *OrganizationUnit) XXX_Merge(src proto.Message) { - xxx_messageInfo_OrganizationUnit.Merge(dst, src) -} -func (m *OrganizationUnit) XXX_Size() int { - return xxx_messageInfo_OrganizationUnit.Size(m) -} -func (m *OrganizationUnit) XXX_DiscardUnknown() { - xxx_messageInfo_OrganizationUnit.DiscardUnknown(m) -} - -var xxx_messageInfo_OrganizationUnit proto.InternalMessageInfo - -func (m *OrganizationUnit) GetMspIdentifier() string { - if m != nil { - return m.MspIdentifier - } - return "" -} - -func (m *OrganizationUnit) GetOrganizationalUnitIdentifier() string { - if m != nil { - return m.OrganizationalUnitIdentifier - } - return "" -} - -func (m *OrganizationUnit) GetCertifiersIdentifier() []byte { - if m != nil { - return m.CertifiersIdentifier - } - return nil -} - -// MSPRole governs the organization of the Principal -// field of an MSPPrincipal when it aims to define one of the -// two dedicated roles within an MSP: Admin and Members. -type MSPRole struct { - // MSPIdentifier represents the identifier of the MSP this principal - // refers to - MspIdentifier string `protobuf:"bytes,1,opt,name=msp_identifier,json=mspIdentifier,proto3" json:"msp_identifier,omitempty"` - // MSPRoleType defines which of the available, pre-defined MSP-roles - // an identiy should posess inside the MSP with identifier MSPidentifier - Role MSPRole_MSPRoleType `protobuf:"varint,2,opt,name=role,proto3,enum=common.MSPRole_MSPRoleType" json:"role,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MSPRole) Reset() { *m = MSPRole{} } -func (m *MSPRole) String() string { return proto.CompactTextString(m) } -func (*MSPRole) ProtoMessage() {} -func (*MSPRole) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_principal_9016cf1a8a7156cd, []int{2} -} -func (m *MSPRole) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MSPRole.Unmarshal(m, b) -} -func (m *MSPRole) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MSPRole.Marshal(b, m, deterministic) -} -func (dst *MSPRole) XXX_Merge(src proto.Message) { - xxx_messageInfo_MSPRole.Merge(dst, src) -} -func (m *MSPRole) XXX_Size() int { - return xxx_messageInfo_MSPRole.Size(m) -} -func (m *MSPRole) XXX_DiscardUnknown() { - xxx_messageInfo_MSPRole.DiscardUnknown(m) -} - -var xxx_messageInfo_MSPRole proto.InternalMessageInfo - -func (m *MSPRole) GetMspIdentifier() string { - if m != nil { - return m.MspIdentifier - } - return "" -} - -func (m *MSPRole) GetRole() MSPRole_MSPRoleType { - if m != nil { - return m.Role - } - return MSPRole_MEMBER -} - -// MSPIdentityAnonymity can be used to enforce an identity to be anonymous or nominal. -type MSPIdentityAnonymity struct { - AnonymityType MSPIdentityAnonymity_MSPIdentityAnonymityType `protobuf:"varint,1,opt,name=anonymity_type,json=anonymityType,proto3,enum=common.MSPIdentityAnonymity_MSPIdentityAnonymityType" json:"anonymity_type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MSPIdentityAnonymity) Reset() { *m = MSPIdentityAnonymity{} } -func (m *MSPIdentityAnonymity) String() string { return proto.CompactTextString(m) } -func (*MSPIdentityAnonymity) ProtoMessage() {} -func (*MSPIdentityAnonymity) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_principal_9016cf1a8a7156cd, []int{3} -} -func (m *MSPIdentityAnonymity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MSPIdentityAnonymity.Unmarshal(m, b) -} -func (m *MSPIdentityAnonymity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MSPIdentityAnonymity.Marshal(b, m, deterministic) -} -func (dst *MSPIdentityAnonymity) XXX_Merge(src proto.Message) { - xxx_messageInfo_MSPIdentityAnonymity.Merge(dst, src) -} -func (m *MSPIdentityAnonymity) XXX_Size() int { - return xxx_messageInfo_MSPIdentityAnonymity.Size(m) -} -func (m *MSPIdentityAnonymity) XXX_DiscardUnknown() { - xxx_messageInfo_MSPIdentityAnonymity.DiscardUnknown(m) -} - -var xxx_messageInfo_MSPIdentityAnonymity proto.InternalMessageInfo - -func (m *MSPIdentityAnonymity) GetAnonymityType() MSPIdentityAnonymity_MSPIdentityAnonymityType { - if m != nil { - return m.AnonymityType - } - return MSPIdentityAnonymity_NOMINAL -} - -// CombinedPrincipal governs the organization of the Principal -// field of a policy principal when principal_classification has -// indicated that a combined form of principals is required -type CombinedPrincipal struct { - // Principals refer to combined principals - Principals []*MSPPrincipal `protobuf:"bytes,1,rep,name=principals,proto3" json:"principals,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CombinedPrincipal) Reset() { *m = CombinedPrincipal{} } -func (m *CombinedPrincipal) String() string { return proto.CompactTextString(m) } -func (*CombinedPrincipal) ProtoMessage() {} -func (*CombinedPrincipal) Descriptor() ([]byte, []int) { - return fileDescriptor_msp_principal_9016cf1a8a7156cd, []int{4} -} -func (m *CombinedPrincipal) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CombinedPrincipal.Unmarshal(m, b) -} -func (m *CombinedPrincipal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CombinedPrincipal.Marshal(b, m, deterministic) -} -func (dst *CombinedPrincipal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CombinedPrincipal.Merge(dst, src) -} -func (m *CombinedPrincipal) XXX_Size() int { - return xxx_messageInfo_CombinedPrincipal.Size(m) -} -func (m *CombinedPrincipal) XXX_DiscardUnknown() { - xxx_messageInfo_CombinedPrincipal.DiscardUnknown(m) -} - -var xxx_messageInfo_CombinedPrincipal proto.InternalMessageInfo - -func (m *CombinedPrincipal) GetPrincipals() []*MSPPrincipal { - if m != nil { - return m.Principals - } - return nil -} - -func init() { - proto.RegisterType((*MSPPrincipal)(nil), "common.MSPPrincipal") - proto.RegisterType((*OrganizationUnit)(nil), "common.OrganizationUnit") - proto.RegisterType((*MSPRole)(nil), "common.MSPRole") - proto.RegisterType((*MSPIdentityAnonymity)(nil), "common.MSPIdentityAnonymity") - proto.RegisterType((*CombinedPrincipal)(nil), "common.CombinedPrincipal") - proto.RegisterEnum("common.MSPPrincipal_Classification", MSPPrincipal_Classification_name, MSPPrincipal_Classification_value) - proto.RegisterEnum("common.MSPRole_MSPRoleType", MSPRole_MSPRoleType_name, MSPRole_MSPRoleType_value) - proto.RegisterEnum("common.MSPIdentityAnonymity_MSPIdentityAnonymityType", MSPIdentityAnonymity_MSPIdentityAnonymityType_name, MSPIdentityAnonymity_MSPIdentityAnonymityType_value) -} - -func init() { - proto.RegisterFile("msp/msp_principal.proto", fileDescriptor_msp_principal_9016cf1a8a7156cd) -} - -var fileDescriptor_msp_principal_9016cf1a8a7156cd = []byte{ - // 519 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x93, 0xdf, 0x6a, 0xdb, 0x30, - 0x14, 0xc6, 0xeb, 0xa4, 0x6b, 0x9b, 0x93, 0x3f, 0xa8, 0x22, 0xa5, 0x81, 0x95, 0x11, 0xbc, 0x0d, - 0x72, 0xe5, 0x40, 0xba, 0xed, 0x62, 0x77, 0x4e, 0x62, 0x86, 0x20, 0x96, 0x8d, 0xe3, 0x5c, 0xb4, - 0x94, 0x05, 0xc7, 0x51, 0x52, 0x81, 0x6d, 0x19, 0xdb, 0xbd, 0xf0, 0xde, 0x65, 0x6f, 0xb0, 0xcb, - 0x3d, 0xd5, 0x9e, 0x62, 0xd8, 0x6e, 0x12, 0x65, 0xeb, 0x60, 0x57, 0xf6, 0x39, 0xe7, 0xf7, 0x1d, - 0x1d, 0x49, 0x9f, 0xe0, 0x3a, 0x4c, 0xe3, 0x61, 0x98, 0xc6, 0xcb, 0x38, 0xe1, 0x91, 0xcf, 0x63, - 0x2f, 0xd0, 0xe2, 0x44, 0x64, 0x02, 0x9f, 0xf9, 0x22, 0x0c, 0x45, 0xa4, 0xfe, 0x52, 0xa0, 0x65, - 0xce, 0x6d, 0x7b, 0x57, 0xc6, 0x5f, 0xa1, 0xb7, 0x67, 0x97, 0x7e, 0xe0, 0xa5, 0x29, 0xdf, 0x70, - 0xdf, 0xcb, 0xb8, 0x88, 0x7a, 0x4a, 0x5f, 0x19, 0x74, 0x46, 0x6f, 0xb5, 0x4a, 0xab, 0xc9, 0x3a, - 0x6d, 0x72, 0x84, 0x3a, 0xd7, 0xfb, 0x26, 0xc7, 0x05, 0x7c, 0x03, 0x8d, 0x7d, 0xa9, 0x57, 0xeb, - 0x2b, 0x83, 0x96, 0x73, 0x48, 0xa8, 0x0f, 0xd0, 0xf9, 0x83, 0xbf, 0x80, 0x53, 0xc7, 0x9a, 0x19, - 0xe8, 0x04, 0x5f, 0xc1, 0xa5, 0xe5, 0x7c, 0xd1, 0x29, 0xb9, 0xd7, 0x5d, 0x62, 0xd1, 0xe5, 0x82, - 0x12, 0x17, 0x29, 0xb8, 0x05, 0x17, 0x64, 0x6a, 0x50, 0x97, 0xb8, 0x77, 0xa8, 0x86, 0xdb, 0xd0, - 0xd0, 0xa9, 0x45, 0xef, 0xcc, 0x22, 0xac, 0x17, 0xc5, 0x89, 0x65, 0x8e, 0x09, 0x35, 0xa6, 0xe8, - 0x54, 0xfd, 0xa9, 0x00, 0xb2, 0x92, 0xad, 0x17, 0xf1, 0x6f, 0x65, 0xf3, 0x45, 0xc4, 0x33, 0xfc, - 0x1e, 0x3a, 0xc5, 0x01, 0xf1, 0x35, 0x8b, 0x32, 0xbe, 0xe1, 0x2c, 0x29, 0xb7, 0xd9, 0x70, 0xda, - 0x61, 0x1a, 0x93, 0x7d, 0x12, 0x4f, 0xe1, 0x8d, 0x90, 0xa4, 0x5e, 0xb0, 0x7c, 0x8a, 0x78, 0x26, - 0xcb, 0x6a, 0xa5, 0xec, 0xe6, 0x98, 0x2a, 0x96, 0x90, 0xba, 0xdc, 0xc2, 0x95, 0xcf, 0x92, 0x2a, - 0x48, 0x65, 0x71, 0xbd, 0x3c, 0x89, 0xee, 0xa1, 0x78, 0x10, 0xa9, 0xdf, 0x15, 0x38, 0x37, 0xe7, - 0xb6, 0x23, 0x02, 0xf6, 0xbf, 0xd3, 0x0e, 0xe1, 0x34, 0x11, 0x01, 0x2b, 0x67, 0xea, 0x8c, 0x5e, - 0x4b, 0x37, 0x56, 0x74, 0xd9, 0x7d, 0xdd, 0x3c, 0x66, 0x4e, 0x09, 0xaa, 0x9f, 0xa1, 0x29, 0x25, - 0x31, 0xc0, 0x99, 0x69, 0x98, 0x63, 0xc3, 0x41, 0x27, 0xb8, 0x01, 0xaf, 0xf4, 0xa9, 0x49, 0x28, - 0x52, 0x8a, 0xf4, 0x64, 0x46, 0x0c, 0xea, 0xa2, 0x5a, 0x71, 0x31, 0xb6, 0x61, 0x38, 0xa8, 0xae, - 0xfe, 0x50, 0xa0, 0x6b, 0xce, 0xed, 0x6a, 0xf9, 0x2c, 0xd7, 0x23, 0x11, 0xe5, 0x21, 0xcf, 0x72, - 0xfc, 0x00, 0x1d, 0x6f, 0x17, 0x2c, 0xb3, 0x3c, 0x66, 0xcf, 0x0e, 0xfa, 0x28, 0xcd, 0xf3, 0x97, - 0xea, 0xc5, 0x64, 0x39, 0x69, 0xdb, 0x93, 0x43, 0xf5, 0x13, 0xf4, 0xfe, 0x85, 0xe2, 0x26, 0x9c, - 0x53, 0xcb, 0x24, 0x54, 0x9f, 0xa1, 0x93, 0x83, 0x27, 0xac, 0xc5, 0x1c, 0x29, 0x2a, 0x81, 0xcb, - 0x89, 0x08, 0x57, 0x3c, 0x62, 0xeb, 0x83, 0xed, 0x3f, 0x00, 0xec, 0x5d, 0x98, 0xf6, 0x94, 0x7e, - 0x7d, 0xd0, 0x1c, 0x75, 0x5f, 0x32, 0xba, 0x23, 0x71, 0x63, 0x1b, 0xde, 0x89, 0x64, 0xab, 0x3d, - 0xe6, 0x31, 0x4b, 0x02, 0xb6, 0xde, 0xb2, 0x44, 0xdb, 0x78, 0xab, 0x84, 0xfb, 0xd5, 0x2b, 0x4b, - 0x9f, 0x1b, 0xdc, 0x0f, 0xb6, 0x3c, 0x7b, 0x7c, 0x5a, 0x15, 0xe1, 0x50, 0x82, 0x87, 0x15, 0x3c, - 0xac, 0xe0, 0xe2, 0x9d, 0xae, 0xce, 0xca, 0xff, 0xdb, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x40, - 0x36, 0xd2, 0xf9, 0xb9, 0x03, 0x00, 0x00, -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.proto b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.proto deleted file mode 100644 index 4739c6931..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/hyperledger/fabric/protos/msp/msp_principal.proto +++ /dev/null @@ -1,157 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -syntax = "proto3"; - -option go_package = "github.com/hyperledger/fabric/protos/msp"; -option java_package = "org.hyperledger.fabric.protos.common"; - -package common; - - -// msp_principal.proto contains proto messages defining the generalized -// MSP notion of identity called an MSPPrincipal. It is used as part of -// the chain configuration, in particular as the identity parameters to -// the configuration.proto file. This does not represent the MSP -// configuration for a chain, but is understood by MSPs - -// MSPPrincipal aims to represent an MSP-centric set of identities. -// In particular, this structure allows for definition of -// - a group of identities that are member of the same MSP -// - a group of identities that are member of the same organization unit -// in the same MSP -// - a group of identities that are administering a specific MSP -// - a specific identity -// Expressing these groups is done given two fields of the fields below -// - Classification, that defines the type of classification of identities -// in an MSP this principal would be defined on; Classification can take -// three values: -// (i) ByMSPRole: that represents a classification of identities within -// MSP based on one of the two pre-defined MSP rules, "member" and "admin" -// (ii) ByOrganizationUnit: that represents a classification of identities -// within MSP based on the organization unit an identity belongs to -// (iii)ByIdentity that denotes that MSPPrincipal is mapped to a single -// identity/certificate; this would mean that the Principal bytes -// message -message MSPPrincipal { - - enum Classification { - ROLE = 0; // Represents the one of the dedicated MSP roles, the - // one of a member of MSP network, and the one of an - // administrator of an MSP network - ORGANIZATION_UNIT = 1; // Denotes a finer grained (affiliation-based) - // groupping of entities, per MSP affiliation - // E.g., this can well be represented by an MSP's - // Organization unit - IDENTITY = 2; // Denotes a principal that consists of a single - // identity - ANONYMITY = 3; // Denotes a principal that can be used to enforce - // an identity to be anonymous or nominal. - COMBINED = 4; // Denotes a combined principal - } - - // Classification describes the way that one should process - // Principal. An Classification value of "ByOrganizationUnit" reflects - // that "Principal" contains the name of an organization this MSP - // handles. A Classification value "ByIdentity" means that - // "Principal" contains a specific identity. Default value - // denotes that Principal contains one of the groups by - // default supported by all MSPs ("admin" or "member"). - Classification principal_classification = 1; - - // Principal completes the policy principal definition. For the default - // principal types, Principal can be either "Admin" or "Member". - // For the ByOrganizationUnit/ByIdentity values of Classification, - // PolicyPrincipal acquires its value from an organization unit or - // identity, respectively. - // For the Combined Classification type, the Principal is a marshalled - // CombinedPrincipal. - bytes principal = 2; -} - - -// OrganizationUnit governs the organization of the Principal -// field of a policy principal when a specific organization unity members -// are to be defined within a policy principal. -message OrganizationUnit { - - // MSPIdentifier represents the identifier of the MSP this organization unit - // refers to - string msp_identifier = 1; - - // OrganizationUnitIdentifier defines the organizational unit under the - // MSP identified with MSPIdentifier - string organizational_unit_identifier = 2; - - // CertifiersIdentifier is the hash of certificates chain of trust - // related to this organizational unit - bytes certifiers_identifier = 3; -} - -// MSPRole governs the organization of the Principal -// field of an MSPPrincipal when it aims to define one of the -// two dedicated roles within an MSP: Admin and Members. -message MSPRole { - - // MSPIdentifier represents the identifier of the MSP this principal - // refers to - string msp_identifier = 1; - - enum MSPRoleType { - MEMBER = 0; // Represents an MSP Member - ADMIN = 1; // Represents an MSP Admin - CLIENT = 2; // Represents an MSP Client - PEER = 3; // Represents an MSP Peer - } - - // MSPRoleType defines which of the available, pre-defined MSP-roles - // an identiy should posess inside the MSP with identifier MSPidentifier - MSPRoleType role = 2; - -} - -// MSPIdentityAnonymity can be used to enforce an identity to be anonymous or nominal. -message MSPIdentityAnonymity { - - enum MSPIdentityAnonymityType { - NOMINAL = 0; // Represents a nominal MSP Identity - ANONYMOUS = 1; // Represents an anonymous MSP Identity - } - - MSPIdentityAnonymityType anonymity_type = 1; - -} - -// CombinedPrincipal governs the organization of the Principal -// field of a policy principal when principal_classification has -// indicated that a combined form of principals is required -message CombinedPrincipal { - - // Principals refer to combined principals - repeated MSPPrincipal principals = 1; -} - -// TODO: Bring msp.SerializedIdentity from fabric/msp/identities.proto here. Reason below. -// SerializedIdentity represents an serialized version of an identity; -// this consists of an MSP-identifier this identity would correspond to -// and the bytes of the actual identity. A serialized form of -// SerializedIdentity would govern "Principal" field of a PolicyPrincipal -// of classification "ByIdentity". diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/LICENSE b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e75..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/README.md b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 27f7bc65c..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,55 +0,0 @@ - - - -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## License - -BSD-2-Clause diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/appveyor.yml b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade0..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/errors.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index dc4b2063d..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,286 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which when applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// together with the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required, the errors.WithStack and -// errors.WithMessage functions destructure errors.Wrap into its component -// operations: annotating an error with a stack trace and with a message, -// respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error that does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// Although the causer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported: -// -// %s print the error. If the error has a Cause it will be -// printed recursively. -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface: -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// The returned errors.StackTrace type is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d", f) -// } -// } -// -// Although the stackTracer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is called, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -// WithMessagef annotates err with the format specifier. -// If err is nil, WithMessagef returns nil. -func WithMessagef(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/stack.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 3799f4857..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,151 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s function name and path of source file relative to the compile time -// GOPATH separated by \n\t (\n\t) -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -// Format formats the stack of Frames according to the fmt.Formatter interface. -// -// %s lists source files for each Frame in the stack -// %v lists the source file and line number for each Frame in the stack -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+v Prints filename, function, and line number for each Frame in the stack. -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - fmt.Fprintf(s, "\n%+v", f) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - fmt.Fprintf(s, "%v", []Frame(st)) - } - case 's': - fmt.Fprintf(s, "%s", []Frame(st)) - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/vendor.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/vendor.json deleted file mode 100644 index 9794848f1..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/abac/go/vendor/vendor.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "comment": "", - "ignore": "test", - "package": [ - { - "checksumSHA1": "GaJLoEuMGnP5ofXvuweAI4wx06U=", - "path": "github.com/golang/protobuf/proto", - "revision": "1918e1ff6ffd2be7bed0553df8650672c3bfe80d", - "revisionTime": "2018-10-30T15:47:21Z" - }, - { - "checksumSHA1": "XGpUl1X+7ly1ski4Pc+N9ozfVv8=", - "path": "github.com/hyperledger/fabric/core/chaincode/shim/ext/attrmgr", - "revision": "60f968db8e6e2ebcf439391610e22250993d0a85", - "revisionTime": "2018-09-12T02:19:31Z" - }, - { - "checksumSHA1": "vFuT7942CfsCcH9IG3zHmQ4d/oI=", - "path": "github.com/hyperledger/fabric/core/chaincode/shim/ext/cid", - "revision": "60f968db8e6e2ebcf439391610e22250993d0a85", - "revisionTime": "2018-09-12T02:19:31Z" - }, - { - "checksumSHA1": "ZzWCzHsWRI/LAxhZYUMqVcIAsZQ=", - "path": "github.com/hyperledger/fabric/protos/msp", - "revision": "60f968db8e6e2ebcf439391610e22250993d0a85", - "revisionTime": "2018-09-12T02:19:31Z" - }, - { - "checksumSHA1": "DTy0iJ2w5C+FDsN9EnzfhNmvS+o=", - "path": "github.com/pkg/errors", - "revision": "059132a15dd08d6704c67711dae0cf35ab991756", - "revisionTime": "2018-10-23T23:59:46Z" - } - ], - "rootPath": "github.com/hyperledger/fabric-samples/chaincode/abac/go" -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/go/chaincode_example02.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/go/chaincode_example02.go index f43e3d410..534380664 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/go/chaincode_example02.go +++ b/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/go/chaincode_example02.go @@ -1,7 +1,3 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - /* Copyright IBM Corp. 2016 All Rights Reserved. diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/build.gradle b/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/build.gradle deleted file mode 100644 index 5221272c1..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/build.gradle +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright IBM Corp. 2018 All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -plugins { - id 'com.github.johnrengelman.shadow' version '2.0.3' - id 'java' -} - -group 'org.hyperledger.fabric-chaincode-java' -version '1.0-SNAPSHOT' - -sourceCompatibility = 1.8 - -repositories { - mavenLocal() - mavenCentral() -} - -dependencies { - compile group: 'org.hyperledger.fabric-chaincode-java', name: 'fabric-chaincode-shim', version: '1.+' - testCompile group: 'junit', name: 'junit', version: '4.12' -} - -shadowJar { - baseName = 'chaincode' - version = null - classifier = null - - manifest { - attributes 'Main-Class': 'org.hyperledger.fabric.example.SimpleChaincode' - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/settings.gradle b/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/settings.gradle deleted file mode 100644 index 9ce14a668..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/settings.gradle +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright IBM Corp. 2017 All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -rootProject.name = 'fabric-chaincode-example-gradle' - diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/src/main/java/org/hyperledger/fabric/example/SimpleChaincode.java b/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/src/main/java/org/hyperledger/fabric/example/SimpleChaincode.java deleted file mode 100644 index dd93a4e06..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/java/src/main/java/org/hyperledger/fabric/example/SimpleChaincode.java +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright IBM Corp., DTCC All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ -package org.hyperledger.fabric.example; - -import java.util.List; - -import com.google.protobuf.ByteString; -import io.netty.handler.ssl.OpenSsl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hyperledger.fabric.shim.ChaincodeBase; -import org.hyperledger.fabric.shim.ChaincodeStub; - -import static java.nio.charset.StandardCharsets.UTF_8; - -public class SimpleChaincode extends ChaincodeBase { - - private static Log _logger = LogFactory.getLog(SimpleChaincode.class); - - @Override - public Response init(ChaincodeStub stub) { - try { - _logger.info("Init java simple chaincode"); - String func = stub.getFunction(); - if (!func.equals("init")) { - return newErrorResponse("function other than init is not supported"); - } - List args = stub.getParameters(); - if (args.size() != 4) { - newErrorResponse("Incorrect number of arguments. Expecting 4"); - } - // Initialize the chaincode - String account1Key = args.get(0); - int account1Value = Integer.parseInt(args.get(1)); - String account2Key = args.get(2); - int account2Value = Integer.parseInt(args.get(3)); - - _logger.info(String.format("account %s, value = %s; account %s, value %s", account1Key, account1Value, account2Key, account2Value)); - stub.putStringState(account1Key, args.get(1)); - stub.putStringState(account2Key, args.get(3)); - - return newSuccessResponse(); - } catch (Throwable e) { - return newErrorResponse(e); - } - } - - @Override - public Response invoke(ChaincodeStub stub) { - try { - _logger.info("Invoke java simple chaincode"); - String func = stub.getFunction(); - List params = stub.getParameters(); - if (func.equals("invoke")) { - return invoke(stub, params); - } - if (func.equals("delete")) { - return delete(stub, params); - } - if (func.equals("query")) { - return query(stub, params); - } - return newErrorResponse("Invalid invoke function name. Expecting one of: [\"invoke\", \"delete\", \"query\"]"); - } catch (Throwable e) { - return newErrorResponse(e); - } - } - - private Response invoke(ChaincodeStub stub, List args) { - if (args.size() != 3) { - return newErrorResponse("Incorrect number of arguments. Expecting 3"); - } - String accountFromKey = args.get(0); - String accountToKey = args.get(1); - - String accountFromValueStr = stub.getStringState(accountFromKey); - if (accountFromValueStr == null) { - return newErrorResponse(String.format("Entity %s not found", accountFromKey)); - } - int accountFromValue = Integer.parseInt(accountFromValueStr); - - String accountToValueStr = stub.getStringState(accountToKey); - if (accountToValueStr == null) { - return newErrorResponse(String.format("Entity %s not found", accountToKey)); - } - int accountToValue = Integer.parseInt(accountToValueStr); - - int amount = Integer.parseInt(args.get(2)); - - if (amount > accountFromValue) { - return newErrorResponse(String.format("not enough money in account %s", accountFromKey)); - } - - accountFromValue -= amount; - accountToValue += amount; - - _logger.info(String.format("new value of A: %s", accountFromValue)); - _logger.info(String.format("new value of B: %s", accountToValue)); - - stub.putStringState(accountFromKey, Integer.toString(accountFromValue)); - stub.putStringState(accountToKey, Integer.toString(accountToValue)); - - _logger.info("Transfer complete"); - - return newSuccessResponse("invoke finished successfully", ByteString.copyFrom(accountFromKey + ": " + accountFromValue + " " + accountToKey + ": " + accountToValue, UTF_8).toByteArray()); - } - - // Deletes an entity from state - private Response delete(ChaincodeStub stub, List args) { - if (args.size() != 1) { - return newErrorResponse("Incorrect number of arguments. Expecting 1"); - } - String key = args.get(0); - // Delete the key from the state in ledger - stub.delState(key); - return newSuccessResponse(); - } - - // query callback representing the query of a chaincode - private Response query(ChaincodeStub stub, List args) { - if (args.size() != 1) { - return newErrorResponse("Incorrect number of arguments. Expecting name of the person to query"); - } - String key = args.get(0); - //byte[] stateBytes - String val = stub.getStringState(key); - if (val == null) { - return newErrorResponse(String.format("Error: state for %s is null", key)); - } - _logger.info(String.format("Query Response:\nName: %s, Amount: %s\n", key, val)); - return newSuccessResponse(val, ByteString.copyFrom(val, UTF_8).toByteArray()); - } - - public static void main(String[] args) { - System.out.println("OpenSSL avaliable: " + OpenSsl.isAvailable()); - new SimpleChaincode().start(args); - } - -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/node/chaincode_example02.js b/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/node/chaincode_example02.js deleted file mode 100644 index 3682e595b..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/node/chaincode_example02.js +++ /dev/null @@ -1,141 +0,0 @@ -/* -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 -*/ - -const shim = require('fabric-shim'); -const util = require('util'); - -var Chaincode = class { - // Initialize the chaincode - async Init(stub) { - console.info('========= example02 Init ========='); - let ret = stub.getFunctionAndParameters(); - console.info(ret); - let args = ret.params; - // initialise only if 4 parameters passed. - if (args.length != 4) { - return shim.error('Incorrect number of arguments. Expecting 4'); - } - - let A = args[0]; - let B = args[2]; - let Aval = args[1]; - let Bval = args[3]; - - if ( - typeof parseInt(Aval) !== 'number' || - typeof parseInt(Bval) !== 'number' - ) { - return shim.error('Expecting integer value for asset holding'); - } - - try { - await stub.putState(A, Buffer.from(Aval)); - try { - await stub.putState(B, Buffer.from(Bval)); - return shim.success(); - } catch (err) { - return shim.error(err); - } - } catch (err) { - return shim.error(err); - } - } - - async Invoke(stub) { - let ret = stub.getFunctionAndParameters(); - console.info(ret); - let method = this[ret.fcn]; - if (!method) { - console.log('no method of name:' + ret.fcn + ' found'); - return shim.success(); - } - try { - let payload = await method(stub, ret.params); - return shim.success(payload); - } catch (err) { - console.log(err); - return shim.error(err); - } - } - - async invoke(stub, args) { - if (args.length != 3) { - throw new Error('Incorrect number of arguments. Expecting 3'); - } - - let A = args[0]; - let B = args[1]; - if (!A || !B) { - throw new Error('asset holding must not be empty'); - } - - // Get the state from the ledger - let Avalbytes = await stub.getState(A); - if (!Avalbytes) { - throw new Error('Failed to get state of asset holder A'); - } - let Aval = parseInt(Avalbytes.toString()); - - let Bvalbytes = await stub.getState(B); - if (!Bvalbytes) { - throw new Error('Failed to get state of asset holder B'); - } - - let Bval = parseInt(Bvalbytes.toString()); - // Perform the execution - let amount = parseInt(args[2]); - if (typeof amount !== 'number') { - throw new Error('Expecting integer value for amount to be transaferred'); - } - - Aval = Aval - amount; - Bval = Bval + amount; - console.info(util.format('Aval = %d, Bval = %d\n', Aval, Bval)); - - // Write the states back to the ledger - await stub.putState(A, Buffer.from(Aval.toString())); - await stub.putState(B, Buffer.from(Bval.toString())); - } - - // Deletes an entity from state - async delete(stub, args) { - if (args.length != 1) { - throw new Error('Incorrect number of arguments. Expecting 1'); - } - - let A = args[0]; - - // Delete the key from the state in ledger - await stub.deleteState(A); - } - - // query callback representing the query of a chaincode - async query(stub, args) { - if (args.length != 1) { - throw new Error( - 'Incorrect number of arguments. Expecting name of the person to query' - ); - } - - let jsonResp = {}; - let A = args[0]; - - // Get the state from the ledger - let Avalbytes = await stub.getState(A); - if (!Avalbytes) { - jsonResp.error = 'Failed to get state for ' + A; - throw new Error(JSON.stringify(jsonResp)); - } - - jsonResp.name = A; - jsonResp.amount = Avalbytes.toString(); - console.info('Query Response:'); - console.info(jsonResp); - return Avalbytes; - } -}; - -shim.start(new Chaincode()); diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/node/package.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/node/package.json deleted file mode 100644 index ea4e125de..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/chaincode_example02/node/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "chaincode_example02", - "version": "1.0.0", - "description": "chaincode_example02 chaincode implemented in node.js", - "engines": { - "node": ">=8.4.0", - "npm": ">=5.3.0" - }, - "scripts": { - "start": "node chaincode_example02.js" - }, - "engine-strict": true, - "license": "Apache-2.0", - "dependencies": { - "fabric-shim": "~1.4.0" - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/go/fabcar.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/go/fabcar.go deleted file mode 100644 index 2b55643c7..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/go/fabcar.go +++ /dev/null @@ -1,208 +0,0 @@ -/* - *SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * The sample smart contract for documentation topic: - * Writing Your First Blockchain Application - */ - -package main - -/* Imports - * 4 utility libraries for formatting, handling bytes, reading and writing JSON, and string manipulation - * 2 specific Hyperledger Fabric specific libraries for Smart Contracts - */ -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - - "github.com/hyperledger/fabric/core/chaincode/shim" - sc "github.com/hyperledger/fabric/protos/peer" -) - -// Define the Smart Contract structure -type SmartContract struct { -} - -// Define the car structure, with 4 properties. Structure tags are used by encoding/json library -type Car struct { - Make string `json:"make"` - Model string `json:"model"` - Colour string `json:"colour"` - Owner string `json:"owner"` -} - -/* - * The Init method is called when the Smart Contract "fabcar" is instantiated by the blockchain network - * Best practice is to have any Ledger initialization in separate function -- see initLedger() - */ -func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response { - return shim.Success(nil) -} - -/* - * The Invoke method is called as a result of an application request to run the Smart Contract "fabcar" - * The calling application program has also specified the particular smart contract function to be called, with arguments - */ -func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response { - - // Retrieve the requested Smart Contract function and arguments - function, args := APIstub.GetFunctionAndParameters() - // Route to the appropriate handler function to interact with the ledger appropriately - if function == "queryCar" { - return s.queryCar(APIstub, args) - } else if function == "initLedger" { - return s.initLedger(APIstub) - } else if function == "createCar" { - return s.createCar(APIstub, args) - } else if function == "queryAllCars" { - return s.queryAllCars(APIstub) - } else if function == "changeCarOwner" { - return s.changeCarOwner(APIstub, args) - } - - return shim.Error("Invalid Smart Contract function name.") -} - -func (s *SmartContract) queryCar(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { - - if len(args) != 1 { - return shim.Error("Incorrect number of arguments. Expecting 1") - } - - carAsBytes, _ := APIstub.GetState(args[0]) - return shim.Success(carAsBytes) -} - -func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) sc.Response { - cars := []Car{ - Car{Make: "Toyota", Model: "Prius", Colour: "blue", Owner: "Tomoko"}, - Car{Make: "Ford", Model: "Mustang", Colour: "red", Owner: "Brad"}, - Car{Make: "Hyundai", Model: "Tucson", Colour: "green", Owner: "Jin Soo"}, - Car{Make: "Volkswagen", Model: "Passat", Colour: "yellow", Owner: "Max"}, - Car{Make: "Tesla", Model: "S", Colour: "black", Owner: "Adriana"}, - Car{Make: "Peugeot", Model: "205", Colour: "purple", Owner: "Michel"}, - Car{Make: "Chery", Model: "S22L", Colour: "white", Owner: "Aarav"}, - Car{Make: "Fiat", Model: "Punto", Colour: "violet", Owner: "Pari"}, - Car{Make: "Tata", Model: "Nano", Colour: "indigo", Owner: "Valeria"}, - Car{Make: "Holden", Model: "Barina", Colour: "brown", Owner: "Shotaro"}, - } - - i := 0 - for i < len(cars) { - fmt.Println("i is ", i) - carAsBytes, _ := json.Marshal(cars[i]) - APIstub.PutState("CAR"+strconv.Itoa(i), carAsBytes) - fmt.Println("Added", cars[i]) - i = i + 1 - } - - return shim.Success(nil) -} - -func (s *SmartContract) createCar(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { - - if len(args) != 5 { - return shim.Error("Incorrect number of arguments. Expecting 5") - } - - var car = Car{Make: args[1], Model: args[2], Colour: args[3], Owner: args[4]} - - carAsBytes, _ := json.Marshal(car) - APIstub.PutState(args[0], carAsBytes) - - return shim.Success(nil) -} - -func (s *SmartContract) queryAllCars(APIstub shim.ChaincodeStubInterface) sc.Response { - - startKey := "CAR0" - endKey := "CAR999" - - resultsIterator, err := APIstub.GetStateByRange(startKey, endKey) - if err != nil { - return shim.Error(err.Error()) - } - defer resultsIterator.Close() - - // buffer is a JSON array containing QueryResults - var buffer bytes.Buffer - buffer.WriteString("[") - - bArrayMemberAlreadyWritten := false - for resultsIterator.HasNext() { - queryResponse, err := resultsIterator.Next() - if err != nil { - return shim.Error(err.Error()) - } - // Add a comma before array members, suppress it for the first array member - if bArrayMemberAlreadyWritten == true { - buffer.WriteString(",") - } - buffer.WriteString("{\"Key\":") - buffer.WriteString("\"") - buffer.WriteString(queryResponse.Key) - buffer.WriteString("\"") - - buffer.WriteString(", \"Record\":") - // Record is a JSON object, so we write as-is - buffer.WriteString(string(queryResponse.Value)) - buffer.WriteString("}") - bArrayMemberAlreadyWritten = true - } - buffer.WriteString("]") - - fmt.Printf("- queryAllCars:\n%s\n", buffer.String()) - - return shim.Success(buffer.Bytes()) -} - -func (s *SmartContract) changeCarOwner(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { - - if len(args) != 2 { - return shim.Error("Incorrect number of arguments. Expecting 2") - } - - carAsBytes, _ := APIstub.GetState(args[0]) - car := Car{} - - json.Unmarshal(carAsBytes, &car) - car.Owner = args[1] - - carAsBytes, _ = json.Marshal(car) - APIstub.PutState(args[0], carAsBytes) - - return shim.Success(nil) -} - -// The main function is only relevant in unit test mode. Only included here for completeness. -func main() { - - // Create a new Smart Contract - err := shim.Start(new(SmartContract)) - if err != nil { - fmt.Printf("Error creating new Smart Contract: %s", err) - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript-low-level/fabcar.js b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript-low-level/fabcar.js deleted file mode 100644 index 8ffdcf475..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript-low-level/fabcar.js +++ /dev/null @@ -1,193 +0,0 @@ -/* -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 -*/ - -'use strict'; -const shim = require('fabric-shim'); -const util = require('util'); - -let Chaincode = class { - // The Init method is called when the Smart Contract 'fabcar' is instantiated by the blockchain network - // Best practice is to have any Ledger initialization in separate function -- see initLedger() - async Init(stub) { - console.info('=========== Instantiated fabcar chaincode ==========='); - return shim.success(); - } - - // The Invoke method is called as a result of an application request to run the Smart Contract - // 'fabcar'. The calling application program has also specified the particular smart contract - // function to be called, with arguments - async Invoke(stub) { - let ret = stub.getFunctionAndParameters(); - console.info(ret); - - let method = this[ret.fcn]; - if (!method) { - console.error('no function of name:' + ret.fcn + ' found'); - throw new Error('Received unknown function ' + ret.fcn + ' invocation'); - } - try { - let payload = await method(stub, ret.params); - return shim.success(payload); - } catch (err) { - console.log(err); - return shim.error(err); - } - } - - async queryCar(stub, args) { - if (args.length != 1) { - throw new Error( - 'Incorrect number of arguments. Expecting CarNumber ex: CAR01' - ); - } - let carNumber = args[0]; - - let carAsBytes = await stub.getState(carNumber); //get the car from chaincode state - if (!carAsBytes || carAsBytes.toString().length <= 0) { - throw new Error(carNumber + ' does not exist: '); - } - console.log(carAsBytes.toString()); - return carAsBytes; - } - - async initLedger(stub, args) { - console.info('============= START : Initialize Ledger ==========='); - let cars = []; - cars.push({ - make: 'Toyota', - model: 'Prius', - color: 'blue', - owner: 'Tomoko' - }); - cars.push({ - make: 'Ford', - model: 'Mustang', - color: 'red', - owner: 'Brad' - }); - cars.push({ - make: 'Hyundai', - model: 'Tucson', - color: 'green', - owner: 'Jin Soo' - }); - cars.push({ - make: 'Volkswagen', - model: 'Passat', - color: 'yellow', - owner: 'Max' - }); - cars.push({ - make: 'Tesla', - model: 'S', - color: 'black', - owner: 'Adriana' - }); - cars.push({ - make: 'Peugeot', - model: '205', - color: 'purple', - owner: 'Michel' - }); - cars.push({ - make: 'Chery', - model: 'S22L', - color: 'white', - owner: 'Aarav' - }); - cars.push({ - make: 'Fiat', - model: 'Punto', - color: 'violet', - owner: 'Pari' - }); - cars.push({ - make: 'Tata', - model: 'Nano', - color: 'indigo', - owner: 'Valeria' - }); - cars.push({ - make: 'Holden', - model: 'Barina', - color: 'brown', - owner: 'Shotaro' - }); - - for (let i = 0; i < cars.length; i++) { - cars[i].docType = 'car'; - await stub.putState('CAR' + i, Buffer.from(JSON.stringify(cars[i]))); - console.info('Added <--> ', cars[i]); - } - console.info('============= END : Initialize Ledger ==========='); - } - - async createCar(stub, args) { - console.info('============= START : Create Car ==========='); - if (args.length != 5) { - throw new Error('Incorrect number of arguments. Expecting 5'); - } - - var car = { - docType: 'car', - make: args[1], - model: args[2], - color: args[3], - owner: args[4] - }; - - await stub.putState(args[0], Buffer.from(JSON.stringify(car))); - console.info('============= END : Create Car ==========='); - } - - async queryAllCars(stub, args) { - let startKey = 'CAR0'; - let endKey = 'CAR999'; - - let iterator = await stub.getStateByRange(startKey, endKey); - - let allResults = []; - while (true) { - let res = await iterator.next(); - - if (res.value && res.value.value.toString()) { - let jsonRes = {}; - console.log(res.value.value.toString('utf8')); - - jsonRes.Key = res.value.key; - try { - jsonRes.Record = JSON.parse(res.value.value.toString('utf8')); - } catch (err) { - console.log(err); - jsonRes.Record = res.value.value.toString('utf8'); - } - allResults.push(jsonRes); - } - if (res.done) { - console.log('end of data'); - await iterator.close(); - console.info(allResults); - return Buffer.from(JSON.stringify(allResults)); - } - } - } - - async changeCarOwner(stub, args) { - console.info('============= START : changeCarOwner ==========='); - if (args.length != 2) { - throw new Error('Incorrect number of arguments. Expecting 2'); - } - - let carAsBytes = await stub.getState(args[0]); - let car = JSON.parse(carAsBytes); - car.owner = args[1]; - - await stub.putState(args[0], Buffer.from(JSON.stringify(car))); - console.info('============= END : changeCarOwner ==========='); - } -}; - -shim.start(new Chaincode()); diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript-low-level/package.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript-low-level/package.json deleted file mode 100644 index 9ab05de60..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript-low-level/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "fabcar", - "version": "1.0.0", - "description": "fabcar chaincode implemented in node.js", - "engines": { - "node": ">=8.4.0", - "npm": ">=5.3.0" - }, - "scripts": { - "start": "node fabcar.js" - }, - "engine-strict": true, - "license": "Apache-2.0", - "dependencies": { - "fabric-shim": "~1.4.0" - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.editorconfig b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.editorconfig deleted file mode 100755 index 75a13be20..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.editorconfig +++ /dev/null @@ -1,16 +0,0 @@ -# -# SPDX-License-Identifier: Apache-2.0 -# - -root = true - -[*] -indent_style = space -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[*.md] -trim_trailing_whitespace = false diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.eslintignore b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.eslintignore deleted file mode 100644 index 159584701..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.eslintignore +++ /dev/null @@ -1,5 +0,0 @@ -# -# SPDX-License-Identifier: Apache-2.0 -# - -coverage diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.eslintrc.js b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.eslintrc.js deleted file mode 100644 index 99a8a5057..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.eslintrc.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - */ - -module.exports = { - env: { - node: true, - mocha: true - }, - parserOptions: { - ecmaVersion: 8, - sourceType: 'script' - }, - extends: 'eslint:recommended', - rules: { - indent: ['error', 4], - 'linebreak-style': ['error', 'unix'], - quotes: ['error', 'single'], - semi: ['error', 'always'], - 'no-unused-vars': ['error', { args: 'none' }], - 'no-console': 'off', - curly: 'error', - eqeqeq: 'error', - 'no-throw-literal': 'error', - strict: 'error', - 'no-var': 'error', - 'dot-notation': 'error', - 'no-tabs': 'error', - 'no-trailing-spaces': 'error', - 'no-use-before-define': 'error', - 'no-useless-call': 'error', - 'no-with': 'error', - 'operator-linebreak': 'error', - yoda: 'error', - 'quote-props': ['error', 'as-needed'], - 'no-constant-condition': ['error', { checkLoops: false }] - } -}; diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.gitignore b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.gitignore deleted file mode 100644 index a00ca9415..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/.gitignore +++ /dev/null @@ -1,77 +0,0 @@ -# -# SPDX-License-Identifier: Apache-2.0 -# - -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# TypeScript v1 declaration files -typings/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env - -# parcel-bundler cache (https://parceljs.org/) -.cache - -# next.js build output -.next - -# nuxt.js build output -.nuxt - -# vuepress build output -.vuepress/dist - -# Serverless directories -.serverless diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/index.js b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/index.js deleted file mode 100644 index e8f896013..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - */ - -'use strict'; - -const FabCar = require('./lib/fabcar'); - -module.exports.FabCar = FabCar; -module.exports.contracts = [FabCar]; diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/lib/fabcar.js b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/lib/fabcar.js deleted file mode 100644 index 50064ba75..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/lib/fabcar.js +++ /dev/null @@ -1,157 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - */ - -'use strict'; - -const { Contract } = require('fabric-contract-api'); - -class FabCar extends Contract { - async initLedger(ctx) { - console.info('============= START : Initialize Ledger ==========='); - const cars = [ - { - color: 'blue', - make: 'Toyota', - model: 'Prius', - owner: 'Tomoko' - }, - { - color: 'red', - make: 'Ford', - model: 'Mustang', - owner: 'Brad' - }, - { - color: 'green', - make: 'Hyundai', - model: 'Tucson', - owner: 'Jin Soo' - }, - { - color: 'yellow', - make: 'Volkswagen', - model: 'Passat', - owner: 'Max' - }, - { - color: 'black', - make: 'Tesla', - model: 'S', - owner: 'Adriana' - }, - { - color: 'purple', - make: 'Peugeot', - model: '205', - owner: 'Michel' - }, - { - color: 'white', - make: 'Chery', - model: 'S22L', - owner: 'Aarav' - }, - { - color: 'violet', - make: 'Fiat', - model: 'Punto', - owner: 'Pari' - }, - { - color: 'indigo', - make: 'Tata', - model: 'Nano', - owner: 'Valeria' - }, - { - color: 'brown', - make: 'Holden', - model: 'Barina', - owner: 'Shotaro' - } - ]; - - for (let i = 0; i < cars.length; i++) { - cars[i].docType = 'car'; - await ctx.stub.putState( - 'CAR' + i, - Buffer.from(JSON.stringify(cars[i])) - ); - console.info('Added <--> ', cars[i]); - } - console.info('============= END : Initialize Ledger ==========='); - } - - async queryCar(ctx, carNumber) { - const carAsBytes = await ctx.stub.getState(carNumber); // get the car from chaincode state - if (!carAsBytes || carAsBytes.length === 0) { - throw new Error(`${carNumber} does not exist`); - } - console.log(carAsBytes.toString()); - return carAsBytes.toString(); - } - - async createCar(ctx, carNumber, make, model, color, owner) { - console.info('============= START : Create Car ==========='); - - const car = { - color, - docType: 'car', - make, - model, - owner - }; - - await ctx.stub.putState(carNumber, Buffer.from(JSON.stringify(car))); - console.info('============= END : Create Car ==========='); - } - - async queryAllCars(ctx) { - const startKey = 'CAR0'; - const endKey = 'CAR999'; - - const iterator = await ctx.stub.getStateByRange(startKey, endKey); - - const allResults = []; - while (true) { - const res = await iterator.next(); - - if (res.value && res.value.value.toString()) { - console.log(res.value.value.toString('utf8')); - - const Key = res.value.key; - let Record; - try { - Record = JSON.parse(res.value.value.toString('utf8')); - } catch (err) { - console.log(err); - Record = res.value.value.toString('utf8'); - } - allResults.push({ Key, Record }); - } - if (res.done) { - console.log('end of data'); - await iterator.close(); - console.info(allResults); - return JSON.stringify(allResults); - } - } - } - - async changeCarOwner(ctx, carNumber, newOwner) { - console.info('============= START : changeCarOwner ==========='); - - const carAsBytes = await ctx.stub.getState(carNumber); // get the car from chaincode state - if (!carAsBytes || carAsBytes.length === 0) { - throw new Error(`${carNumber} does not exist`); - } - const car = JSON.parse(carAsBytes.toString()); - car.owner = newOwner; - - await ctx.stub.putState(carNumber, Buffer.from(JSON.stringify(car))); - console.info('============= END : changeCarOwner ==========='); - } -} - -module.exports = FabCar; diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/package.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/package.json deleted file mode 100644 index abe745587..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/javascript/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "fabcar", - "version": "1.0.0", - "description": "FabCar contract implemented in JavaScript", - "main": "index.js", - "engines": { - "node": ">=8", - "npm": ">=5" - }, - "scripts": { - "lint": "eslint .", - "pretest": "npm run lint", - "test": "nyc mocha --recursive", - "start": "fabric-chaincode-node start" - }, - "engineStrict": true, - "author": "Hyperledger", - "license": "Apache-2.0", - "dependencies": { - "fabric-contract-api": "~1.4.0", - "fabric-shim": "~1.4.0" - }, - "devDependencies": { - "chai": "^4.1.2", - "eslint": "^4.19.1", - "mocha": "^5.2.0", - "nyc": "^12.0.2", - "sinon": "^6.0.0", - "sinon-chai": "^3.2.0" - }, - "nyc": { - "exclude": [ - "coverage/**", - "test/**" - ], - "reporter": [ - "text-summary", - "html" - ], - "all": true, - "check-coverage": true, - "statements": 100, - "branches": 100, - "functions": 100, - "lines": 100 - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/.editorconfig b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/.editorconfig deleted file mode 100755 index 75a13be20..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/.editorconfig +++ /dev/null @@ -1,16 +0,0 @@ -# -# SPDX-License-Identifier: Apache-2.0 -# - -root = true - -[*] -indent_style = space -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[*.md] -trim_trailing_whitespace = false diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/.gitignore b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/.gitignore deleted file mode 100644 index 69d6a33bb..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/.gitignore +++ /dev/null @@ -1,81 +0,0 @@ -# -# SPDX-License-Identifier: Apache-2.0 -# - -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# TypeScript v1 declaration files -typings/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env - -# parcel-bundler cache (https://parceljs.org/) -.cache - -# next.js build output -.next - -# nuxt.js build output -.nuxt - -# vuepress build output -.vuepress/dist - -# Serverless directories -.serverless - -# Compiled TypeScript files -dist - diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/package.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/package.json deleted file mode 100644 index ba2d5753d..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "fabcar", - "version": "1.0.0", - "description": "FabCar contract implemented in TypeScript", - "main": "dist/index.js", - "typings": "dist/index.d.ts", - "engines": { - "node": ">=8", - "npm": ">=5" - }, - "scripts": { - "lint": "tslint -c tslint.json 'src/**/*.ts'", - "pretest": "npm run lint", - "test": "nyc mocha -r ts-node/register src/**/*.spec.ts", - "start": "fabric-chaincode-node start", - "build": "tsc", - "build:watch": "tsc -w", - "prepublishOnly": "npm run build" - }, - "engineStrict": true, - "author": "Hyperledger", - "license": "Apache-2.0", - "dependencies": { - "fabric-contract-api": "~1.4.0", - "fabric-shim": "~1.4.0" - }, - "devDependencies": { - "@types/chai": "^4.1.7", - "@types/mocha": "^5.2.5", - "@types/node": "^10.12.10", - "@types/sinon": "^5.0.7", - "@types/sinon-chai": "^3.2.1", - "chai": "^4.2.0", - "mocha": "^5.2.0", - "nyc": "^13.1.0", - "sinon": "^7.1.1", - "sinon-chai": "^3.3.0", - "ts-node": "^7.0.1", - "tslint": "^5.11.0", - "typescript": "^3.1.6" - }, - "nyc": { - "extension": [ - ".ts", - ".tsx" - ], - "exclude": [ - "coverage/**", - "dist/**" - ], - "reporter": [ - "text-summary", - "html" - ], - "all": true, - "check-coverage": true, - "statements": 100, - "branches": 100, - "functions": 100, - "lines": 100 - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/car.ts b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/car.ts deleted file mode 100644 index ba1016253..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/car.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - */ - -export class Car { - public docType?: string; - public color: string; - public make: string; - public model: string; - public owner: string; -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/fabcar.ts b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/fabcar.ts deleted file mode 100644 index de72b0394..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/fabcar.ts +++ /dev/null @@ -1,153 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - */ - -import { Context, Contract } from 'fabric-contract-api'; -import { Car } from './car'; - -export class FabCar extends Contract { - - public async initLedger(ctx: Context) { - console.info('============= START : Initialize Ledger ==========='); - const cars: Car[] = [ - { - color: 'blue', - make: 'Toyota', - model: 'Prius', - owner: 'Tomoko', - }, - { - color: 'red', - make: 'Ford', - model: 'Mustang', - owner: 'Brad', - }, - { - color: 'green', - make: 'Hyundai', - model: 'Tucson', - owner: 'Jin Soo', - }, - { - color: 'yellow', - make: 'Volkswagen', - model: 'Passat', - owner: 'Max', - }, - { - color: 'black', - make: 'Tesla', - model: 'S', - owner: 'Adriana', - }, - { - color: 'purple', - make: 'Peugeot', - model: '205', - owner: 'Michel', - }, - { - color: 'white', - make: 'Chery', - model: 'S22L', - owner: 'Aarav', - }, - { - color: 'violet', - make: 'Fiat', - model: 'Punto', - owner: 'Pari', - }, - { - color: 'indigo', - make: 'Tata', - model: 'Nano', - owner: 'Valeria', - }, - { - color: 'brown', - make: 'Holden', - model: 'Barina', - owner: 'Shotaro', - }, - ]; - - for (let i = 0; i < cars.length; i++) { - cars[i].docType = 'car'; - await ctx.stub.putState('CAR' + i, Buffer.from(JSON.stringify(cars[i]))); - console.info('Added <--> ', cars[i]); - } - console.info('============= END : Initialize Ledger ==========='); - } - - public async queryCar(ctx: Context, carNumber: string): Promise { - const carAsBytes = await ctx.stub.getState(carNumber); // get the car from chaincode state - if (!carAsBytes || carAsBytes.length === 0) { - throw new Error(`${carNumber} does not exist`); - } - console.log(carAsBytes.toString()); - return carAsBytes.toString(); - } - - public async createCar(ctx: Context, carNumber: string, make: string, model: string, color: string, owner: string) { - console.info('============= START : Create Car ==========='); - - const car: Car = { - color, - docType: 'car', - make, - model, - owner, - }; - - await ctx.stub.putState(carNumber, Buffer.from(JSON.stringify(car))); - console.info('============= END : Create Car ==========='); - } - - public async queryAllCars(ctx: Context): Promise { - const startKey = 'CAR0'; - const endKey = 'CAR999'; - - const iterator = await ctx.stub.getStateByRange(startKey, endKey); - - const allResults = []; - while (true) { - const res = await iterator.next(); - - if (res.value && res.value.value.toString()) { - console.log(res.value.value.toString('utf8')); - - const Key = res.value.key; - let Record; - try { - Record = JSON.parse(res.value.value.toString('utf8')); - } catch (err) { - console.log(err); - Record = res.value.value.toString('utf8'); - } - allResults.push({ Key, Record }); - } - if (res.done) { - console.log('end of data'); - await iterator.close(); - console.info(allResults); - return JSON.stringify(allResults); - } - } - } - - public async changeCarOwner(ctx: Context, carNumber: string, newOwner: string) { - console.info('============= START : changeCarOwner ==========='); - - const carAsBytes = await ctx.stub.getState(carNumber); // get the car from chaincode state - if (!carAsBytes || carAsBytes.length === 0) { - throw new Error(`${carNumber} does not exist`); - } - const car: Car = JSON.parse(carAsBytes.toString()); - car.owner = newOwner; - - await ctx.stub.putState(carNumber, Buffer.from(JSON.stringify(car))); - console.info('============= END : changeCarOwner ==========='); - } - -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/index.ts b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/index.ts deleted file mode 100644 index c0a2fcf67..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/src/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - */ - -import { FabCar } from './fabcar'; -export { FabCar } from './fabcar'; - -export const contracts: any[] = [ FabCar ]; diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/tsconfig.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/tsconfig.json deleted file mode 100644 index 63890dd66..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "compilerOptions": { - "outDir": "dist", - "target": "es2017", - "moduleResolution": "node", - "module": "commonjs", - "declaration": true, - "sourceMap": true - }, - "include": ["./src/**/*"], - "exclude": ["./src/**/*.spec.ts"] -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/tslint.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/tslint.json deleted file mode 100644 index 0765acb34..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/fabcar/typescript/tslint.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "defaultSeverity": "error", - "extends": ["tslint:recommended"], - "jsRules": {}, - "rules": { - "indent": [true, "spaces", 4], - "linebreak-style": [true, "LF"], - "quotemark": [true, "single"], - "semicolon": [true, "always"], - "no-console": false, - "curly": true, - "triple-equals": true, - "no-string-throw": true, - "no-var-keyword": true, - "no-trailing-whitespace": true, - "object-literal-key-quotes": [true, "as-needed"] - }, - "rulesDirectory": [] -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/go/META-INF/statedb/couchdb/indexes/indexOwner.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/go/META-INF/statedb/couchdb/indexes/indexOwner.json deleted file mode 100644 index 0cf070623..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/go/META-INF/statedb/couchdb/indexes/indexOwner.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "index": { "fields": ["docType", "owner"] }, - "ddoc": "indexOwnerDoc", - "name": "indexOwner", - "type": "json" -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/go/marbles_chaincode.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/go/marbles_chaincode.go deleted file mode 100644 index 2ed3efd67..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/go/marbles_chaincode.go +++ /dev/null @@ -1,755 +0,0 @@ -/* - SPDX-License-Identifier: Apache-2.0 -*/ - -// ====CHAINCODE EXECUTION SAMPLES (CLI) ================== - -// ==== Invoke marbles ==== -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["initMarble","marble1","blue","35","tom"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["initMarble","marble2","red","50","tom"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["initMarble","marble3","blue","70","tom"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["transferMarble","marble2","jerry"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["transferMarblesBasedOnColor","blue","jerry"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["delete","marble1"]}' - -// ==== Query marbles ==== -// peer chaincode query -C myc1 -n marbles -c '{"Args":["readMarble","marble1"]}' -// peer chaincode query -C myc1 -n marbles -c '{"Args":["getMarblesByRange","marble1","marble3"]}' -// peer chaincode query -C myc1 -n marbles -c '{"Args":["getHistoryForMarble","marble1"]}' - -// Rich Query (Only supported if CouchDB is used as state database): -// peer chaincode query -C myc1 -n marbles -c '{"Args":["queryMarblesByOwner","tom"]}' -// peer chaincode query -C myc1 -n marbles -c '{"Args":["queryMarbles","{\"selector\":{\"owner\":\"tom\"}}"]}' - -// Rich Query with Pagination (Only supported if CouchDB is used as state database): -// peer chaincode query -C myc1 -n marbles -c '{"Args":["queryMarblesWithPagination","{\"selector\":{\"owner\":\"tom\"}}","3",""]}' - -// INDEXES TO SUPPORT COUCHDB RICH QUERIES -// -// Indexes in CouchDB are required in order to make JSON queries efficient and are required for -// any JSON query with a sort. As of Hyperledger Fabric 1.1, indexes may be packaged alongside -// chaincode in a META-INF/statedb/couchdb/indexes directory. Each index must be defined in its own -// text file with extension *.json with the index definition formatted in JSON following the -// CouchDB index JSON syntax as documented at: -// http://docs.couchdb.org/en/2.1.1/api/database/find.html#db-index -// -// This marbles02 example chaincode demonstrates a packaged -// index which you can find in META-INF/statedb/couchdb/indexes/indexOwner.json. -// For deployment of chaincode to production environments, it is recommended -// to define any indexes alongside chaincode so that the chaincode and supporting indexes -// are deployed automatically as a unit, once the chaincode has been installed on a peer and -// instantiated on a channel. See Hyperledger Fabric documentation for more details. -// -// If you have access to the your peer's CouchDB state database in a development environment, -// you may want to iteratively test various indexes in support of your chaincode queries. You -// can use the CouchDB Fauxton interface or a command line curl utility to create and update -// indexes. Then once you finalize an index, include the index definition alongside your -// chaincode in the META-INF/statedb/couchdb/indexes directory, for packaging and deployment -// to managed environments. -// -// In the examples below you can find index definitions that support marbles02 -// chaincode queries, along with the syntax that you can use in development environments -// to create the indexes in the CouchDB Fauxton interface or a curl command line utility. -// - -//Example hostname:port configurations to access CouchDB. -// -//To access CouchDB docker container from within another docker container or from vagrant environments: -// http://couchdb:5984/ -// -//Inside couchdb docker container -// http://127.0.0.1:5984/ - -// Index for docType, owner. -// -// Example curl command line to define index in the CouchDB channel_chaincode database -// curl -i -X POST -H "Content-Type: application/json" -d "{\"index\":{\"fields\":[\"docType\",\"owner\"]},\"name\":\"indexOwner\",\"ddoc\":\"indexOwnerDoc\",\"type\":\"json\"}" http://hostname:port/myc1_marbles/_index -// - -// Index for docType, owner, size (descending order). -// -// Example curl command line to define index in the CouchDB channel_chaincode database -// curl -i -X POST -H "Content-Type: application/json" -d "{\"index\":{\"fields\":[{\"size\":\"desc\"},{\"docType\":\"desc\"},{\"owner\":\"desc\"}]},\"ddoc\":\"indexSizeSortDoc\", \"name\":\"indexSizeSortDesc\",\"type\":\"json\"}" http://hostname:port/myc1_marbles/_index - -// Rich Query with index design doc and index name specified (Only supported if CouchDB is used as state database): -// peer chaincode query -C myc1 -n marbles -c '{"Args":["queryMarbles","{\"selector\":{\"docType\":\"marble\",\"owner\":\"tom\"}, \"use_index\":[\"_design/indexOwnerDoc\", \"indexOwner\"]}"]}' - -// Rich Query with index design doc specified only (Only supported if CouchDB is used as state database): -// peer chaincode query -C myc1 -n marbles -c '{"Args":["queryMarbles","{\"selector\":{\"docType\":{\"$eq\":\"marble\"},\"owner\":{\"$eq\":\"tom\"},\"size\":{\"$gt\":0}},\"fields\":[\"docType\",\"owner\",\"size\"],\"sort\":[{\"size\":\"desc\"}],\"use_index\":\"_design/indexSizeSortDoc\"}"]}' - -package main - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hyperledger/fabric/core/chaincode/shim" - pb "github.com/hyperledger/fabric/protos/peer" -) - -// SimpleChaincode example simple Chaincode implementation -type SimpleChaincode struct { -} - -type marble struct { - ObjectType string `json:"docType"` //docType is used to distinguish the various types of objects in state database - Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around - Color string `json:"color"` - Size int `json:"size"` - Owner string `json:"owner"` -} - -// =================================================================================== -// Main -// =================================================================================== -func main() { - err := shim.Start(new(SimpleChaincode)) - if err != nil { - fmt.Printf("Error starting Simple chaincode: %s", err) - } -} - -// Init initializes chaincode -// =========================== -func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { - return shim.Success(nil) -} - -// Invoke - Our entry point for Invocations -// ======================================== -func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response { - function, args := stub.GetFunctionAndParameters() - fmt.Println("invoke is running " + function) - - // Handle different functions - if function == "initMarble" { //create a new marble - return t.initMarble(stub, args) - } else if function == "transferMarble" { //change owner of a specific marble - return t.transferMarble(stub, args) - } else if function == "transferMarblesBasedOnColor" { //transfer all marbles of a certain color - return t.transferMarblesBasedOnColor(stub, args) - } else if function == "delete" { //delete a marble - return t.delete(stub, args) - } else if function == "readMarble" { //read a marble - return t.readMarble(stub, args) - } else if function == "queryMarblesByOwner" { //find marbles for owner X using rich query - return t.queryMarblesByOwner(stub, args) - } else if function == "queryMarbles" { //find marbles based on an ad hoc rich query - return t.queryMarbles(stub, args) - } else if function == "getHistoryForMarble" { //get history of values for a marble - return t.getHistoryForMarble(stub, args) - } else if function == "getMarblesByRange" { //get marbles based on range query - return t.getMarblesByRange(stub, args) - } else if function == "getMarblesByRangeWithPagination" { - return t.getMarblesByRangeWithPagination(stub, args) - } else if function == "queryMarblesWithPagination" { - return t.queryMarblesWithPagination(stub, args) - } - - fmt.Println("invoke did not find func: " + function) //error - return shim.Error("Received unknown function invocation") -} - -// ============================================================ -// initMarble - create a new marble, store into chaincode state -// ============================================================ -func (t *SimpleChaincode) initMarble(stub shim.ChaincodeStubInterface, args []string) pb.Response { - var err error - - // 0 1 2 3 - // "asdf", "blue", "35", "bob" - if len(args) != 4 { - return shim.Error("Incorrect number of arguments. Expecting 4") - } - - // ==== Input sanitation ==== - fmt.Println("- start init marble") - if len(args[0]) <= 0 { - return shim.Error("1st argument must be a non-empty string") - } - if len(args[1]) <= 0 { - return shim.Error("2nd argument must be a non-empty string") - } - if len(args[2]) <= 0 { - return shim.Error("3rd argument must be a non-empty string") - } - if len(args[3]) <= 0 { - return shim.Error("4th argument must be a non-empty string") - } - marbleName := args[0] - color := strings.ToLower(args[1]) - owner := strings.ToLower(args[3]) - size, err := strconv.Atoi(args[2]) - if err != nil { - return shim.Error("3rd argument must be a numeric string") - } - - // ==== Check if marble already exists ==== - marbleAsBytes, err := stub.GetState(marbleName) - if err != nil { - return shim.Error("Failed to get marble: " + err.Error()) - } else if marbleAsBytes != nil { - fmt.Println("This marble already exists: " + marbleName) - return shim.Error("This marble already exists: " + marbleName) - } - - // ==== Create marble object and marshal to JSON ==== - objectType := "marble" - marble := &marble{objectType, marbleName, color, size, owner} - marbleJSONasBytes, err := json.Marshal(marble) - if err != nil { - return shim.Error(err.Error()) - } - //Alternatively, build the marble json string manually if you don't want to use struct marshalling - //marbleJSONasString := `{"docType":"Marble", "name": "` + marbleName + `", "color": "` + color + `", "size": ` + strconv.Itoa(size) + `, "owner": "` + owner + `"}` - //marbleJSONasBytes := []byte(str) - - // === Save marble to state === - err = stub.PutState(marbleName, marbleJSONasBytes) - if err != nil { - return shim.Error(err.Error()) - } - - // ==== Index the marble to enable color-based range queries, e.g. return all blue marbles ==== - // An 'index' is a normal key/value entry in state. - // The key is a composite key, with the elements that you want to range query on listed first. - // In our case, the composite key is based on indexName~color~name. - // This will enable very efficient state range queries based on composite keys matching indexName~color~* - indexName := "color~name" - colorNameIndexKey, err := stub.CreateCompositeKey(indexName, []string{marble.Color, marble.Name}) - if err != nil { - return shim.Error(err.Error()) - } - // Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the marble. - // Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value - value := []byte{0x00} - stub.PutState(colorNameIndexKey, value) - - // ==== Marble saved and indexed. Return success ==== - fmt.Println("- end init marble") - return shim.Success(nil) -} - -// =============================================== -// readMarble - read a marble from chaincode state -// =============================================== -func (t *SimpleChaincode) readMarble(stub shim.ChaincodeStubInterface, args []string) pb.Response { - var name, jsonResp string - var err error - - if len(args) != 1 { - return shim.Error("Incorrect number of arguments. Expecting name of the marble to query") - } - - name = args[0] - valAsbytes, err := stub.GetState(name) //get the marble from chaincode state - if err != nil { - jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}" - return shim.Error(jsonResp) - } else if valAsbytes == nil { - jsonResp = "{\"Error\":\"Marble does not exist: " + name + "\"}" - return shim.Error(jsonResp) - } - - return shim.Success(valAsbytes) -} - -// ================================================== -// delete - remove a marble key/value pair from state -// ================================================== -func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response { - var jsonResp string - var marbleJSON marble - if len(args) != 1 { - return shim.Error("Incorrect number of arguments. Expecting 1") - } - marbleName := args[0] - - // to maintain the color~name index, we need to read the marble first and get its color - valAsbytes, err := stub.GetState(marbleName) //get the marble from chaincode state - if err != nil { - jsonResp = "{\"Error\":\"Failed to get state for " + marbleName + "\"}" - return shim.Error(jsonResp) - } else if valAsbytes == nil { - jsonResp = "{\"Error\":\"Marble does not exist: " + marbleName + "\"}" - return shim.Error(jsonResp) - } - - err = json.Unmarshal([]byte(valAsbytes), &marbleJSON) - if err != nil { - jsonResp = "{\"Error\":\"Failed to decode JSON of: " + marbleName + "\"}" - return shim.Error(jsonResp) - } - - err = stub.DelState(marbleName) //remove the marble from chaincode state - if err != nil { - return shim.Error("Failed to delete state:" + err.Error()) - } - - // maintain the index - indexName := "color~name" - colorNameIndexKey, err := stub.CreateCompositeKey(indexName, []string{marbleJSON.Color, marbleJSON.Name}) - if err != nil { - return shim.Error(err.Error()) - } - - // Delete index entry to state. - err = stub.DelState(colorNameIndexKey) - if err != nil { - return shim.Error("Failed to delete state:" + err.Error()) - } - return shim.Success(nil) -} - -// =========================================================== -// transfer a marble by setting a new owner name on the marble -// =========================================================== -func (t *SimpleChaincode) transferMarble(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - // 0 1 - // "name", "bob" - if len(args) < 2 { - return shim.Error("Incorrect number of arguments. Expecting 2") - } - - marbleName := args[0] - newOwner := strings.ToLower(args[1]) - fmt.Println("- start transferMarble ", marbleName, newOwner) - - marbleAsBytes, err := stub.GetState(marbleName) - if err != nil { - return shim.Error("Failed to get marble:" + err.Error()) - } else if marbleAsBytes == nil { - return shim.Error("Marble does not exist") - } - - marbleToTransfer := marble{} - err = json.Unmarshal(marbleAsBytes, &marbleToTransfer) //unmarshal it aka JSON.parse() - if err != nil { - return shim.Error(err.Error()) - } - marbleToTransfer.Owner = newOwner //change the owner - - marbleJSONasBytes, _ := json.Marshal(marbleToTransfer) - err = stub.PutState(marbleName, marbleJSONasBytes) //rewrite the marble - if err != nil { - return shim.Error(err.Error()) - } - - fmt.Println("- end transferMarble (success)") - return shim.Success(nil) -} - -// =========================================================================================== -// constructQueryResponseFromIterator constructs a JSON array containing query results from -// a given result iterator -// =========================================================================================== -func constructQueryResponseFromIterator(resultsIterator shim.StateQueryIteratorInterface) (*bytes.Buffer, error) { - // buffer is a JSON array containing QueryResults - var buffer bytes.Buffer - buffer.WriteString("[") - - bArrayMemberAlreadyWritten := false - for resultsIterator.HasNext() { - queryResponse, err := resultsIterator.Next() - if err != nil { - return nil, err - } - // Add a comma before array members, suppress it for the first array member - if bArrayMemberAlreadyWritten == true { - buffer.WriteString(",") - } - buffer.WriteString("{\"Key\":") - buffer.WriteString("\"") - buffer.WriteString(queryResponse.Key) - buffer.WriteString("\"") - - buffer.WriteString(", \"Record\":") - // Record is a JSON object, so we write as-is - buffer.WriteString(string(queryResponse.Value)) - buffer.WriteString("}") - bArrayMemberAlreadyWritten = true - } - buffer.WriteString("]") - - return &buffer, nil -} - -// =========================================================================================== -// addPaginationMetadataToQueryResults adds QueryResponseMetadata, which contains pagination -// info, to the constructed query results -// =========================================================================================== -func addPaginationMetadataToQueryResults(buffer *bytes.Buffer, responseMetadata *pb.QueryResponseMetadata) *bytes.Buffer { - - buffer.WriteString("[{\"ResponseMetadata\":{\"RecordsCount\":") - buffer.WriteString("\"") - buffer.WriteString(fmt.Sprintf("%v", responseMetadata.FetchedRecordsCount)) - buffer.WriteString("\"") - buffer.WriteString(", \"Bookmark\":") - buffer.WriteString("\"") - buffer.WriteString(responseMetadata.Bookmark) - buffer.WriteString("\"}}]") - - return buffer -} - -// =========================================================================================== -// getMarblesByRange performs a range query based on the start and end keys provided. - -// Read-only function results are not typically submitted to ordering. If the read-only -// results are submitted to ordering, or if the query is used in an update transaction -// and submitted to ordering, then the committing peers will re-execute to guarantee that -// result sets are stable between endorsement time and commit time. The transaction is -// invalidated by the committing peers if the result set has changed between endorsement -// time and commit time. -// Therefore, range queries are a safe option for performing update transactions based on query results. -// =========================================================================================== -func (t *SimpleChaincode) getMarblesByRange(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - if len(args) < 2 { - return shim.Error("Incorrect number of arguments. Expecting 2") - } - - startKey := args[0] - endKey := args[1] - - resultsIterator, err := stub.GetStateByRange(startKey, endKey) - if err != nil { - return shim.Error(err.Error()) - } - defer resultsIterator.Close() - - buffer, err := constructQueryResponseFromIterator(resultsIterator) - if err != nil { - return shim.Error(err.Error()) - } - - fmt.Printf("- getMarblesByRange queryResult:\n%s\n", buffer.String()) - - return shim.Success(buffer.Bytes()) -} - -// ==== Example: GetStateByPartialCompositeKey/RangeQuery ========================================= -// transferMarblesBasedOnColor will transfer marbles of a given color to a certain new owner. -// Uses a GetStateByPartialCompositeKey (range query) against color~name 'index'. -// Committing peers will re-execute range queries to guarantee that result sets are stable -// between endorsement time and commit time. The transaction is invalidated by the -// committing peers if the result set has changed between endorsement time and commit time. -// Therefore, range queries are a safe option for performing update transactions based on query results. -// =========================================================================================== -func (t *SimpleChaincode) transferMarblesBasedOnColor(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - // 0 1 - // "color", "bob" - if len(args) < 2 { - return shim.Error("Incorrect number of arguments. Expecting 2") - } - - color := args[0] - newOwner := strings.ToLower(args[1]) - fmt.Println("- start transferMarblesBasedOnColor ", color, newOwner) - - // Query the color~name index by color - // This will execute a key range query on all keys starting with 'color' - coloredMarbleResultsIterator, err := stub.GetStateByPartialCompositeKey("color~name", []string{color}) - if err != nil { - return shim.Error(err.Error()) - } - defer coloredMarbleResultsIterator.Close() - - // Iterate through result set and for each marble found, transfer to newOwner - var i int - for i = 0; coloredMarbleResultsIterator.HasNext(); i++ { - // Note that we don't get the value (2nd return variable), we'll just get the marble name from the composite key - responseRange, err := coloredMarbleResultsIterator.Next() - if err != nil { - return shim.Error(err.Error()) - } - - // get the color and name from color~name composite key - objectType, compositeKeyParts, err := stub.SplitCompositeKey(responseRange.Key) - if err != nil { - return shim.Error(err.Error()) - } - returnedColor := compositeKeyParts[0] - returnedMarbleName := compositeKeyParts[1] - fmt.Printf("- found a marble from index:%s color:%s name:%s\n", objectType, returnedColor, returnedMarbleName) - - // Now call the transfer function for the found marble. - // Re-use the same function that is used to transfer individual marbles - response := t.transferMarble(stub, []string{returnedMarbleName, newOwner}) - // if the transfer failed break out of loop and return error - if response.Status != shim.OK { - return shim.Error("Transfer failed: " + response.Message) - } - } - - responsePayload := fmt.Sprintf("Transferred %d %s marbles to %s", i, color, newOwner) - fmt.Println("- end transferMarblesBasedOnColor: " + responsePayload) - return shim.Success([]byte(responsePayload)) -} - -// =======Rich queries ========================================================================= -// Two examples of rich queries are provided below (parameterized query and ad hoc query). -// Rich queries pass a query string to the state database. -// Rich queries are only supported by state database implementations -// that support rich query (e.g. CouchDB). -// The query string is in the syntax of the underlying state database. -// With rich queries there is no guarantee that the result set hasn't changed between -// endorsement time and commit time, aka 'phantom reads'. -// Therefore, rich queries should not be used in update transactions, unless the -// application handles the possibility of result set changes between endorsement and commit time. -// Rich queries can be used for point-in-time queries against a peer. -// ============================================================================================ - -// ===== Example: Parameterized rich query ================================================= -// queryMarblesByOwner queries for marbles based on a passed in owner. -// This is an example of a parameterized query where the query logic is baked into the chaincode, -// and accepting a single query parameter (owner). -// Only available on state databases that support rich query (e.g. CouchDB) -// ========================================================================================= -func (t *SimpleChaincode) queryMarblesByOwner(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - // 0 - // "bob" - if len(args) < 1 { - return shim.Error("Incorrect number of arguments. Expecting 1") - } - - owner := strings.ToLower(args[0]) - - queryString := fmt.Sprintf("{\"selector\":{\"docType\":\"marble\",\"owner\":\"%s\"}}", owner) - - queryResults, err := getQueryResultForQueryString(stub, queryString) - if err != nil { - return shim.Error(err.Error()) - } - return shim.Success(queryResults) -} - -// ===== Example: Ad hoc rich query ======================================================== -// queryMarbles uses a query string to perform a query for marbles. -// Query string matching state database syntax is passed in and executed as is. -// Supports ad hoc queries that can be defined at runtime by the client. -// If this is not desired, follow the queryMarblesForOwner example for parameterized queries. -// Only available on state databases that support rich query (e.g. CouchDB) -// ========================================================================================= -func (t *SimpleChaincode) queryMarbles(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - // 0 - // "queryString" - if len(args) < 1 { - return shim.Error("Incorrect number of arguments. Expecting 1") - } - - queryString := args[0] - - queryResults, err := getQueryResultForQueryString(stub, queryString) - if err != nil { - return shim.Error(err.Error()) - } - return shim.Success(queryResults) -} - -// ========================================================================================= -// getQueryResultForQueryString executes the passed in query string. -// Result set is built and returned as a byte array containing the JSON results. -// ========================================================================================= -func getQueryResultForQueryString(stub shim.ChaincodeStubInterface, queryString string) ([]byte, error) { - - fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString) - - resultsIterator, err := stub.GetQueryResult(queryString) - if err != nil { - return nil, err - } - defer resultsIterator.Close() - - buffer, err := constructQueryResponseFromIterator(resultsIterator) - if err != nil { - return nil, err - } - - fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String()) - - return buffer.Bytes(), nil -} - -// ====== Pagination ========================================================================= -// Pagination provides a method to retrieve records with a defined pagesize and -// start point (bookmark). An empty string bookmark defines the first "page" of a query -// result. Paginated queries return a bookmark that can be used in -// the next query to retrieve the next page of results. Paginated queries extend -// rich queries and range queries to include a pagesize and bookmark. -// -// Two examples are provided in this example. The first is getMarblesByRangeWithPagination -// which executes a paginated range query. -// The second example is a paginated query for rich ad-hoc queries. -// ========================================================================================= - -// ====== Example: Pagination with Range Query =============================================== -// getMarblesByRangeWithPagination performs a range query based on the start & end key, -// page size and a bookmark. - -// The number of fetched records will be equal to or lesser than the page size. -// Paginated range queries are only valid for read only transactions. -// =========================================================================================== -func (t *SimpleChaincode) getMarblesByRangeWithPagination(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - if len(args) < 4 { - return shim.Error("Incorrect number of arguments. Expecting 4") - } - - startKey := args[0] - endKey := args[1] - //return type of ParseInt is int64 - pageSize, err := strconv.ParseInt(args[2], 10, 32) - if err != nil { - return shim.Error(err.Error()) - } - bookmark := args[3] - - resultsIterator, responseMetadata, err := stub.GetStateByRangeWithPagination(startKey, endKey, int32(pageSize), bookmark) - if err != nil { - return shim.Error(err.Error()) - } - defer resultsIterator.Close() - - buffer, err := constructQueryResponseFromIterator(resultsIterator) - if err != nil { - return shim.Error(err.Error()) - } - - bufferWithPaginationInfo := addPaginationMetadataToQueryResults(buffer, responseMetadata) - - fmt.Printf("- getMarblesByRange queryResult:\n%s\n", bufferWithPaginationInfo.String()) - - return shim.Success(buffer.Bytes()) -} - -// ===== Example: Pagination with Ad hoc Rich Query ======================================================== -// queryMarblesWithPagination uses a query string, page size and a bookmark to perform a query -// for marbles. Query string matching state database syntax is passed in and executed as is. -// The number of fetched records would be equal to or lesser than the specified page size. -// Supports ad hoc queries that can be defined at runtime by the client. -// If this is not desired, follow the queryMarblesForOwner example for parameterized queries. -// Only available on state databases that support rich query (e.g. CouchDB) -// Paginated queries are only valid for read only transactions. -// ========================================================================================= -func (t *SimpleChaincode) queryMarblesWithPagination(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - // 0 - // "queryString" - if len(args) < 3 { - return shim.Error("Incorrect number of arguments. Expecting 3") - } - - queryString := args[0] - //return type of ParseInt is int64 - pageSize, err := strconv.ParseInt(args[1], 10, 32) - if err != nil { - return shim.Error(err.Error()) - } - bookmark := args[2] - - queryResults, err := getQueryResultForQueryStringWithPagination(stub, queryString, int32(pageSize), bookmark) - if err != nil { - return shim.Error(err.Error()) - } - return shim.Success(queryResults) -} - -// ========================================================================================= -// getQueryResultForQueryStringWithPagination executes the passed in query string with -// pagination info. Result set is built and returned as a byte array containing the JSON results. -// ========================================================================================= -func getQueryResultForQueryStringWithPagination(stub shim.ChaincodeStubInterface, queryString string, pageSize int32, bookmark string) ([]byte, error) { - - fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString) - - resultsIterator, responseMetadata, err := stub.GetQueryResultWithPagination(queryString, pageSize, bookmark) - if err != nil { - return nil, err - } - defer resultsIterator.Close() - - buffer, err := constructQueryResponseFromIterator(resultsIterator) - if err != nil { - return nil, err - } - - bufferWithPaginationInfo := addPaginationMetadataToQueryResults(buffer, responseMetadata) - - fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", bufferWithPaginationInfo.String()) - - return buffer.Bytes(), nil -} - -func (t *SimpleChaincode) getHistoryForMarble(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - if len(args) < 1 { - return shim.Error("Incorrect number of arguments. Expecting 1") - } - - marbleName := args[0] - - fmt.Printf("- start getHistoryForMarble: %s\n", marbleName) - - resultsIterator, err := stub.GetHistoryForKey(marbleName) - if err != nil { - return shim.Error(err.Error()) - } - defer resultsIterator.Close() - - // buffer is a JSON array containing historic values for the marble - var buffer bytes.Buffer - buffer.WriteString("[") - - bArrayMemberAlreadyWritten := false - for resultsIterator.HasNext() { - response, err := resultsIterator.Next() - if err != nil { - return shim.Error(err.Error()) - } - // Add a comma before array members, suppress it for the first array member - if bArrayMemberAlreadyWritten == true { - buffer.WriteString(",") - } - buffer.WriteString("{\"TxId\":") - buffer.WriteString("\"") - buffer.WriteString(response.TxId) - buffer.WriteString("\"") - - buffer.WriteString(", \"Value\":") - // if it was a delete operation on given key, then we need to set the - //corresponding value null. Else, we will write the response.Value - //as-is (as the Value itself a JSON marble) - if response.IsDelete { - buffer.WriteString("null") - } else { - buffer.WriteString(string(response.Value)) - } - - buffer.WriteString(", \"Timestamp\":") - buffer.WriteString("\"") - buffer.WriteString(time.Unix(response.Timestamp.Seconds, int64(response.Timestamp.Nanos)).String()) - buffer.WriteString("\"") - - buffer.WriteString(", \"IsDelete\":") - buffer.WriteString("\"") - buffer.WriteString(strconv.FormatBool(response.IsDelete)) - buffer.WriteString("\"") - - buffer.WriteString("}") - bArrayMemberAlreadyWritten = true - } - buffer.WriteString("]") - - fmt.Printf("- getHistoryForMarble returning:\n%s\n", buffer.String()) - - return shim.Success(buffer.Bytes()) -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/META-INF/statedb/couchdb/indexes/indexOwner.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/META-INF/statedb/couchdb/indexes/indexOwner.json deleted file mode 100644 index 0cf070623..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/META-INF/statedb/couchdb/indexes/indexOwner.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "index": { "fields": ["docType", "owner"] }, - "ddoc": "indexOwnerDoc", - "name": "indexOwner", - "type": "json" -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/marbles_chaincode.js b/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/marbles_chaincode.js deleted file mode 100644 index 3d2d67b97..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/marbles_chaincode.js +++ /dev/null @@ -1,509 +0,0 @@ -/* -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 -*/ - -// ====CHAINCODE EXECUTION SAMPLES (CLI) ================== - -// ==== Invoke marbles ==== -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["initMarble","marble1","blue","35","tom"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["initMarble","marble2","red","50","tom"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["initMarble","marble3","blue","70","tom"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["transferMarble","marble2","jerry"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["transferMarblesBasedOnColor","blue","jerry"]}' -// peer chaincode invoke -C myc1 -n marbles -c '{"Args":["delete","marble1"]}' - -// ==== Query marbles ==== -// peer chaincode query -C myc1 -n marbles -c '{"Args":["readMarble","marble1"]}' -// peer chaincode query -C myc1 -n marbles -c '{"Args":["getMarblesByRange","marble1","marble3"]}' -// peer chaincode query -C myc1 -n marbles -c '{"Args":["getHistoryForMarble","marble1"]}' -// peer chaincode query -C myc1 -n marbles -c '{"Args":["getMarblesByRangeWithPagination","marble1","marble3","3",""]}' - -// Rich Query (Only supported if CouchDB is used as state database): -// peer chaincode query -C myc1 -n marbles -c '{"Args":["queryMarblesByOwner","tom"]}' -// peer chaincode query -C myc1 -n marbles -c '{"Args":["queryMarbles","{\"selector\":{\"owner\":\"tom\"}}"]}' - -// Rich Query with Pagination (Only supported if CouchDB is used as state database): -// peer chaincode query -C myc1 -n marbles -c '{"Args":["queryMarblesWithPagination","{\"selector\":{\"owner\":\"tom\"}}","3",""]}' - -'use strict'; -const shim = require('fabric-shim'); -const util = require('util'); - -let Chaincode = class { - async Init(stub) { - let ret = stub.getFunctionAndParameters(); - console.info(ret); - console.info('=========== Instantiated Marbles Chaincode ==========='); - return shim.success(); - } - - async Invoke(stub) { - console.info('Transaction ID: ' + stub.getTxID()); - console.info(util.format('Args: %j', stub.getArgs())); - - let ret = stub.getFunctionAndParameters(); - console.info(ret); - - let method = this[ret.fcn]; - if (!method) { - console.log('no function of name:' + ret.fcn + ' found'); - throw new Error('Received unknown function ' + ret.fcn + ' invocation'); - } - try { - let payload = await method(stub, ret.params, this); - return shim.success(payload); - } catch (err) { - console.log(err); - return shim.error(err); - } - } - - // =============================================== - // initMarble - create a new marble - // =============================================== - async initMarble(stub, args, thisClass) { - if (args.length != 4) { - throw new Error('Incorrect number of arguments. Expecting 4'); - } - // ==== Input sanitation ==== - console.info('--- start init marble ---'); - if (args[0].lenth <= 0) { - throw new Error('1st argument must be a non-empty string'); - } - if (args[1].lenth <= 0) { - throw new Error('2nd argument must be a non-empty string'); - } - if (args[2].lenth <= 0) { - throw new Error('3rd argument must be a non-empty string'); - } - if (args[3].lenth <= 0) { - throw new Error('4th argument must be a non-empty string'); - } - let marbleName = args[0]; - let color = args[1].toLowerCase(); - let owner = args[3].toLowerCase(); - let size = parseInt(args[2]); - if (typeof size !== 'number') { - throw new Error('3rd argument must be a numeric string'); - } - - // ==== Check if marble already exists ==== - let marbleState = await stub.getState(marbleName); - if (marbleState.toString()) { - throw new Error('This marble already exists: ' + marbleName); - } - - // ==== Create marble object and marshal to JSON ==== - let marble = {}; - marble.docType = 'marble'; - marble.name = marbleName; - marble.color = color; - marble.size = size; - marble.owner = owner; - - // === Save marble to state === - await stub.putState(marbleName, Buffer.from(JSON.stringify(marble))); - let indexName = 'color~name'; - let colorNameIndexKey = await stub.createCompositeKey(indexName, [ - marble.color, - marble.name - ]); - console.info(colorNameIndexKey); - // Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the marble. - // Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value - await stub.putState(colorNameIndexKey, Buffer.from('\u0000')); - // ==== Marble saved and indexed. Return success ==== - console.info('- end init marble'); - } - - // =============================================== - // readMarble - read a marble from chaincode state - // =============================================== - async readMarble(stub, args, thisClass) { - if (args.length != 1) { - throw new Error( - 'Incorrect number of arguments. Expecting name of the marble to query' - ); - } - - let name = args[0]; - if (!name) { - throw new Error(' marble name must not be empty'); - } - let marbleAsbytes = await stub.getState(name); //get the marble from chaincode state - if (!marbleAsbytes.toString()) { - let jsonResp = {}; - jsonResp.Error = 'Marble does not exist: ' + name; - throw new Error(JSON.stringify(jsonResp)); - } - console.info('======================================='); - console.log(marbleAsbytes.toString()); - console.info('======================================='); - return marbleAsbytes; - } - - // ================================================== - // delete - remove a marble key/value pair from state - // ================================================== - async delete(stub, args, thisClass) { - if (args.length != 1) { - throw new Error( - 'Incorrect number of arguments. Expecting name of the marble to delete' - ); - } - let marbleName = args[0]; - if (!marbleName) { - throw new Error('marble name must not be empty'); - } - // to maintain the color~name index, we need to read the marble first and get its color - let valAsbytes = await stub.getState(marbleName); //get the marble from chaincode state - let jsonResp = {}; - if (!valAsbytes) { - jsonResp.error = 'marble does not exist: ' + name; - throw new Error(jsonResp); - } - let marbleJSON = {}; - try { - marbleJSON = JSON.parse(valAsbytes.toString()); - } catch (err) { - jsonResp = {}; - jsonResp.error = 'Failed to decode JSON of: ' + marbleName; - throw new Error(jsonResp); - } - - await stub.deleteState(marbleName); //remove the marble from chaincode state - - // delete the index - let indexName = 'color~name'; - let colorNameIndexKey = stub.createCompositeKey(indexName, [ - marbleJSON.color, - marbleJSON.name - ]); - if (!colorNameIndexKey) { - throw new Error(' Failed to create the createCompositeKey'); - } - // Delete index entry to state. - await stub.deleteState(colorNameIndexKey); - } - - // =========================================================== - // transfer a marble by setting a new owner name on the marble - // =========================================================== - async transferMarble(stub, args, thisClass) { - // 0 1 - // 'name', 'bob' - if (args.length < 2) { - throw new Error( - 'Incorrect number of arguments. Expecting marblename and owner' - ); - } - - let marbleName = args[0]; - let newOwner = args[1].toLowerCase(); - console.info('- start transferMarble ', marbleName, newOwner); - - let marbleAsBytes = await stub.getState(marbleName); - if (!marbleAsBytes || !marbleAsBytes.toString()) { - throw new Error('marble does not exist'); - } - let marbleToTransfer = {}; - try { - marbleToTransfer = JSON.parse(marbleAsBytes.toString()); //unmarshal - } catch (err) { - let jsonResp = {}; - jsonResp.error = 'Failed to decode JSON of: ' + marbleName; - throw new Error(jsonResp); - } - console.info(marbleToTransfer); - marbleToTransfer.owner = newOwner; //change the owner - - let marbleJSONasBytes = Buffer.from(JSON.stringify(marbleToTransfer)); - await stub.putState(marbleName, marbleJSONasBytes); //rewrite the marble - - console.info('- end transferMarble (success)'); - } - - // =========================================================================================== - // getMarblesByRange performs a range query based on the start and end keys provided. - - // Read-only function results are not typically submitted to ordering. If the read-only - // results are submitted to ordering, or if the query is used in an update transaction - // and submitted to ordering, then the committing peers will re-execute to guarantee that - // result sets are stable between endorsement time and commit time. The transaction is - // invalidated by the committing peers if the result set has changed between endorsement - // time and commit time. - // Therefore, range queries are a safe option for performing update transactions based on query results. - // =========================================================================================== - async getMarblesByRange(stub, args, thisClass) { - if (args.length < 2) { - throw new Error('Incorrect number of arguments. Expecting 2'); - } - - let startKey = args[0]; - let endKey = args[1]; - - let resultsIterator = await stub.getStateByRange(startKey, endKey); - let method = thisClass['getAllResults']; - let results = await method(resultsIterator, false); - - return Buffer.from(JSON.stringify(results)); - } - - // ==== Example: GetStateByPartialCompositeKey/RangeQuery ========================================= - // transferMarblesBasedOnColor will transfer marbles of a given color to a certain new owner. - // Uses a GetStateByPartialCompositeKey (range query) against color~name 'index'. - // Committing peers will re-execute range queries to guarantee that result sets are stable - // between endorsement time and commit time. The transaction is invalidated by the - // committing peers if the result set has changed between endorsement time and commit time. - // Therefore, range queries are a safe option for performing update transactions based on query results. - // =========================================================================================== - async transferMarblesBasedOnColor(stub, args, thisClass) { - // 0 1 - // 'color', 'bob' - if (args.length < 2) { - throw new Error('Incorrect number of arguments. Expecting color and owner'); - } - - let color = args[0]; - let newOwner = args[1].toLowerCase(); - console.info('- start transferMarblesBasedOnColor ', color, newOwner); - - // Query the color~name index by color - // This will execute a key range query on all keys starting with 'color' - let coloredMarbleResultsIterator = await stub.getStateByPartialCompositeKey( - 'color~name', - [color] - ); - - let method = thisClass['transferMarble']; - // Iterate through result set and for each marble found, transfer to newOwner - while (true) { - let responseRange = await coloredMarbleResultsIterator.next(); - if (!responseRange || !responseRange.value || !responseRange.value.key) { - return; - } - console.log(responseRange.value.key); - - // let value = res.value.value.toString('utf8'); - let objectType; - let attributes; - ({ objectType, attributes } = await stub.splitCompositeKey( - responseRange.value.key - )); - - let returnedColor = attributes[0]; - let returnedMarbleName = attributes[1]; - console.info( - util.format( - '- found a marble from index:%s color:%s name:%s\n', - objectType, - returnedColor, - returnedMarbleName - ) - ); - - // Now call the transfer function for the found marble. - // Re-use the same function that is used to transfer individual marbles - let response = await method(stub, [returnedMarbleName, newOwner]); - } - - let responsePayload = util.format( - 'Transferred %s marbles to %s', - color, - newOwner - ); - console.info('- end transferMarblesBasedOnColor: ' + responsePayload); - } - - // ===== Example: Parameterized rich query ================================================= - // queryMarblesByOwner queries for marbles based on a passed in owner. - // This is an example of a parameterized query where the query logic is baked into the chaincode, - // and accepting a single query parameter (owner). - // Only available on state databases that support rich query (e.g. CouchDB) - // ========================================================================================= - async queryMarblesByOwner(stub, args, thisClass) { - // 0 - // 'bob' - if (args.length < 1) { - throw new Error('Incorrect number of arguments. Expecting owner name.'); - } - - let owner = args[0].toLowerCase(); - let queryString = {}; - queryString.selector = {}; - queryString.selector.docType = 'marble'; - queryString.selector.owner = owner; - let method = thisClass['getQueryResultForQueryString']; - let queryResults = await method(stub, JSON.stringify(queryString), thisClass); - return queryResults; //shim.success(queryResults); - } - - // ===== Example: Ad hoc rich query ======================================================== - // queryMarbles uses a query string to perform a query for marbles. - // Query string matching state database syntax is passed in and executed as is. - // Supports ad hoc queries that can be defined at runtime by the client. - // If this is not desired, follow the queryMarblesForOwner example for parameterized queries. - // Only available on state databases that support rich query (e.g. CouchDB) - // ========================================================================================= - async queryMarbles(stub, args, thisClass) { - // 0 - // 'queryString' - if (args.length < 1) { - throw new Error('Incorrect number of arguments. Expecting queryString'); - } - let queryString = args[0]; - if (!queryString) { - throw new Error('queryString must not be empty'); - } - let method = thisClass['getQueryResultForQueryString']; - let queryResults = await method(stub, queryString, thisClass); - return queryResults; - } - - async getAllResults(iterator, isHistory) { - let allResults = []; - while (true) { - let res = await iterator.next(); - - if (res.value && res.value.value.toString()) { - let jsonRes = {}; - console.log(res.value.value.toString('utf8')); - - if (isHistory && isHistory === true) { - jsonRes.TxId = res.value.tx_id; - jsonRes.Timestamp = res.value.timestamp; - jsonRes.IsDelete = res.value.is_delete.toString(); - try { - jsonRes.Value = JSON.parse(res.value.value.toString('utf8')); - } catch (err) { - console.log(err); - jsonRes.Value = res.value.value.toString('utf8'); - } - } else { - jsonRes.Key = res.value.key; - try { - jsonRes.Record = JSON.parse(res.value.value.toString('utf8')); - } catch (err) { - console.log(err); - jsonRes.Record = res.value.value.toString('utf8'); - } - } - allResults.push(jsonRes); - } - if (res.done) { - console.log('end of data'); - await iterator.close(); - console.info(allResults); - return allResults; - } - } - } - - // ========================================================================================= - // getQueryResultForQueryString executes the passed in query string. - // Result set is built and returned as a byte array containing the JSON results. - // ========================================================================================= - async getQueryResultForQueryString(stub, queryString, thisClass) { - console.info('- getQueryResultForQueryString queryString:\n' + queryString); - let resultsIterator = await stub.getQueryResult(queryString); - let method = thisClass['getAllResults']; - - let results = await method(resultsIterator, false); - - return Buffer.from(JSON.stringify(results)); - } - - async getHistoryForMarble(stub, args, thisClass) { - if (args.length < 1) { - throw new Error('Incorrect number of arguments. Expecting 1'); - } - let marbleName = args[0]; - console.info('- start getHistoryForMarble: %s\n', marbleName); - - let resultsIterator = await stub.getHistoryForKey(marbleName); - let method = thisClass['getAllResults']; - let results = await method(resultsIterator, true); - - return Buffer.from(JSON.stringify(results)); - } - - // ====== Pagination ========================================================================= - // Pagination provides a method to retrieve records with a defined pagesize and - // start point (bookmark). An empty string bookmark defines the first "page" of a query - // result. Paginated queries return a bookmark that can be used in - // the next query to retrieve the next page of results. Paginated queries extend - // rich queries and range queries to include a pagesize and bookmark. - // - // Two examples are provided in this example. The first is getMarblesByRangeWithPagination - // which executes a paginated range query. - // The second example is a paginated query for rich ad-hoc queries. - // ========================================================================================= - - // ====== Example: Pagination with Range Query =============================================== - // getMarblesByRangeWithPagination performs a range query based on the start & end key, - // page size and a bookmark. - // - // The number of fetched records will be equal to or lesser than the page size. - // Paginated range queries are only valid for read only transactions. - // =========================================================================================== - async getMarblesByRangeWithPagination(stub, args, thisClass) { - if (args.length < 2) { - throw new Error('Incorrect number of arguments. Expecting 2'); - } - const startKey = args[0]; - const endKey = args[1]; - - const pageSize = parseInt(args[2], 10); - const bookmark = args[3]; - - const { iterator, metadata } = await stub.getStateByRangeWithPagination( - startKey, - endKey, - pageSize, - bookmark - ); - const getAllResults = thisClass['getAllResults']; - const results = await getAllResults(iterator, false); - // use RecordsCount and Bookmark to keep consistency with the go sample - results.ResponseMetadata = { - RecordsCount: metadata.fetched_records_count, - Bookmark: metadata.bookmark - }; - return Buffer.from(JSON.stringify(results)); - } - - // ========================================================================================= - // getQueryResultForQueryStringWithPagination executes the passed in query string with - // pagination info. Result set is built and returned as a byte array containing the JSON results. - // ========================================================================================= - async queryMarblesWithPagination(stub, args, thisClass) { - // 0 - // "queryString" - if (args.length < 3) { - return shim.Error('Incorrect number of arguments. Expecting 3'); - } - - const queryString = args[0]; - const pageSize = parseInt(args[2], 10); - const bookmark = args[3]; - - const { iterator, metadata } = await stub.GetQueryResultWithPagination( - queryString, - pageSize, - bookmark - ); - const getAllResults = thisClass['getAllResults']; - const results = await getAllResults(iterator, false); - // use RecordsCount and Bookmark to keep consistency with the go sample - results.ResponseMetadata = { - RecordsCount: metadata.fetched_records_count, - Bookmark: metadata.bookmark - }; - - return Buffer.from(JSON.stringify(results)); - } -}; - -shim.start(new Chaincode()); diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/package.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/package.json deleted file mode 100644 index 46582a329..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02/node/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "marbles", - "version": "1.0.0", - "description": "marbles chaincode implemented in node.js", - "engines": { - "node": ">=8.4.0", - "npm": ">=5.3.0" - }, - "scripts": { - "start": "node marbles_chaincode.js" - }, - "engine-strict": true, - "license": "Apache-2.0", - "dependencies": { - "fabric-shim": "~1.4.0" - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/collections_config.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/collections_config.json deleted file mode 100644 index 2ab44c034..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/collections_config.json +++ /dev/null @@ -1,18 +0,0 @@ -[ - { - "name": "collectionMarbles", - "policy": "OR('Org1MSP.member', 'Org2MSP.member')", - "requiredPeerCount": 0, - "maxPeerCount": 3, - "blockToLive": 1000000, - "memberOnlyRead": true - }, - { - "name": "collectionMarblePrivateDetails", - "policy": "OR('Org1MSP.member')", - "requiredPeerCount": 0, - "maxPeerCount": 3, - "blockToLive": 3, - "memberOnlyRead": true - } -] diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/go/META-INF/statedb/couchdb/collections/collectionMarbles/indexes/indexOwner.json b/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/go/META-INF/statedb/couchdb/collections/collectionMarbles/indexes/indexOwner.json deleted file mode 100644 index 0cf070623..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/go/META-INF/statedb/couchdb/collections/collectionMarbles/indexes/indexOwner.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "index": { "fields": ["docType", "owner"] }, - "ddoc": "indexOwnerDoc", - "name": "indexOwner", - "type": "json" -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/go/marbles_chaincode_private.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/go/marbles_chaincode_private.go deleted file mode 100644 index 055d6f36d..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/marbles02_private/go/marbles_chaincode_private.go +++ /dev/null @@ -1,650 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -// ====CHAINCODE EXECUTION SAMPLES (CLI) ================== - -// ==== Invoke marbles, pass private data as base64 encoded bytes in transient map ==== -// -// export MARBLE=$(echo -n "{\"name\":\"marble1\",\"color\":\"blue\",\"size\":35,\"owner\":\"tom\",\"price\":99}" | base64) -// peer chaincode invoke -C mychannel -n marblesp -c '{"Args":["initMarble"]}' --transient "{\"marble\":\"$MARBLE\"}" -// -// export MARBLE=$(echo -n "{\"name\":\"marble2\",\"color\":\"red\",\"size\":50,\"owner\":\"tom\",\"price\":102}" | base64) -// peer chaincode invoke -C mychannel -n marblesp -c '{"Args":["initMarble"]}' --transient "{\"marble\":\"$MARBLE\"}" -// -// export MARBLE=$(echo -n "{\"name\":\"marble3\",\"color\":\"blue\",\"size\":70,\"owner\":\"tom\",\"price\":103}" | base64) -// peer chaincode invoke -C mychannel -n marblesp -c '{"Args":["initMarble"]}' --transient "{\"marble\":\"$MARBLE\"}" -// -// export MARBLE_OWNER=$(echo -n "{\"name\":\"marble2\",\"owner\":\"jerry\"}" | base64) -// peer chaincode invoke -C mychannel -n marblesp -c '{"Args":["transferMarble"]}' --transient "{\"marble_owner\":\"$MARBLE_OWNER\"}" -// -// export MARBLE_DELETE=$(echo -n "{\"name\":\"marble1\"}" | base64) -// peer chaincode invoke -C mychannel -n marblesp -c '{"Args":["delete"]}' --transient "{\"marble_delete\":\"$MARBLE_DELETE\"}" - -// ==== Query marbles, since queries are not recorded on chain we don't need to hide private data in transient map ==== -// peer chaincode query -C mychannel -n marblesp -c '{"Args":["readMarble","marble1"]}' -// peer chaincode query -C mychannel -n marblesp -c '{"Args":["readMarblePrivateDetails","marble1"]}' -// peer chaincode query -C mychannel -n marblesp -c '{"Args":["getMarblesByRange","marble1","marble4"]}' -// -// Rich Query (Only supported if CouchDB is used as state database): -// peer chaincode query -C mychannel -n marblesp -c '{"Args":["queryMarblesByOwner","tom"]}' -// peer chaincode query -C mychannel -n marblesp -c '{"Args":["queryMarbles","{\"selector\":{\"owner\":\"tom\"}}"]}' - -// INDEXES TO SUPPORT COUCHDB RICH QUERIES -// -// Indexes in CouchDB are required in order to make JSON queries efficient and are required for -// any JSON query with a sort. As of Hyperledger Fabric 1.1, indexes may be packaged alongside -// chaincode in a META-INF/statedb/couchdb/indexes directory. Or for indexes on private data -// collections, in a META-INF/statedb/couchdb/collections//indexes directory. -// Each index must be defined in its own text file with extension *.json with the index -// definition formatted in JSON following the CouchDB index JSON syntax as documented at: -// http://docs.couchdb.org/en/2.1.1/api/database/find.html#db-index -// -// This marbles02_private example chaincode demonstrates a packaged index which you -// can find in META-INF/statedb/couchdb/collection/collectionMarbles/indexes/indexOwner.json. -// For deployment of chaincode to production environments, it is recommended -// to define any indexes alongside chaincode so that the chaincode and supporting indexes -// are deployed automatically as a unit, once the chaincode has been installed on a peer and -// instantiated on a channel. See Hyperledger Fabric documentation for more details. -// -// If you have access to the your peer's CouchDB state database in a development environment, -// you may want to iteratively test various indexes in support of your chaincode queries. You -// can use the CouchDB Fauxton interface or a command line curl utility to create and update -// indexes. Then once you finalize an index, include the index definition alongside your -// chaincode in the META-INF/statedb/couchdb/indexes directory or -// META-INF/statedb/couchdb/collections//indexes directory, for packaging -// and deployment to managed environments. -// -// In the examples below you can find index definitions that support marbles02_private -// chaincode queries, along with the syntax that you can use in development environments -// to create the indexes in the CouchDB Fauxton interface. -// - -//Example hostname:port configurations to access CouchDB. -// -//To access CouchDB docker container from within another docker container or from vagrant environments: -// http://couchdb:5984/ -// -//Inside couchdb docker container -// http://127.0.0.1:5984/ - -// Index for docType, owner. -// Note that docType and owner fields must be prefixed with the "data" wrapper -// -// Index definition for use with Fauxton interface -// {"index":{"fields":["data.docType","data.owner"]},"ddoc":"indexOwnerDoc", "name":"indexOwner","type":"json"} - -// Index for docType, owner, size (descending order). -// Note that docType, owner and size fields must be prefixed with the "data" wrapper -// -// Index definition for use with Fauxton interface -// {"index":{"fields":[{"data.size":"desc"},{"data.docType":"desc"},{"data.owner":"desc"}]},"ddoc":"indexSizeSortDoc", "name":"indexSizeSortDesc","type":"json"} - -// Rich Query with index design doc and index name specified (Only supported if CouchDB is used as state database): -// peer chaincode query -C mychannel -n marblesp -c '{"Args":["queryMarbles","{\"selector\":{\"docType\":\"marble\",\"owner\":\"tom\"}, \"use_index\":[\"_design/indexOwnerDoc\", \"indexOwner\"]}"]}' - -// Rich Query with index design doc specified only (Only supported if CouchDB is used as state database): -// peer chaincode query -C mychannel -n marblesp -c '{"Args":["queryMarbles","{\"selector\":{\"docType\":{\"$eq\":\"marble\"},\"owner\":{\"$eq\":\"tom\"},\"size\":{\"$gt\":0}},\"fields\":[\"docType\",\"owner\",\"size\"],\"sort\":[{\"size\":\"desc\"}],\"use_index\":\"_design/indexSizeSortDoc\"}"]}' - -package main - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" - - "github.com/hyperledger/fabric/core/chaincode/shim" - pb "github.com/hyperledger/fabric/protos/peer" -) - -// SimpleChaincode example simple Chaincode implementation -type SimpleChaincode struct { -} - -type marble struct { - ObjectType string `json:"docType"` //docType is used to distinguish the various types of objects in state database - Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around - Color string `json:"color"` - Size int `json:"size"` - Owner string `json:"owner"` -} - -type marblePrivateDetails struct { - ObjectType string `json:"docType"` //docType is used to distinguish the various types of objects in state database - Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around - Price int `json:"price"` -} - -// =================================================================================== -// Main -// =================================================================================== -func main() { - err := shim.Start(new(SimpleChaincode)) - if err != nil { - fmt.Printf("Error starting Simple chaincode: %s", err) - } -} - -// Init initializes chaincode -// =========================== -func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { - return shim.Success(nil) -} - -// Invoke - Our entry point for Invocations -// ======================================== -func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response { - function, args := stub.GetFunctionAndParameters() - fmt.Println("invoke is running " + function) - - // Handle different functions - switch function { - case "initMarble": - //create a new marble - return t.initMarble(stub, args) - case "readMarble": - //read a marble - return t.readMarble(stub, args) - case "readMarblePrivateDetails": - //read a marble private details - return t.readMarblePrivateDetails(stub, args) - case "transferMarble": - //change owner of a specific marble - return t.transferMarble(stub, args) - case "delete": - //delete a marble - return t.delete(stub, args) - case "queryMarblesByOwner": - //find marbles for owner X using rich query - return t.queryMarblesByOwner(stub, args) - case "queryMarbles": - //find marbles based on an ad hoc rich query - return t.queryMarbles(stub, args) - case "getMarblesByRange": - //get marbles based on range query - return t.getMarblesByRange(stub, args) - default: - //error - fmt.Println("invoke did not find func: " + function) - return shim.Error("Received unknown function invocation") - } -} - -// ============================================================ -// initMarble - create a new marble, store into chaincode state -// ============================================================ -func (t *SimpleChaincode) initMarble(stub shim.ChaincodeStubInterface, args []string) pb.Response { - var err error - - type marbleTransientInput struct { - Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around - Color string `json:"color"` - Size int `json:"size"` - Owner string `json:"owner"` - Price int `json:"price"` - } - - // ==== Input sanitation ==== - fmt.Println("- start init marble") - - if len(args) != 0 { - return shim.Error("Incorrect number of arguments. Private marble data must be passed in transient map.") - } - - transMap, err := stub.GetTransient() - if err != nil { - return shim.Error("Error getting transient: " + err.Error()) - } - - if _, ok := transMap["marble"]; !ok { - return shim.Error("marble must be a key in the transient map") - } - - if len(transMap["marble"]) == 0 { - return shim.Error("marble value in the transient map must be a non-empty JSON string") - } - - var marbleInput marbleTransientInput - err = json.Unmarshal(transMap["marble"], &marbleInput) - if err != nil { - return shim.Error("Failed to decode JSON of: " + string(transMap["marble"])) - } - - if len(marbleInput.Name) == 0 { - return shim.Error("name field must be a non-empty string") - } - if len(marbleInput.Color) == 0 { - return shim.Error("color field must be a non-empty string") - } - if marbleInput.Size <= 0 { - return shim.Error("size field must be a positive integer") - } - if len(marbleInput.Owner) == 0 { - return shim.Error("owner field must be a non-empty string") - } - if marbleInput.Price <= 0 { - return shim.Error("price field must be a positive integer") - } - - // ==== Check if marble already exists ==== - marbleAsBytes, err := stub.GetPrivateData("collectionMarbles", marbleInput.Name) - if err != nil { - return shim.Error("Failed to get marble: " + err.Error()) - } else if marbleAsBytes != nil { - fmt.Println("This marble already exists: " + marbleInput.Name) - return shim.Error("This marble already exists: " + marbleInput.Name) - } - - // ==== Create marble object, marshal to JSON, and save to state ==== - marble := &marble{ - ObjectType: "marble", - Name: marbleInput.Name, - Color: marbleInput.Color, - Size: marbleInput.Size, - Owner: marbleInput.Owner, - } - marbleJSONasBytes, err := json.Marshal(marble) - if err != nil { - return shim.Error(err.Error()) - } - - // === Save marble to state === - err = stub.PutPrivateData("collectionMarbles", marbleInput.Name, marbleJSONasBytes) - if err != nil { - return shim.Error(err.Error()) - } - - // ==== Create marble private details object with price, marshal to JSON, and save to state ==== - marblePrivateDetails := &marblePrivateDetails{ - ObjectType: "marblePrivateDetails", - Name: marbleInput.Name, - Price: marbleInput.Price, - } - marblePrivateDetailsBytes, err := json.Marshal(marblePrivateDetails) - if err != nil { - return shim.Error(err.Error()) - } - err = stub.PutPrivateData("collectionMarblePrivateDetails", marbleInput.Name, marblePrivateDetailsBytes) - if err != nil { - return shim.Error(err.Error()) - } - - // ==== Index the marble to enable color-based range queries, e.g. return all blue marbles ==== - // An 'index' is a normal key/value entry in state. - // The key is a composite key, with the elements that you want to range query on listed first. - // In our case, the composite key is based on indexName~color~name. - // This will enable very efficient state range queries based on composite keys matching indexName~color~* - indexName := "color~name" - colorNameIndexKey, err := stub.CreateCompositeKey(indexName, []string{marble.Color, marble.Name}) - if err != nil { - return shim.Error(err.Error()) - } - // Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the marble. - // Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value - value := []byte{0x00} - stub.PutPrivateData("collectionMarbles", colorNameIndexKey, value) - - // ==== Marble saved and indexed. Return success ==== - fmt.Println("- end init marble") - return shim.Success(nil) -} - -// =============================================== -// readMarble - read a marble from chaincode state -// =============================================== -func (t *SimpleChaincode) readMarble(stub shim.ChaincodeStubInterface, args []string) pb.Response { - var name, jsonResp string - var err error - - if len(args) != 1 { - return shim.Error("Incorrect number of arguments. Expecting name of the marble to query") - } - - name = args[0] - valAsbytes, err := stub.GetPrivateData("collectionMarbles", name) //get the marble from chaincode state - if err != nil { - jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}" - return shim.Error(jsonResp) - } else if valAsbytes == nil { - jsonResp = "{\"Error\":\"Marble does not exist: " + name + "\"}" - return shim.Error(jsonResp) - } - - return shim.Success(valAsbytes) -} - -// =============================================== -// readMarblereadMarblePrivateDetails - read a marble private details from chaincode state -// =============================================== -func (t *SimpleChaincode) readMarblePrivateDetails(stub shim.ChaincodeStubInterface, args []string) pb.Response { - var name, jsonResp string - var err error - - if len(args) != 1 { - return shim.Error("Incorrect number of arguments. Expecting name of the marble to query") - } - - name = args[0] - valAsbytes, err := stub.GetPrivateData("collectionMarblePrivateDetails", name) //get the marble private details from chaincode state - if err != nil { - jsonResp = "{\"Error\":\"Failed to get private details for " + name + ": " + err.Error() + "\"}" - return shim.Error(jsonResp) - } else if valAsbytes == nil { - jsonResp = "{\"Error\":\"Marble private details does not exist: " + name + "\"}" - return shim.Error(jsonResp) - } - - return shim.Success(valAsbytes) -} - -// ================================================== -// delete - remove a marble key/value pair from state -// ================================================== -func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response { - fmt.Println("- start delete marble") - - type marbleDeleteTransientInput struct { - Name string `json:"name"` - } - - if len(args) != 0 { - return shim.Error("Incorrect number of arguments. Private marble name must be passed in transient map.") - } - - transMap, err := stub.GetTransient() - if err != nil { - return shim.Error("Error getting transient: " + err.Error()) - } - - if _, ok := transMap["marble_delete"]; !ok { - return shim.Error("marble_delete must be a key in the transient map") - } - - if len(transMap["marble_delete"]) == 0 { - return shim.Error("marble_delete value in the transient map must be a non-empty JSON string") - } - - var marbleDeleteInput marbleDeleteTransientInput - err = json.Unmarshal(transMap["marble_delete"], &marbleDeleteInput) - if err != nil { - return shim.Error("Failed to decode JSON of: " + string(transMap["marble_delete"])) - } - - if len(marbleDeleteInput.Name) == 0 { - return shim.Error("name field must be a non-empty string") - } - - // to maintain the color~name index, we need to read the marble first and get its color - valAsbytes, err := stub.GetPrivateData("collectionMarbles", marbleDeleteInput.Name) //get the marble from chaincode state - if err != nil { - return shim.Error("Failed to get state for " + marbleDeleteInput.Name) - } else if valAsbytes == nil { - return shim.Error("Marble does not exist: " + marbleDeleteInput.Name) - } - - var marbleToDelete marble - err = json.Unmarshal([]byte(valAsbytes), &marbleToDelete) - if err != nil { - return shim.Error("Failed to decode JSON of: " + string(valAsbytes)) - } - - // delete the marble from state - err = stub.DelPrivateData("collectionMarbles", marbleDeleteInput.Name) - if err != nil { - return shim.Error("Failed to delete state:" + err.Error()) - } - - // Also delete the marble from the color~name index - indexName := "color~name" - colorNameIndexKey, err := stub.CreateCompositeKey(indexName, []string{marbleToDelete.Color, marbleToDelete.Name}) - if err != nil { - return shim.Error(err.Error()) - } - err = stub.DelPrivateData("collectionMarbles", colorNameIndexKey) - if err != nil { - return shim.Error("Failed to delete state:" + err.Error()) - } - - // Finally, delete private details of marble - err = stub.DelPrivateData("collectionMarblePrivateDetails", marbleDeleteInput.Name) - if err != nil { - return shim.Error(err.Error()) - } - - return shim.Success(nil) -} - -// =========================================================== -// transfer a marble by setting a new owner name on the marble -// =========================================================== -func (t *SimpleChaincode) transferMarble(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - fmt.Println("- start transfer marble") - - type marbleTransferTransientInput struct { - Name string `json:"name"` - Owner string `json:"owner"` - } - - if len(args) != 0 { - return shim.Error("Incorrect number of arguments. Private marble data must be passed in transient map.") - } - - transMap, err := stub.GetTransient() - if err != nil { - return shim.Error("Error getting transient: " + err.Error()) - } - - if _, ok := transMap["marble_owner"]; !ok { - return shim.Error("marble_owner must be a key in the transient map") - } - - if len(transMap["marble_owner"]) == 0 { - return shim.Error("marble_owner value in the transient map must be a non-empty JSON string") - } - - var marbleTransferInput marbleTransferTransientInput - err = json.Unmarshal(transMap["marble_owner"], &marbleTransferInput) - if err != nil { - return shim.Error("Failed to decode JSON of: " + string(transMap["marble_owner"])) - } - - if len(marbleTransferInput.Name) == 0 { - return shim.Error("name field must be a non-empty string") - } - if len(marbleTransferInput.Owner) == 0 { - return shim.Error("owner field must be a non-empty string") - } - - marbleAsBytes, err := stub.GetPrivateData("collectionMarbles", marbleTransferInput.Name) - if err != nil { - return shim.Error("Failed to get marble:" + err.Error()) - } else if marbleAsBytes == nil { - return shim.Error("Marble does not exist: " + marbleTransferInput.Name) - } - - marbleToTransfer := marble{} - err = json.Unmarshal(marbleAsBytes, &marbleToTransfer) //unmarshal it aka JSON.parse() - if err != nil { - return shim.Error(err.Error()) - } - marbleToTransfer.Owner = marbleTransferInput.Owner //change the owner - - marbleJSONasBytes, _ := json.Marshal(marbleToTransfer) - err = stub.PutPrivateData("collectionMarbles", marbleToTransfer.Name, marbleJSONasBytes) //rewrite the marble - if err != nil { - return shim.Error(err.Error()) - } - - fmt.Println("- end transferMarble (success)") - return shim.Success(nil) -} - -// =========================================================================================== -// getMarblesByRange performs a range query based on the start and end keys provided. - -// Read-only function results are not typically submitted to ordering. If the read-only -// results are submitted to ordering, or if the query is used in an update transaction -// and submitted to ordering, then the committing peers will re-execute to guarantee that -// result sets are stable between endorsement time and commit time. The transaction is -// invalidated by the committing peers if the result set has changed between endorsement -// time and commit time. -// Therefore, range queries are a safe option for performing update transactions based on query results. -// =========================================================================================== -func (t *SimpleChaincode) getMarblesByRange(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - if len(args) < 2 { - return shim.Error("Incorrect number of arguments. Expecting 2") - } - - startKey := args[0] - endKey := args[1] - - resultsIterator, err := stub.GetPrivateDataByRange("collectionMarbles", startKey, endKey) - if err != nil { - return shim.Error(err.Error()) - } - defer resultsIterator.Close() - - // buffer is a JSON array containing QueryResults - var buffer bytes.Buffer - buffer.WriteString("[") - - bArrayMemberAlreadyWritten := false - for resultsIterator.HasNext() { - queryResponse, err := resultsIterator.Next() - if err != nil { - return shim.Error(err.Error()) - } - // Add a comma before array members, suppress it for the first array member - if bArrayMemberAlreadyWritten == true { - buffer.WriteString(",") - } - buffer.WriteString("{\"Key\":") - buffer.WriteString("\"") - buffer.WriteString(queryResponse.Key) - buffer.WriteString("\"") - - buffer.WriteString(", \"Record\":") - // Record is a JSON object, so we write as-is - buffer.WriteString(string(queryResponse.Value)) - buffer.WriteString("}") - bArrayMemberAlreadyWritten = true - } - buffer.WriteString("]") - - fmt.Printf("- getMarblesByRange queryResult:\n%s\n", buffer.String()) - - return shim.Success(buffer.Bytes()) -} - -// =======Rich queries ========================================================================= -// Two examples of rich queries are provided below (parameterized query and ad hoc query). -// Rich queries pass a query string to the state database. -// Rich queries are only supported by state database implementations -// that support rich query (e.g. CouchDB). -// The query string is in the syntax of the underlying state database. -// With rich queries there is no guarantee that the result set hasn't changed between -// endorsement time and commit time, aka 'phantom reads'. -// Therefore, rich queries should not be used in update transactions, unless the -// application handles the possibility of result set changes between endorsement and commit time. -// Rich queries can be used for point-in-time queries against a peer. -// ============================================================================================ - -// ===== Example: Parameterized rich query ================================================= -// queryMarblesByOwner queries for marbles based on a passed in owner. -// This is an example of a parameterized query where the query logic is baked into the chaincode, -// and accepting a single query parameter (owner). -// Only available on state databases that support rich query (e.g. CouchDB) -// ========================================================================================= -func (t *SimpleChaincode) queryMarblesByOwner(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - // 0 - // "bob" - if len(args) < 1 { - return shim.Error("Incorrect number of arguments. Expecting 1") - } - - owner := strings.ToLower(args[0]) - - queryString := fmt.Sprintf("{\"selector\":{\"docType\":\"marble\",\"owner\":\"%s\"}}", owner) - - queryResults, err := getQueryResultForQueryString(stub, queryString) - if err != nil { - return shim.Error(err.Error()) - } - return shim.Success(queryResults) -} - -// ===== Example: Ad hoc rich query ======================================================== -// queryMarbles uses a query string to perform a query for marbles. -// Query string matching state database syntax is passed in and executed as is. -// Supports ad hoc queries that can be defined at runtime by the client. -// If this is not desired, follow the queryMarblesForOwner example for parameterized queries. -// Only available on state databases that support rich query (e.g. CouchDB) -// ========================================================================================= -func (t *SimpleChaincode) queryMarbles(stub shim.ChaincodeStubInterface, args []string) pb.Response { - - // 0 - // "queryString" - if len(args) < 1 { - return shim.Error("Incorrect number of arguments. Expecting 1") - } - - queryString := args[0] - - queryResults, err := getQueryResultForQueryString(stub, queryString) - if err != nil { - return shim.Error(err.Error()) - } - return shim.Success(queryResults) -} - -// ========================================================================================= -// getQueryResultForQueryString executes the passed in query string. -// Result set is built and returned as a byte array containing the JSON results. -// ========================================================================================= -func getQueryResultForQueryString(stub shim.ChaincodeStubInterface, queryString string) ([]byte, error) { - - fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString) - - resultsIterator, err := stub.GetPrivateDataQueryResult("collectionMarbles", queryString) - if err != nil { - return nil, err - } - defer resultsIterator.Close() - - // buffer is a JSON array containing QueryRecords - var buffer bytes.Buffer - buffer.WriteString("[") - - bArrayMemberAlreadyWritten := false - for resultsIterator.HasNext() { - queryResponse, err := resultsIterator.Next() - if err != nil { - return nil, err - } - // Add a comma before array members, suppress it for the first array member - if bArrayMemberAlreadyWritten == true { - buffer.WriteString(",") - } - buffer.WriteString("{\"Key\":") - buffer.WriteString("\"") - buffer.WriteString(queryResponse.Key) - buffer.WriteString("\"") - - buffer.WriteString(", \"Record\":") - // Record is a JSON object, so we write as-is - buffer.WriteString(string(queryResponse.Value)) - buffer.WriteString("}") - bArrayMemberAlreadyWritten = true - } - buffer.WriteString("]") - - fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String()) - - return buffer.Bytes(), nil -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/chaincode/sacc/sacc.go b/app/platform/fabric/e2e-test/fabric-samples/chaincode/sacc/sacc.go deleted file mode 100644 index 4bfb165b5..000000000 --- a/app/platform/fabric/e2e-test/fabric-samples/chaincode/sacc/sacc.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright IBM Corp All Rights Reserved - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package main - -import ( - "fmt" - - "github.com/hyperledger/fabric/core/chaincode/shim" - "github.com/hyperledger/fabric/protos/peer" -) - -// SimpleAsset implements a simple chaincode to manage an asset -type SimpleAsset struct { -} - -// Init is called during chaincode instantiation to initialize any -// data. Note that chaincode upgrade also calls this function to reset -// or to migrate data. -func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response { - // Get the args from the transaction proposal - args := stub.GetStringArgs() - if len(args) != 2 { - return shim.Error("Incorrect arguments. Expecting a key and a value") - } - - // Set up any variables or assets here by calling stub.PutState() - - // We store the key and the value on the ledger - err := stub.PutState(args[0], []byte(args[1])) - if err != nil { - return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0])) - } - return shim.Success(nil) -} - -// Invoke is called per transaction on the chaincode. Each transaction is -// either a 'get' or a 'set' on the asset created by Init function. The Set -// method may create a new asset by specifying a new key-value pair. -func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response { - // Extract the function and args from the transaction proposal - fn, args := stub.GetFunctionAndParameters() - - var result string - var err error - if fn == "set" { - result, err = set(stub, args) - } else { // assume 'get' even if fn is nil - result, err = get(stub, args) - } - if err != nil { - return shim.Error(err.Error()) - } - - // Return the result as success payload - return shim.Success([]byte(result)) -} - -// Set stores the asset (both key and value) on the ledger. If the key exists, -// it will override the value with the new one -func set(stub shim.ChaincodeStubInterface, args []string) (string, error) { - if len(args) != 2 { - return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value") - } - - err := stub.PutState(args[0], []byte(args[1])) - if err != nil { - return "", fmt.Errorf("Failed to set asset: %s", args[0]) - } - return args[1], nil -} - -// Get returns the value of the specified asset key -func get(stub shim.ChaincodeStubInterface, args []string) (string, error) { - if len(args) != 1 { - return "", fmt.Errorf("Incorrect arguments. Expecting a key") - } - - value, err := stub.GetState(args[0]) - if err != nil { - return "", fmt.Errorf("Failed to get asset: %s with error: %s", args[0], err) - } - if value == nil { - return "", fmt.Errorf("Asset not found: %s", args[0]) - } - return string(value), nil -} - -// main function starts up the chaincode in the container during instantiate -func main() { - if err := shim.Start(new(SimpleAsset)); err != nil { - fmt.Printf("Error starting SimpleAsset chaincode: %s", err) - } -} diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/.env b/app/platform/fabric/e2e-test/fabric-samples/first-network/.env index bbac17e2a..431f11469 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/.env +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/.env @@ -1,5 +1,3 @@ -# -# SPDX-License-Identifier: Apache-2.0 -# COMPOSE_PROJECT_NAME=net IMAGE_TAG=latest +SYS_CHANNEL=byfn-sys-channel diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/.gitignore b/app/platform/fabric/e2e-test/fabric-samples/first-network/.gitignore index 5b6d4fd66..4888c4c23 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/.gitignore +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/.gitignore @@ -1,9 +1,8 @@ -# -# SPDX-License-Identifier: Apache-2.0 -# /channel-artifacts/*.tx /channel-artifacts/*.block /crypto-config/* /docker-compose-e2e.yaml /ledgers /ledgers-backup +/channel-artifacts/*.json +/org3-artifacts/crypto-config/* \ No newline at end of file diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/README.md b/app/platform/fabric/e2e-test/fabric-samples/first-network/README.md index 8fb5d5cc0..6d9e2543a 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/README.md +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/README.md @@ -1,6 +1,3 @@ - - - ## Build Your First Network (BYFN) The directions for using this are documented in the Hyperledger Fabric diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/base/docker-compose-base.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/base/docker-compose-base.yaml index be6767daa..4c55ff961 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/base/docker-compose-base.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/base/docker-compose-base.yaml @@ -9,28 +9,14 @@ services: orderer.example.com: container_name: orderer.example.com - image: hyperledger/fabric-orderer:$IMAGE_TAG - environment: - - FABRIC_LOGGING_SPEC=INFO - - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0 - - ORDERER_GENERAL_GENESISMETHOD=file - - ORDERER_GENERAL_GENESISFILE=/var/hyperledger/orderer/orderer.genesis.block - - ORDERER_GENERAL_LOCALMSPID=OrdererMSP - - ORDERER_GENERAL_LOCALMSPDIR=/var/hyperledger/orderer/msp - # enabled TLS - - ORDERER_GENERAL_TLS_ENABLED=true - - ORDERER_GENERAL_TLS_PRIVATEKEY=/var/hyperledger/orderer/tls/server.key - - ORDERER_GENERAL_TLS_CERTIFICATE=/var/hyperledger/orderer/tls/server.crt - - ORDERER_GENERAL_TLS_ROOTCAS=[/var/hyperledger/orderer/tls/ca.crt] - - ORDERER_KAFKA_TOPIC_REPLICATIONFACTOR=1 - - ORDERER_KAFKA_VERBOSE=true - working_dir: /opt/gopath/src/github.com/hyperledger/fabric - command: orderer + extends: + file: peer-base.yaml + service: orderer-base volumes: - - ./../../../configs/${CORE_PEER_NETWORKID}/channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block - - ./../../../configs/${CORE_PEER_NETWORKID}/ordererOrganizations/example.com/orderers/orderer.example.com/msp:/var/hyperledger/orderer/msp - - ./../../../configs/${CORE_PEER_NETWORKID}/ordererOrganizations/example.com/orderers/orderer.example.com/tls/:/var/hyperledger/orderer/tls - - orderer.example.com:/var/hyperledger/production/orderer + - ../channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block + - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp:/var/hyperledger/orderer/msp + - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/:/var/hyperledger/orderer/tls + - orderer.example.com:/var/hyperledger/production/orderer ports: - 7050:7050 @@ -42,17 +28,19 @@ services: environment: - CORE_PEER_ID=peer0.org1.example.com - CORE_PEER_ADDRESS=peer0.org1.example.com:7051 - - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org1.example.com:7051 + - CORE_PEER_LISTENADDRESS=0.0.0.0:7051 + - CORE_PEER_CHAINCODEADDRESS=peer0.org1.example.com:7052 + - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:7052 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org1.example.com:8051 - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051 - CORE_PEER_LOCALMSPID=Org1MSP volumes: - /var/run/:/host/var/run/ - - ./../../../configs/${CORE_PEER_NETWORKID}/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp:/etc/hyperledger/fabric/msp - - ./../../../configs/${CORE_PEER_NETWORKID}/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls:/etc/hyperledger/fabric/tls + - ../crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp:/etc/hyperledger/fabric/msp + - ../crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls:/etc/hyperledger/fabric/tls - peer0.org1.example.com:/var/hyperledger/production ports: - 7051:7051 - - 7053:7053 peer1.org1.example.com: container_name: peer1.org1.example.com @@ -61,19 +49,21 @@ services: service: peer-base environment: - CORE_PEER_ID=peer1.org1.example.com - - CORE_PEER_ADDRESS=peer1.org1.example.com:7051 - - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org1.example.com:7051 + - CORE_PEER_ADDRESS=peer1.org1.example.com:8051 + - CORE_PEER_LISTENADDRESS=0.0.0.0:8051 + - CORE_PEER_CHAINCODEADDRESS=peer1.org1.example.com:8052 + - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:8052 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org1.example.com:8051 - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org1.example.com:7051 - CORE_PEER_LOCALMSPID=Org1MSP volumes: - /var/run/:/host/var/run/ - - ./../../../configs/${CORE_PEER_NETWORKID}/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/msp:/etc/hyperledger/fabric/msp - - ./../../../configs/${CORE_PEER_NETWORKID}/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls:/etc/hyperledger/fabric/tls + - ../crypto-config/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/msp:/etc/hyperledger/fabric/msp + - ../crypto-config/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls:/etc/hyperledger/fabric/tls - peer1.org1.example.com:/var/hyperledger/production ports: - - 8051:7051 - - 8053:7053 + - 8051:8051 peer0.org2.example.com: container_name: peer0.org2.example.com @@ -82,18 +72,20 @@ services: service: peer-base environment: - CORE_PEER_ID=peer0.org2.example.com - - CORE_PEER_ADDRESS=peer0.org2.example.com:7051 - - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org2.example.com:7051 - - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org2.example.com:7051 + - CORE_PEER_ADDRESS=peer0.org2.example.com:9051 + - CORE_PEER_LISTENADDRESS=0.0.0.0:9051 + - CORE_PEER_CHAINCODEADDRESS=peer0.org2.example.com:9052 + - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:9052 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org2.example.com:9051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org2.example.com:10051 - CORE_PEER_LOCALMSPID=Org2MSP volumes: - /var/run/:/host/var/run/ - - ./../../../configs/${CORE_PEER_NETWORKID}/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/msp:/etc/hyperledger/fabric/msp - - ./../../../configs/${CORE_PEER_NETWORKID}/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls:/etc/hyperledger/fabric/tls + - ../crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/msp:/etc/hyperledger/fabric/msp + - ../crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls:/etc/hyperledger/fabric/tls - peer0.org2.example.com:/var/hyperledger/production ports: - - 9051:7051 - - 9053:7053 + - 9051:9051 peer1.org2.example.com: container_name: peer1.org2.example.com @@ -102,15 +94,17 @@ services: service: peer-base environment: - CORE_PEER_ID=peer1.org2.example.com - - CORE_PEER_ADDRESS=peer1.org2.example.com:7051 - - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org2.example.com:7051 - - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org2.example.com:7051 + - CORE_PEER_ADDRESS=peer1.org2.example.com:10051 + - CORE_PEER_LISTENADDRESS=0.0.0.0:10051 + - CORE_PEER_CHAINCODEADDRESS=peer1.org2.example.com:10052 + - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:10052 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org2.example.com:10051 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org2.example.com:9051 - CORE_PEER_LOCALMSPID=Org2MSP volumes: - /var/run/:/host/var/run/ - - ./../../../configs/${CORE_PEER_NETWORKID}/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/msp:/etc/hyperledger/fabric/msp - - ./../../../configs/${CORE_PEER_NETWORKID}/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/tls:/etc/hyperledger/fabric/tls + - ../crypto-config/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/msp:/etc/hyperledger/fabric/msp + - ../crypto-config/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/tls:/etc/hyperledger/fabric/tls - peer1.org2.example.com:/var/hyperledger/production ports: - - 10051:7051 - - 10053:7053 + - 10051:10051 diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/base/peer-base.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/base/peer-base.yaml index 97a98d8a7..6f6dd3e12 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/base/peer-base.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/base/peer-base.yaml @@ -13,7 +13,7 @@ services: # the following setting starts chaincode containers on the same # bridge network as the peers # https://docs.docker.com/compose/networking/ - - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_behave + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_byfn - FABRIC_LOGGING_SPEC=INFO #- FABRIC_LOGGING_SPEC=DEBUG - CORE_PEER_TLS_ENABLED=true @@ -25,3 +25,26 @@ services: - CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/fabric/tls/ca.crt working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer command: peer node start + + orderer-base: + image: hyperledger/fabric-orderer:$IMAGE_TAG + environment: + - FABRIC_LOGGING_SPEC=INFO + - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0 + - ORDERER_GENERAL_GENESISMETHOD=file + - ORDERER_GENERAL_GENESISFILE=/var/hyperledger/orderer/orderer.genesis.block + - ORDERER_GENERAL_LOCALMSPID=OrdererMSP + - ORDERER_GENERAL_LOCALMSPDIR=/var/hyperledger/orderer/msp + # enabled TLS + - ORDERER_GENERAL_TLS_ENABLED=true + - ORDERER_GENERAL_TLS_PRIVATEKEY=/var/hyperledger/orderer/tls/server.key + - ORDERER_GENERAL_TLS_CERTIFICATE=/var/hyperledger/orderer/tls/server.crt + - ORDERER_GENERAL_TLS_ROOTCAS=[/var/hyperledger/orderer/tls/ca.crt] + - ORDERER_KAFKA_TOPIC_REPLICATIONFACTOR=1 + - ORDERER_KAFKA_VERBOSE=true + - ORDERER_GENERAL_CLUSTER_CLIENTCERTIFICATE=/var/hyperledger/orderer/tls/server.crt + - ORDERER_GENERAL_CLUSTER_CLIENTPRIVATEKEY=/var/hyperledger/orderer/tls/server.key + - ORDERER_GENERAL_CLUSTER_ROOTCAS=[/var/hyperledger/orderer/tls/ca.crt] + working_dir: /opt/gopath/src/github.com/hyperledger/fabric + command: orderer + diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/byfn.sh b/app/platform/fabric/e2e-test/fabric-samples/first-network/byfn.sh index 2a105a425..f7e6d8070 100755 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/byfn.sh +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/byfn.sh @@ -35,7 +35,7 @@ export VERBOSE=false # Print the usage message function printHelp() { echo "Usage: " - echo " byfn.sh [-c ] [-t ] [-d ] [-f ] [-s ] [-l ] [-o ] [-i ] [-v]" + echo " byfn.sh [-c ] [-t ] [-d ] [-f ] [-s ] [-l ] [-o ] [-i ] [-a] [-n] [-v]" echo " - one of 'up', 'down', 'restart', 'generate' or 'upgrade'" echo " - 'up' - bring up the network with docker-compose up" echo " - 'down' - clear the network with docker-compose down" @@ -48,8 +48,10 @@ function printHelp() { echo " -f - specify which docker-compose file use (defaults to docker-compose-cli.yaml)" echo " -s - the database backend to use: goleveldb (default) or couchdb" echo " -l - the chaincode language: golang (default) or node" - echo " -o - the consensus-type of the ordering service: solo (default) or kafka" + echo " -o - the consensus-type of the ordering service: solo (default), kafka, or etcdraft" echo " -i - the tag to be used to launch the network (defaults to \"latest\")" + echo " -a - launch certificate authorities (no certificate authorities are launched by default)" + echo " -n - do not deploy chaincode (abstore chaincode is deployed by default)" echo " -v - verbose mode" echo " byfn.sh -h (print this message)" echo @@ -71,8 +73,7 @@ function printHelp() { # Ask user for confirmation to proceed function askProceed() { - # read -p "Continue? [Y/n] " ans - ans=y + read -p "Continue? [Y/n] " ans case "$ans" in y | Y | "") echo "proceeding ..." @@ -157,19 +158,22 @@ function networkUp() { replacePrivateKey generateChannelArtifacts fi + COMPOSE_FILES="-f ${COMPOSE_FILE}" + if [ "${CERTIFICATE_AUTHORITIES}" == "true" ]; then + COMPOSE_FILES="${COMPOSE_FILES} -f ${COMPOSE_FILE_CA}" + export BYFN_CA1_PRIVATE_KEY=$(cd crypto-config/peerOrganizations/org1.example.com/ca && ls *_sk) + export BYFN_CA2_PRIVATE_KEY=$(cd crypto-config/peerOrganizations/org2.example.com/ca && ls *_sk) + fi + if [ "${CONSENSUS_TYPE}" == "kafka" ]; then + COMPOSE_FILES="${COMPOSE_FILES} -f ${COMPOSE_FILE_KAFKA}" + elif [ "${CONSENSUS_TYPE}" == "etcdraft" ]; then + COMPOSE_FILES="${COMPOSE_FILES} -f ${COMPOSE_FILE_RAFT2}" + fi if [ "${IF_COUCHDB}" == "couchdb" ]; then - if [ "$CONSENSUS_TYPE" == "kafka" ]; then - IMAGE_TAG=$IMAGETAG docker-compose -f $COMPOSE_FILE -f $COMPOSE_FILE_KAFKA -f $COMPOSE_FILE_COUCH up -d 2>&1 - else - IMAGE_TAG=$IMAGETAG docker-compose -f $COMPOSE_FILE -f $COMPOSE_FILE_COUCH up -d 2>&1 - fi - else - if [ "$CONSENSUS_TYPE" == "kafka" ]; then - IMAGE_TAG=$IMAGETAG docker-compose -f $COMPOSE_FILE -f $COMPOSE_FILE_KAFKA up -d 2>&1 - else - IMAGE_TAG=$IMAGETAG docker-compose -f $COMPOSE_FILE up -d 2>&1 - fi + COMPOSE_FILES="${COMPOSE_FILES} -f ${COMPOSE_FILE_COUCH}" fi + IMAGE_TAG=$IMAGETAG docker-compose ${COMPOSE_FILES} up -d 2>&1 + docker ps -a if [ $? -ne 0 ]; then echo "ERROR !!!! Unable to start network" exit 1 @@ -177,12 +181,18 @@ function networkUp() { if [ "$CONSENSUS_TYPE" == "kafka" ]; then sleep 1 - echo "Sleeping 10s to allow kafka cluster to complete booting" + echo "Sleeping 10s to allow $CONSENSUS_TYPE cluster to complete booting" sleep 9 fi + if [ "$CONSENSUS_TYPE" == "etcdraft" ]; then + sleep 1 + echo "Sleeping 15s to allow $CONSENSUS_TYPE cluster to complete booting" + sleep 14 + fi + # now run the end to end script - docker exec cli scripts/script.sh $CHANNEL_NAME $CLI_DELAY $LANGUAGE $CLI_TIMEOUT $VERBOSE + docker exec cli scripts/script.sh $CHANNEL_NAME $CLI_DELAY $LANGUAGE $CLI_TIMEOUT $VERBOSE $NO_CHAINCODE if [ $? -ne 0 ]; then echo "ERROR !!!! Test failed" exit 1 @@ -206,18 +216,19 @@ function upgradeNetwork() { mkdir -p $LEDGERS_BACKUP export IMAGE_TAG=$IMAGETAG + COMPOSE_FILES="-f ${COMPOSE_FILE}" + if [ "${CERTIFICATE_AUTHORITIES}" == "true" ]; then + COMPOSE_FILES="${COMPOSE_FILES} -f ${COMPOSE_FILE_CA}" + export BYFN_CA1_PRIVATE_KEY=$(cd crypto-config/peerOrganizations/org1.example.com/ca && ls *_sk) + export BYFN_CA2_PRIVATE_KEY=$(cd crypto-config/peerOrganizations/org2.example.com/ca && ls *_sk) + fi + if [ "${CONSENSUS_TYPE}" == "kafka" ]; then + COMPOSE_FILES="${COMPOSE_FILES} -f ${COMPOSE_FILE_KAFKA}" + elif [ "${CONSENSUS_TYPE}" == "etcdraft" ]; then + COMPOSE_FILES="${COMPOSE_FILES} -f ${COMPOSE_FILE_RAFT2}" + fi if [ "${IF_COUCHDB}" == "couchdb" ]; then - if [ "$CONSENSUS_TYPE" == "kafka" ]; then - COMPOSE_FILES="-f $COMPOSE_FILE -f $COMPOSE_FILE_KAFKA -f $COMPOSE_FILE_COUCH" - else - COMPOSE_FILES="-f $COMPOSE_FILE -f $COMPOSE_FILE_COUCH" - fi - else - if [ "$CONSENSUS_TYPE" == "kafka" ]; then - COMPOSE_FILES="-f $COMPOSE_FILE -f $COMPOSE_FILE_KAFKA" - else - COMPOSE_FILES="-f $COMPOSE_FILE" - fi + COMPOSE_FILES="${COMPOSE_FILES} -f ${COMPOSE_FILE_COUCH}" fi # removing the cli container @@ -264,7 +275,7 @@ function upgradeNetwork() { function networkDown() { # stop org3 containers also in addition to org1 and org2, in case we were running sample to add org3 # stop kafka and zookeeper containers in case we're running with kafka consensus-type - docker-compose -f $COMPOSE_FILE -f $COMPOSE_FILE_COUCH -f $COMPOSE_FILE_KAFKA -f $COMPOSE_FILE_ORG3 down --volumes --remove-orphans + docker-compose -f $COMPOSE_FILE -f $COMPOSE_FILE_COUCH -f $COMPOSE_FILE_KAFKA -f $COMPOSE_FILE_RAFT2 -f $COMPOSE_FILE_CA -f $COMPOSE_FILE_ORG3 down --volumes --remove-orphans # Don't remove the generated artifacts -- note, the ledgers are always removed if [ "$MODE" != "restart" ]; then @@ -301,11 +312,11 @@ function replacePrivateKey() { # The next steps will replace the template's contents with the # actual values of the private key file names for the two CAs. CURRENT_DIR=$PWD - cd peerOrganizations/org1.example.com/ca/ + cd crypto-config/peerOrganizations/org1.example.com/ca/ PRIV_KEY=$(ls *_sk) cd "$CURRENT_DIR" sed $OPTS "s/CA1_PRIVATE_KEY/${PRIV_KEY}/g" docker-compose-e2e.yaml - cd peerOrganizations/org2.example.com/ca/ + cd crypto-config/peerOrganizations/org2.example.com/ca/ PRIV_KEY=$(ls *_sk) cd "$CURRENT_DIR" sed $OPTS "s/CA2_PRIVATE_KEY/${PRIV_KEY}/g" docker-compose-e2e.yaml @@ -348,7 +359,7 @@ function generateCerts() { rm -Rf crypto-config fi set -x - cryptogen generate --config=./crypto-config.yaml --output . + cryptogen generate --config=./crypto-config.yaml res=$? set +x if [ $res -ne 0 ]; then @@ -411,9 +422,11 @@ function generateChannelArtifacts() { echo "CONSENSUS_TYPE="$CONSENSUS_TYPE set -x if [ "$CONSENSUS_TYPE" == "solo" ]; then - configtxgen -profile TwoOrgsOrdererGenesis -channelID byfn-sys-channel -outputBlock ./channel-artifacts/genesis.block + configtxgen -profile TwoOrgsOrdererGenesis -channelID $SYS_CHANNEL -outputBlock ./channel-artifacts/genesis.block elif [ "$CONSENSUS_TYPE" == "kafka" ]; then - configtxgen -profile SampleDevModeKafka -channelID byfn-sys-channel -outputBlock ./channel-artifacts/genesis.block + configtxgen -profile SampleDevModeKafka -channelID $SYS_CHANNEL -outputBlock ./channel-artifacts/genesis.block + elif [ "$CONSENSUS_TYPE" == "etcdraft" ]; then + configtxgen -profile SampleMultiNodeEtcdRaft -channelID $SYS_CHANNEL -outputBlock ./channel-artifacts/genesis.block else set +x echo "unrecognized CONSESUS_TYPE='$CONSENSUS_TYPE'. exiting" @@ -475,6 +488,8 @@ OS_ARCH=$(echo "$(uname -s | tr '[:upper:]' '[:lower:]' | sed 's/mingw64_nt.*/wi CLI_TIMEOUT=10 # default for delay between commands CLI_DELAY=3 +# system channel name defaults to "byfn-sys-channel" +SYS_CHANNEL="byfn-sys-channel" # channel name defaults to "mychannel" CHANNEL_NAME="mychannel" # use this as the default docker-compose yaml definition @@ -485,6 +500,10 @@ COMPOSE_FILE_COUCH=docker-compose-couch.yaml COMPOSE_FILE_ORG3=docker-compose-org3.yaml # kafka and zookeeper compose file COMPOSE_FILE_KAFKA=docker-compose-kafka.yaml +# two additional etcd/raft orderers +COMPOSE_FILE_RAFT2=docker-compose-etcdraft2.yaml +# certificate authorities compose file +COMPOSE_FILE_CA=docker-compose-ca.yaml # # use golang as the default language for chaincode LANGUAGE=golang @@ -514,7 +533,7 @@ else exit 1 fi -while getopts "h?c:t:d:f:s:l:i:o:v" opt; do +while getopts "h?c:t:d:f:s:l:i:o:anv" opt; do case "$opt" in h | \?) printHelp @@ -541,9 +560,15 @@ while getopts "h?c:t:d:f:s:l:i:o:v" opt; do i) IMAGETAG=$(go env GOARCH)"-"$OPTARG ;; - o) + o) CONSENSUS_TYPE=$OPTARG ;; + a) + CERTIFICATE_AUTHORITIES=true + ;; + n) + NO_CHAINCODE=true + ;; v) VERBOSE=true ;; @@ -560,7 +585,7 @@ else echo "${EXPMODE} for channel '${CHANNEL_NAME}' with CLI timeout of '${CLI_TIMEOUT}' seconds and CLI delay of '${CLI_DELAY}' seconds" fi # ask for confirmation to proceed -askProceed +yes | askProceed #Create the network using docker compose if [ "${MODE}" == "up" ]; then diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/configtx.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/configtx.yaml index 5ee89d7d6..ad8d746b3 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/configtx.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/configtx.yaml @@ -25,7 +25,7 @@ Organizations: ID: OrdererMSP # MSPDir is the filesystem path which contains the MSP configuration - MSPDir: ordererOrganizations/example.com/msp + MSPDir: crypto-config/ordererOrganizations/example.com/msp # Policies defines the set of policies at this level of the config tree # For organization policies, their canonical path is usually @@ -49,7 +49,7 @@ Organizations: # ID to load the MSP definition as ID: Org1MSP - MSPDir: peerOrganizations/org1.example.com/msp + MSPDir: crypto-config/peerOrganizations/org1.example.com/msp # Policies defines the set of policies at this level of the config tree # For organization policies, their canonical path is usually @@ -81,7 +81,7 @@ Organizations: # ID to load the MSP definition as ID: Org2MSP - MSPDir: peerOrganizations/org2.example.com/msp + MSPDir: crypto-config/peerOrganizations/org2.example.com/msp # Policies defines the set of policies at this level of the config tree # For organization policies, their canonical path is usually @@ -102,7 +102,7 @@ Organizations: # for cross org gossip communication. Note, this value is only # encoded in the genesis block in the Application section context - Host: peer0.org2.example.com - Port: 7051 + Port: 9051 ################################################################################ # @@ -128,32 +128,35 @@ Capabilities: # supported by both. # Set the value of the capability to true to require it. Channel: &ChannelCapabilities - # V1.3 for Channel is a catchall flag for behavior which has been - # determined to be desired for all orderers and peers running at the v1.3.x + # V1.4.2 for Channel is a catchall flag for behavior which has been + # determined to be desired for all orderers and peers running at the v1.4.2 # level, but which would be incompatible with orderers and peers from # prior releases. - # Prior to enabling V1.3 channel capabilities, ensure that all - # orderers and peers on a channel are at v1.3.0 or later. - V1_3: true + # Prior to enabling V1.4.2 channel capabilities, ensure that all + # orderers and peers on a channel are at v1.4.2 or later. + V1_4_2: true # Orderer capabilities apply only to the orderers, and may be safely # used with prior release peers. # Set the value of the capability to true to require it. Orderer: &OrdererCapabilities - # V1.1 for Orderer is a catchall flag for behavior which has been - # determined to be desired for all orderers running at the v1.1.x + # V1.4.2 for Orderer is a catchall flag for behavior which has been + # determined to be desired for all orderers running at the v1.4.2 # level, but which would be incompatible with orderers from prior releases. - # Prior to enabling V1.1 orderer capabilities, ensure that all - # orderers on a channel are at v1.1.0 or later. - V1_1: true + # Prior to enabling V1.4.2 orderer capabilities, ensure that all + # orderers on a channel are at v1.4.2 or later. + V1_4_2: true # Application capabilities apply only to the peer network, and may be safely # used with prior release orderers. # Set the value of the capability to true to require it. Application: &ApplicationCapabilities + # V1.4.2 for Application enables the new non-backwards compatible + # features and fixes of fabric v1.4.2. + V1_4_2: true # V1.3 for Application enables the new non-backwards compatible # features and fixes of fabric v1.3. - V1_3: true + V1_3: false # V1.2 for Application enables the new non-backwards compatible # features and fixes of fabric v1.2 (note, this need not be set if # later version capabilities are set) @@ -314,6 +317,7 @@ Profiles: - *Org2 TwoOrgsChannel: Consortium: SampleConsortium + <<: *ChannelDefaults Application: <<: *ApplicationDefaults Organizations: @@ -345,4 +349,54 @@ Profiles: SampleConsortium: Organizations: - *Org1 - - *Org2 \ No newline at end of file + - *Org2 + + SampleMultiNodeEtcdRaft: + <<: *ChannelDefaults + Capabilities: + <<: *ChannelCapabilities + Orderer: + <<: *OrdererDefaults + OrdererType: etcdraft + EtcdRaft: + Consenters: + - Host: orderer.example.com + Port: 7050 + ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt + ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt + - Host: orderer2.example.com + Port: 7050 + ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/server.crt + ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/server.crt + - Host: orderer3.example.com + Port: 7050 + ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/server.crt + ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/server.crt + - Host: orderer4.example.com + Port: 7050 + ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/server.crt + ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/server.crt + - Host: orderer5.example.com + Port: 7050 + ClientTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer5.example.com/tls/server.crt + ServerTLSCert: crypto-config/ordererOrganizations/example.com/orderers/orderer5.example.com/tls/server.crt + Addresses: + - orderer.example.com:7050 + - orderer2.example.com:7050 + - orderer3.example.com:7050 + - orderer4.example.com:7050 + - orderer5.example.com:7050 + + Organizations: + - *OrdererOrg + Capabilities: + <<: *OrdererCapabilities + Application: + <<: *ApplicationDefaults + Organizations: + - <<: *OrdererOrg + Consortiums: + SampleConsortium: + Organizations: + - *Org1 + - *Org2 diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org1.json b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org1.json new file mode 100644 index 000000000..172c9f4e8 --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org1.json @@ -0,0 +1,53 @@ +{ + "name": "first-network-org1", + "version": "1.0.0", + "client": { + "organization": "Org1", + "connection": { + "timeout": { + "peer": { + "endorser": "300" + } + } + } + }, + "organizations": { + "Org1": { + "mspid": "Org1MSP", + "peers": ["peer0.org1.example.com", "peer1.org1.example.com"], + "certificateAuthorities": ["ca.org1.example.com"] + } + }, + "peers": { + "peer0.org1.example.com": { + "url": "grpcs://localhost:7051", + "tlsCACerts": { + "path": "crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem" + }, + "grpcOptions": { + "ssl-target-name-override": "peer0.org1.example.com" + } + }, + "peer1.org1.example.com": { + "url": "grpcs://localhost:8051", + "tlsCACerts": { + "path": "crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem" + }, + "grpcOptions": { + "ssl-target-name-override": "peer1.org1.example.com" + } + } + }, + "certificateAuthorities": { + "ca.org1.example.com": { + "url": "https://localhost:7054", + "caName": "ca-org1", + "tlsCACerts": { + "path": "crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem" + }, + "httpOptions": { + "verify": false + } + } + } +} diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org1.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org1.yaml new file mode 100644 index 000000000..daa9ad642 --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org1.yaml @@ -0,0 +1,38 @@ +--- +name: first-network-org1 +version: 1.0.0 +client: + organization: Org1 + connection: + timeout: + peer: + endorser: '300' +organizations: + Org1: + mspid: Org1MSP + peers: + - peer0.org1.example.com + - peer1.org1.example.com + certificateAuthorities: + - ca.org1.example.com +peers: + peer0.org1.example.com: + url: grpcs://localhost:7051 + tlsCACerts: + path: crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem + grpcOptions: + ssl-target-name-override: peer0.org1.example.com + peer1.org1.example.com: + url: grpcs://localhost:8051 + tlsCACerts: + path: crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem + grpcOptions: + ssl-target-name-override: peer1.org1.example.com +certificateAuthorities: + ca.org1.example.com: + url: https://localhost:7054 + caName: ca-org1 + tlsCACerts: + path: crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem + httpOptions: + verify: false diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org2.json b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org2.json new file mode 100644 index 000000000..aa4c4acae --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org2.json @@ -0,0 +1,53 @@ +{ + "name": "first-network-org2", + "version": "1.0.0", + "client": { + "organization": "Org2", + "connection": { + "timeout": { + "peer": { + "endorser": "300" + } + } + } + }, + "organizations": { + "Org2": { + "mspid": "Org2MSP", + "peers": ["peer0.org2.example.com", "peer1.org2.example.com"], + "certificateAuthorities": ["ca.org2.example.com"] + } + }, + "peers": { + "peer0.org2.example.com": { + "url": "grpcs://localhost:9051", + "tlsCACerts": { + "path": "crypto-config/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem" + }, + "grpcOptions": { + "ssl-target-name-override": "peer0.org2.example.com" + } + }, + "peer1.org2.example.com": { + "url": "grpcs://localhost:10051", + "tlsCACerts": { + "path": "crypto-config/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem" + }, + "grpcOptions": { + "ssl-target-name-override": "peer1.org2.example.com" + } + } + }, + "certificateAuthorities": { + "ca.org2.example.com": { + "url": "https://localhost:8054", + "caName": "ca-org2", + "tlsCACerts": { + "path": "crypto-config/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem" + }, + "httpOptions": { + "verify": false + } + } + } +} diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org2.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org2.yaml new file mode 100644 index 000000000..b21c879fd --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org2.yaml @@ -0,0 +1,38 @@ +--- +name: first-network-org2 +version: 1.0.0 +client: + organization: Org2 + connection: + timeout: + peer: + endorser: '300' +organizations: + Org2: + mspid: Org2MSP + peers: + - peer0.org2.example.com + - peer1.org2.example.com + certificateAuthorities: + - ca.org2.example.com +peers: + peer0.org2.example.com: + url: grpcs://localhost:9051 + tlsCACerts: + path: crypto-config/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem + grpcOptions: + ssl-target-name-override: peer0.org2.example.com + peer1.org2.example.com: + url: grpcs://localhost:10051 + tlsCACerts: + path: crypto-config/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem + grpcOptions: + ssl-target-name-override: peer1.org2.example.com +certificateAuthorities: + ca.org2.example.com: + url: https://localhost:8054 + caName: ca-org2 + tlsCACerts: + path: crypto-config/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem + httpOptions: + verify: false diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org3.json b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org3.json new file mode 100644 index 000000000..1ad25381b --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org3.json @@ -0,0 +1,40 @@ +{ + "name": "first-network-org3", + "version": "1.0.0", + "client": { + "organization": "Org3", + "connection": { + "timeout": { + "peer": { + "endorser": "300" + } + } + } + }, + "organizations": { + "Org3": { + "mspid": "Org3MSP", + "peers": ["peer0.org3.example.com", "peer1.org3.example.com"] + } + }, + "peers": { + "peer0.org3.example.com": { + "url": "grpcs://localhost:11051", + "tlsCACerts": { + "path": "org3-artifacts/crypto-config/peerOrganizations/org3.example.com/tlsca/tlsca.org3.example.com-cert.pem" + }, + "grpcOptions": { + "ssl-target-name-override": "peer0.org3.example.com" + } + }, + "peer1.org3.example.com": { + "url": "grpcs://localhost:12051", + "tlsCACerts": { + "path": "org3-artifacts/crypto-config/peerOrganizations/org3.example.com/tlsca/tlsca.org3.example.com-cert.pem" + }, + "grpcOptions": { + "ssl-target-name-override": "peer1.org3.example.com" + } + } + } +} diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org3.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org3.yaml new file mode 100644 index 000000000..ebdc983d3 --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/connection-org3.yaml @@ -0,0 +1,28 @@ +--- +name: first-network-org3 +version: 1.0.0 +client: + organization: Org3 + connection: + timeout: + peer: + endorser: '300' +organizations: + Org3: + mspid: Org3MSP + peers: + - peer0.org3.example.com + - peer1.org3.example.com +peers: + peer0.org3.example.com: + url: grpcs://localhost:11051 + tlsCACerts: + path: org3-artifacts/crypto-config/peerOrganizations/org3.example.com/tlsca/tlsca.org3.example.com-cert.pem + grpcOptions: + ssl-target-name-override: peer0.org3.example.com + peer1.org3.example.com: + url: grpcs://localhost:12051 + tlsCACerts: + path: org3-artifacts/crypto-config/peerOrganizations/org3.example.com/tlsca/tlsca.org3.example.com-cert.pem + grpcOptions: + ssl-target-name-override: peer1.org3.example.com diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/crypto-config.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/crypto-config.yaml index 73b444d8c..a38299b59 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/crypto-config.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/crypto-config.yaml @@ -17,6 +17,11 @@ OrdererOrgs: # --------------------------------------------------------------------------- Specs: - Hostname: orderer + - Hostname: orderer2 + - Hostname: orderer3 + - Hostname: orderer4 + - Hostname: orderer5 + # --------------------------------------------------------------------------- # "PeerOrgs" - Definition of organizations managing peer nodes # --------------------------------------------------------------------------- diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-ca.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-ca.yaml new file mode 100644 index 000000000..7f019606e --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-ca.yaml @@ -0,0 +1,46 @@ +# Copyright IBM Corp. All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# + +version: '2' + +networks: + byfn: + +services: + ca0: + image: hyperledger/fabric-ca:$IMAGE_TAG + environment: + - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server + - FABRIC_CA_SERVER_CA_NAME=ca-org1 + - FABRIC_CA_SERVER_TLS_ENABLED=true + - FABRIC_CA_SERVER_TLS_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org1.example.com-cert.pem + - FABRIC_CA_SERVER_TLS_KEYFILE=/etc/hyperledger/fabric-ca-server-config/${BYFN_CA1_PRIVATE_KEY} + - FABRIC_CA_SERVER_PORT=7054 + ports: + - "7054:7054" + command: sh -c 'fabric-ca-server start --ca.certfile /etc/hyperledger/fabric-ca-server-config/ca.org1.example.com-cert.pem --ca.keyfile /etc/hyperledger/fabric-ca-server-config/${BYFN_CA1_PRIVATE_KEY} -b admin:adminpw -d' + volumes: + - ./crypto-config/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config + container_name: ca_peerOrg1 + networks: + - byfn + + ca1: + image: hyperledger/fabric-ca:$IMAGE_TAG + environment: + - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server + - FABRIC_CA_SERVER_CA_NAME=ca-org2 + - FABRIC_CA_SERVER_TLS_ENABLED=true + - FABRIC_CA_SERVER_TLS_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org2.example.com-cert.pem + - FABRIC_CA_SERVER_TLS_KEYFILE=/etc/hyperledger/fabric-ca-server-config/${BYFN_CA2_PRIVATE_KEY} + - FABRIC_CA_SERVER_PORT=8054 + ports: + - "8054:8054" + command: sh -c 'fabric-ca-server start --ca.certfile /etc/hyperledger/fabric-ca-server-config/ca.org2.example.com-cert.pem --ca.keyfile /etc/hyperledger/fabric-ca-server-config/${BYFN_CA2_PRIVATE_KEY} -b admin:adminpw -d' + volumes: + - ./crypto-config/peerOrganizations/org2.example.com/ca/:/etc/hyperledger/fabric-ca-server-config + container_name: ca_peerOrg2 + networks: + - byfn \ No newline at end of file diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-cli.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-cli.yaml index d40bb6ab2..a7aa3f4b9 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-cli.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-cli.yaml @@ -13,7 +13,7 @@ volumes: peer1.org2.example.com: networks: - behave: + byfn: services: @@ -23,9 +23,7 @@ services: service: orderer.example.com container_name: orderer.example.com networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} + - byfn peer0.org1.example.com: container_name: peer0.org1.example.com @@ -33,9 +31,7 @@ services: file: base/docker-compose-base.yaml service: peer0.org1.example.com networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} + - byfn peer1.org1.example.com: container_name: peer1.org1.example.com @@ -43,9 +39,7 @@ services: file: base/docker-compose-base.yaml service: peer1.org1.example.com networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} + - byfn peer0.org2.example.com: container_name: peer0.org2.example.com @@ -53,9 +47,7 @@ services: file: base/docker-compose-base.yaml service: peer0.org2.example.com networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} + - byfn peer1.org2.example.com: container_name: peer1.org2.example.com @@ -63,9 +55,7 @@ services: file: base/docker-compose-base.yaml service: peer1.org2.example.com networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} + - byfn cli: container_name: cli @@ -73,6 +63,7 @@ services: tty: true stdin_open: true environment: + - SYS_CHANNEL=$SYS_CHANNEL - GOPATH=/opt/gopath - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock #- FABRIC_LOGGING_SPEC=DEBUG @@ -86,14 +77,13 @@ services: - CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer - command: scripts/script.sh - # command: bash + command: /bin/bash volumes: - /var/run/:/host/var/run/ - ./../chaincode/:/opt/gopath/src/github.com/chaincode - - ./../../configs/${CORE_PEER_NETWORKID}:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ + - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ - ./scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/ - - ./../../configs/${CORE_PEER_NETWORKID}/channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts + - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts depends_on: - orderer.example.com - peer0.org1.example.com @@ -101,6 +91,4 @@ services: - peer0.org2.example.com - peer1.org2.example.com networks: - behave: - aliases: - - ${CORE_PEER_NETWORKID} + - byfn diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-etcdraft2.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-etcdraft2.yaml new file mode 100644 index 000000000..1e525ee2b --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-etcdraft2.yaml @@ -0,0 +1,77 @@ +# Copyright IBM Corp. All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# + +version: '2' + +volumes: + orderer2.example.com: + orderer3.example.com: + orderer4.example.com: + orderer5.example.com: + +networks: + byfn: + +services: + + orderer2.example.com: + extends: + file: base/peer-base.yaml + service: orderer-base + container_name: orderer2.example.com + networks: + - byfn + volumes: + - ./channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block + - ./crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com/msp:/var/hyperledger/orderer/msp + - ./crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/:/var/hyperledger/orderer/tls + - orderer2.example.com:/var/hyperledger/production/orderer + ports: + - 8050:7050 + + orderer3.example.com: + extends: + file: base/peer-base.yaml + service: orderer-base + container_name: orderer3.example.com + networks: + - byfn + volumes: + - ./channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block + - ./crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/msp:/var/hyperledger/orderer/msp + - ./crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/:/var/hyperledger/orderer/tls + - orderer3.example.com:/var/hyperledger/production/orderer + ports: + - 9050:7050 + + orderer4.example.com: + extends: + file: base/peer-base.yaml + service: orderer-base + container_name: orderer4.example.com + networks: + - byfn + volumes: + - ./channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block + - ./crypto-config/ordererOrganizations/example.com/orderers/orderer4.example.com/msp:/var/hyperledger/orderer/msp + - ./crypto-config/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/:/var/hyperledger/orderer/tls + - orderer4.example.com:/var/hyperledger/production/orderer + ports: + - 10050:7050 + + orderer5.example.com: + extends: + file: base/peer-base.yaml + service: orderer-base + container_name: orderer5.example.com + networks: + - byfn + volumes: + - ./channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block + - ./crypto-config/ordererOrganizations/example.com/orderers/orderer5.example.com/msp:/var/hyperledger/orderer/msp + - ./crypto-config/ordererOrganizations/example.com/orderers/orderer5.example.com/tls/:/var/hyperledger/orderer/tls + - orderer5.example.com:/var/hyperledger/production/orderer + ports: + - 11050:7050 diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-explorer.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-explorer.yaml new file mode 100644 index 000000000..4883e77da --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-explorer.yaml @@ -0,0 +1,109 @@ +# Copyright IBM Corp. All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# + +version: '2' + +volumes: + orderer.example.com: + peer0.org1.example.com: + peer1.org1.example.com: + peer0.org2.example.com: + peer1.org2.example.com: + +networks: + behave: + byfn: + +services: + + orderer.example.com: + extends: + file: ./docker-compose-cli.yaml + service: orderer.example.com + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + peer0.org1.example.com: + extends: + file: ./docker-compose-cli.yaml + service: peer0.org1.example.com + environment: + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_behave + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + peer1.org1.example.com: + extends: + file: ./docker-compose-cli.yaml + service: peer1.org1.example.com + environment: + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_behave + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + peer0.org2.example.com: + extends: + file: ./docker-compose-cli.yaml + service: peer0.org2.example.com + environment: + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_behave + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + peer1.org2.example.com: + extends: + file: ./docker-compose-cli.yaml + service: peer1.org2.example.com + environment: + - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_behave + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} + + cli: + container_name: cli + image: hyperledger/fabric-tools:$IMAGE_TAG + tty: true + stdin_open: true + environment: + - SYS_CHANNEL=$SYS_CHANNEL + - GOPATH=/opt/gopath + - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock + #- FABRIC_LOGGING_SPEC=DEBUG + - FABRIC_LOGGING_SPEC=INFO + - CORE_PEER_ID=cli + - CORE_PEER_ADDRESS=peer0.org1.example.com:7051 + - CORE_PEER_LOCALMSPID=Org1MSP + - CORE_PEER_TLS_ENABLED=true + - CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt + - CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.key + - CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt + - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp + working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer + volumes: + - /var/run/:/host/var/run/ + - ./../chaincode/:/opt/gopath/src/github.com/chaincode + - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ + - ./scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/ + - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts + depends_on: + - orderer.example.com + - peer0.org1.example.com + - peer1.org1.example.com + - peer0.org2.example.com + - peer1.org2.example.com + networks: + behave: + aliases: + - ${CORE_PEER_NETWORKID} diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-org3.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-org3.yaml index 8da911b1f..2ee41e3c6 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-org3.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/docker-compose-org3.yaml @@ -21,8 +21,12 @@ services: service: peer-base environment: - CORE_PEER_ID=peer0.org3.example.com - - CORE_PEER_ADDRESS=peer0.org3.example.com:7051 - - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org3.example.com:7051 + - CORE_PEER_ADDRESS=peer0.org3.example.com:11051 + - CORE_PEER_LISTENADDRESS=0.0.0.0:11051 + - CORE_PEER_CHAINCODEADDRESS=peer0.org3.example.com:11052 + - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:11052 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org3.example.com:12051 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org3.example.com:11051 - CORE_PEER_LOCALMSPID=Org3MSP volumes: - /var/run/:/host/var/run/ @@ -30,8 +34,7 @@ services: - ./org3-artifacts/crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/tls:/etc/hyperledger/fabric/tls - peer0.org3.example.com:/var/hyperledger/production ports: - - 11051:7051 - - 11053:7053 + - 11051:11051 networks: - byfn @@ -42,9 +45,12 @@ services: service: peer-base environment: - CORE_PEER_ID=peer1.org3.example.com - - CORE_PEER_ADDRESS=peer1.org3.example.com:7051 - - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org3.example.com:7051 - - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org3.example.com:7051 + - CORE_PEER_ADDRESS=peer1.org3.example.com:12051 + - CORE_PEER_LISTENADDRESS=0.0.0.0:12051 + - CORE_PEER_CHAINCODEADDRESS=peer1.org3.example.com:12052 + - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:12052 + - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org3.example.com:11051 + - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org3.example.com:12051 - CORE_PEER_LOCALMSPID=Org3MSP volumes: - /var/run/:/host/var/run/ @@ -52,8 +58,7 @@ services: - ./org3-artifacts/crypto-config/peerOrganizations/org3.example.com/peers/peer1.org3.example.com/tls:/etc/hyperledger/fabric/tls - peer1.org3.example.com:/var/hyperledger/production ports: - - 12051:7051 - - 12053:7053 + - 12051:12051 networks: - byfn @@ -69,7 +74,7 @@ services: - FABRIC_LOGGING_SPEC=INFO #- FABRIC_LOGGING_SPEC=DEBUG - CORE_PEER_ID=Org3cli - - CORE_PEER_ADDRESS=peer0.org3.example.com:7051 + - CORE_PEER_ADDRESS=peer0.org3.example.com:11051 - CORE_PEER_LOCALMSPID=Org3MSP - CORE_PEER_TLS_ENABLED=true - CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/tls/server.crt diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/eyfn.sh b/app/platform/fabric/e2e-test/fabric-samples/first-network/eyfn.sh index c915189b3..ad2c37693 100755 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/eyfn.sh +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/eyfn.sh @@ -136,7 +136,7 @@ function networkUp () { # Tear down running network function networkDown () { - docker-compose -f $COMPOSE_FILE -f $COMPOSE_FILE_KAFKA -f $COMPOSE_FILE_ORG3 -f $COMPOSE_FILE_COUCH down --volumes --remove-orphans + docker-compose -f $COMPOSE_FILE -f $COMPOSE_FILE_KAFKA -f $COMPOSE_FILE_RAFT2 -f $COMPOSE_FILE_ORG3 -f $COMPOSE_FILE_COUCH down --volumes --remove-orphans # Don't remove containers, images, etc if restarting if [ "$MODE" != "restart" ]; then #Cleanup the chaincode containers @@ -247,6 +247,8 @@ COMPOSE_FILE_ORG3=docker-compose-org3.yaml COMPOSE_FILE_COUCH_ORG3=docker-compose-couch-org3.yaml # kafka and zookeeper compose file COMPOSE_FILE_KAFKA=docker-compose-kafka.yaml +# two additional etcd/raft orderers +COMPOSE_FILE_RAFT2=docker-compose-etcdraft2.yaml # use golang as the default language for chaincode LANGUAGE=golang # default image tag diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/org3-artifacts/configtx.yaml b/app/platform/fabric/e2e-test/fabric-samples/first-network/org3-artifacts/configtx.yaml index e1205455c..ab3c81a7a 100644 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/org3-artifacts/configtx.yaml +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/org3-artifacts/configtx.yaml @@ -28,4 +28,4 @@ Organizations: # for cross org gossip communication. Note, this value is only # encoded in the genesis block in the Application section context - Host: peer0.org3.example.com - Port: 7051 + Port: 11051 diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/capabilities.json b/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/capabilities.json new file mode 100644 index 000000000..8cc10954a --- /dev/null +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/capabilities.json @@ -0,0 +1,9 @@ +{ + "mod_policy": "Admins", + "value": { + "capabilities": { + "V1_4_2": {} + } + }, + "version": "0" +} diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/script.sh b/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/script.sh index 386e80154..04bdea5f9 100755 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/script.sh +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/script.sh @@ -1,9 +1,5 @@ #!/bin/bash -# -# SPDX-License-Identifier: Apache-2.0 -# - echo echo " ____ _____ _ ____ _____ " echo "/ ___| |_ _| / \ | _ \ |_ _|" @@ -18,11 +14,13 @@ DELAY="$2" LANGUAGE="$3" TIMEOUT="$4" VERBOSE="$5" +NO_CHAINCODE="$6" : ${CHANNEL_NAME:="mychannel"} : ${DELAY:="3"} : ${LANGUAGE:="golang"} : ${TIMEOUT:="10"} : ${VERBOSE:="false"} +: ${NO_CHAINCODE:="false"} LANGUAGE=`echo "$LANGUAGE" | tr [:upper:] [:lower:]` COUNTER=1 MAX_RETRY=10 @@ -86,31 +84,35 @@ updateAnchorPeers 0 1 echo "Updating anchor peers for org2..." updateAnchorPeers 0 2 -## Install chaincode on peer0.org1 and peer0.org2 -echo "Installing chaincode on peer0.org1..." -installChaincode 0 1 -echo "Install chaincode on peer0.org2..." -installChaincode 0 2 - -# Instantiate chaincode on peer0.org2 -echo "Instantiating chaincode on peer0.org2..." -instantiateChaincode 0 2 - -# Query chaincode on peer0.org1 -echo "Querying chaincode on peer0.org1..." -chaincodeQuery 0 1 100 - -# Invoke chaincode on peer0.org1 and peer0.org2 -echo "Sending invoke transaction on peer0.org1 peer0.org2..." -chaincodeInvoke 0 1 0 2 - -## Install chaincode on peer1.org2 -echo "Installing chaincode on peer1.org2..." -installChaincode 1 2 - -# Query on chaincode on peer1.org2, check if the result is 90 -echo "Querying chaincode on peer1.org2..." -chaincodeQuery 1 2 90 +if [ "${NO_CHAINCODE}" != "true" ]; then + + ## Install chaincode on peer0.org1 and peer0.org2 + echo "Installing chaincode on peer0.org1..." + installChaincode 0 1 + echo "Install chaincode on peer0.org2..." + installChaincode 0 2 + + # Instantiate chaincode on peer0.org2 + echo "Instantiating chaincode on peer0.org2..." + instantiateChaincode 0 2 + + # Query chaincode on peer0.org1 + echo "Querying chaincode on peer0.org1..." + chaincodeQuery 0 1 100 + + # Invoke chaincode on peer0.org1 and peer0.org2 + echo "Sending invoke transaction on peer0.org1 peer0.org2..." + chaincodeInvoke 0 1 0 2 + + ## Install chaincode on peer1.org2 + echo "Installing chaincode on peer1.org2..." + installChaincode 1 2 + + # Query on chaincode on peer1.org2, check if the result is 90 + echo "Querying chaincode on peer1.org2..." + chaincodeQuery 1 2 90 + +fi echo echo "========= All GOOD, BYFN execution completed =========== " diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/upgrade_to_v14.sh b/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/upgrade_to_v14.sh index c61823ca4..f46217e0a 100755 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/upgrade_to_v14.sh +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/upgrade_to_v14.sh @@ -1,9 +1,5 @@ #!/bin/bash -# -# SPDX-License-Identifier: Apache-2.0 -# - echo echo " ____ _____ _ ____ _____ " echo "/ ___| |_ _| / \ | _ \ |_ _|" @@ -26,17 +22,117 @@ VERBOSE="$5" LANGUAGE=$(echo "$LANGUAGE" | tr [:upper:] [:lower:]) COUNTER=1 MAX_RETRY=5 +SYS_CHANNEL=$SYS_CHANNEL CC_SRC_PATH="github.com/chaincode/chaincode_example02/go/" if [ "$LANGUAGE" = "node" ]; then CC_SRC_PATH="/opt/gopath/src/github.com/chaincode/chaincode_example02/node/" fi +echo "System channel name : "$SYS_CHANNEL echo "Channel name : "$CHANNEL_NAME # import utils . scripts/utils.sh +# addCapabilityToChannel +# This function pulls the current channel config, modifies it with capabilities +# for the specified group, computes the config update, signs, and submits it. +addCapabilityToChannel() { + CH_NAME=$1 + GROUP=$2 + + setOrdererGlobals + + # Get the current channel config, decode and write it to config.json + fetchChannelConfig $CH_NAME config.json + + # Modify the correct section of the config based on capabilities group + if [ $GROUP == "orderer" ]; then + jq -s '.[0] * {"channel_group":{"groups":{"Orderer": {"values": {"Capabilities": .[1]}}}}}' config.json ./scripts/capabilities.json > modified_config.json + elif [ $GROUP == "channel" ]; then + jq -s '.[0] * {"channel_group":{"values": {"Capabilities": .[1]}}}' config.json ./scripts/capabilities.json > modified_config.json + elif [ $GROUP == "application" ]; then + jq -s '.[0] * {"channel_group":{"groups":{"Application": {"values": {"Capabilities": .[1]}}}}}' config.json ./scripts/capabilities.json > modified_config.json + fi + + # Create a config updated for this channel based on the differences between config.json and modified_config.json + # write the output to config_update_in_envelope.pb + createConfigUpdate "$CH_NAME" config.json modified_config.json config_update_in_envelope.pb + + # Sign, and set the correct identity for submission. + if [ $CH_NAME != $SYS_CHANNEL ] ; then + if [ $GROUP == "orderer" ]; then + # Modifying the orderer group requires only the Orderer admin to sign. + # Prepare to sign the update as the OrdererOrg.Admin + setOrdererGlobals + elif [ $GROUP == "channel" ]; then + # Modifying the channel group requires a majority of application admins and the orderer admin to sign. + # Sign with PeerOrg1.Admin + signConfigtxAsPeerOrg 1 config_update_in_envelope.pb + # Sign with PeerOrg2.Admin + signConfigtxAsPeerOrg 2 config_update_in_envelope.pb + # Prepare to sign the update as the OrdererOrg.Admin + setOrdererGlobals + elif [ $GROUP == "application" ]; then + # Modifying the application group requires a majority of application admins to sign. + # Sign with PeerOrg1.Admin + signConfigtxAsPeerOrg 1 config_update_in_envelope.pb + # Prepare to sign the update as the PeerOrg2.Admin + setGlobals 0 2 + fi + else + # For the orderer system channel, only the orderer admin needs sign + # which will be attached during the update + setOrdererGlobals + fi + + if [ -z "$CORE_PEER_TLS_ENABLED" -o "$CORE_PEER_TLS_ENABLED" = "false" ]; then + set -x + peer channel update -f config_update_in_envelope.pb -c $CH_NAME -o orderer.example.com:7050 --cafile $ORDERER_CA + res=$? + set +x + else + set -x + peer channel update -f config_update_in_envelope.pb -c $CH_NAME -o orderer.example.com:7050 --tls true --cafile $ORDERER_CA + res=$? + set +x + fi + verifyResult $res "Config update for \"$GROUP\" on \"$CH_NAME\" failed" + echo "===================== Config update for \"$GROUP\" on \"$CH_NAME\" is completed ===================== " + +} + +sleep $DELAY + +#Config update for /Channel on $SYS_CHANNEL +echo "Config update for /Channel on \"$SYS_CHANNEL\"" +addCapabilityToChannel $SYS_CHANNEL channel + +sleep $DELAY + +#Config update for /Channel/Orderer on $SYS_CHANNEL +echo "Config update for /Channel/Orderer on \"$SYS_CHANNEL\"" +addCapabilityToChannel $SYS_CHANNEL orderer + +sleep $DELAY + +#Config update for /Channel on $CHANNEL_NAME +echo "Config update for /Channel on \"$CHANNEL_NAME\"" +addCapabilityToChannel $CHANNEL_NAME channel + +sleep $DELAY + +#Config update for /Channel/Orderer +echo "Config update for /Channel/Orderer on \"$CHANNEL_NAME\"" +addCapabilityToChannel $CHANNEL_NAME orderer + +sleep $DELAY + +#Config update for /Channel/Application +echo "Config update for /Channel/Application on \"$CHANNEL_NAME\"" +addCapabilityToChannel $CHANNEL_NAME application + sleep $DELAY #Query on chaincode on Peer0/Org1 diff --git a/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/utils.sh b/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/utils.sh index 3b3820f1e..a6c533235 100755 --- a/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/utils.sh +++ b/app/platform/fabric/e2e-test/fabric-samples/first-network/scripts/utils.sh @@ -38,16 +38,16 @@ setGlobals() { if [ $PEER -eq 0 ]; then CORE_PEER_ADDRESS=peer0.org1.example.com:7051 else - CORE_PEER_ADDRESS=peer1.org1.example.com:7051 + CORE_PEER_ADDRESS=peer1.org1.example.com:8051 fi elif [ $ORG -eq 2 ]; then CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=$PEER0_ORG2_CA CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp if [ $PEER -eq 0 ]; then - CORE_PEER_ADDRESS=peer0.org2.example.com:7051 + CORE_PEER_ADDRESS=peer0.org2.example.com:9051 else - CORE_PEER_ADDRESS=peer1.org2.example.com:7051 + CORE_PEER_ADDRESS=peer1.org2.example.com:10051 fi elif [ $ORG -eq 3 ]; then @@ -55,9 +55,9 @@ setGlobals() { CORE_PEER_TLS_ROOTCERT_FILE=$PEER0_ORG3_CA CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org3.example.com/users/Admin@org3.example.com/msp if [ $PEER -eq 0 ]; then - CORE_PEER_ADDRESS=peer0.org3.example.com:7051 + CORE_PEER_ADDRESS=peer0.org3.example.com:11051 else - CORE_PEER_ADDRESS=peer1.org3.example.com:7051 + CORE_PEER_ADDRESS=peer1.org3.example.com:12051 fi else echo "================== ERROR !!! ORG Unknown ==================" @@ -277,9 +277,10 @@ parsePeerConnectionParameters() { PEER_CONN_PARMS="" PEERS="" while [ "$#" -gt 0 ]; do + setGlobals $1 $2 PEER="peer$1.org$2" PEERS="$PEERS $PEER" - PEER_CONN_PARMS="$PEER_CONN_PARMS --peerAddresses $PEER.example.com:7051" + PEER_CONN_PARMS="$PEER_CONN_PARMS --peerAddresses $CORE_PEER_ADDRESS" if [ -z "$CORE_PEER_TLS_ENABLED" -o "$CORE_PEER_TLS_ENABLED" = "true" ]; then TLSINFO=$(eval echo "--tlsRootCertFiles \$PEER$1_ORG$2_CA") PEER_CONN_PARMS="$PEER_CONN_PARMS $TLSINFO" diff --git a/app/platform/fabric/e2e-test/steps/explorer_impl.py b/app/platform/fabric/e2e-test/steps/explorer_impl.py index 3b69ac623..042cb3e9e 100644 --- a/app/platform/fabric/e2e-test/steps/explorer_impl.py +++ b/app/platform/fabric/e2e-test/steps/explorer_impl.py @@ -36,44 +36,63 @@ def start_explorer_impl(context): # context.compose_containers = context.composition.collectServiceNames() @given(u'I start first-network') -def start_firstnetwork_impl(context): +@given(u'I start first-network orderer network of type {consensus_type}') +def start_firstnetwork_impl(context, consensus_type="solo"): curpath = os.path.realpath('.') - composeFiles = ["%s/fabric-samples/first-network/docker-compose-cli.yaml" % (curpath)] + composeFiles = ["%s/fabric-samples/first-network/docker-compose-explorer.yaml" % (curpath)] config_util.makeProjectConfigDir(context) shutil.copyfile("{0}/fabric-samples/first-network/crypto-config.yaml".format(curpath), "{0}/configs/{1}/crypto-config.yaml".format(curpath, context.projectName)) shutil.copyfile("{0}/fabric-samples/first-network/configtx.yaml".format(curpath), "{0}/configs/{1}/configtx.yaml".format(curpath, context.projectName)) os.mkdir("{0}/configs/{1}/channel-artifacts".format(curpath, context.projectName)) - # config_util.buildCryptoFile(context, 2, 2, numOrderers, 2, ouEnable=ouEnabled) - generateCryptoArtifacts(context, "mychannel") - # config_util.generateCrypto(context, "./configs/{0}/crypto.yaml".format(context.projectName)) - # config_util.generateConfig(context, "byfn-sys-channel", "TwoOrgsChannel", "TwoOrgsOrdererGenesis") - # shutil.copyfile("{0}/configs/{1}/byfn-sys-channel.tx".format(curpath, context.projectName), "{0}/configs/{1}/channel.tx".format(curpath, context.projectName)) - timeout=120 - with common_util.Timeout(timeout): - if not hasattr(context, "composition"): - context.composition = compose_util.Composition(context, composeFiles, - projectName=context.projectName, - startContainers=True) - else: - context.composition.composeFilesYaml = composeFiles - context.composition.up() - context.compose_containers = context.composition.collectServiceNames() + generateCryptoArtifacts(context, "mychannel", consensus_type) + + # In this step, composition will not be used, clear it once + if hasattr(context, "composition"): + del context.composition + + updated_env = config_util.updateEnviron(context) + updated_env["COMPOSE_PROJECT_NAME"] = context.projectName + updated_env["CORE_PEER_NETWORKID"] = context.projectName + + os.chdir("{0}/fabric-samples/first-network".format(curpath)) + + try: + command = ["./byfn.sh up -f docker-compose-explorer.yaml -c {0} -o {1}".format("mychannel", consensus_type)] + subprocess.call(command, shell=True, env=updated_env, stdout=FNULL) + except: + print("Failed npm install: {0}".format(sys.exc_info()[1])) - common_util.wait_until_in_log(["cli"], "Query successful on peer1.org2 on channel ") + os.chdir(curpath) -def generateCryptoArtifacts(context, channelID): +def generateCryptoArtifacts(context, channelID, consensus_type): + curpath = os.path.realpath('.') testConfigs = config_util.makeProjectConfigDir(context) updated_env = config_util.updateEnviron(context) try: - command = ["../../fabric-samples/first-network/byfn.sh", "generate", "-c", channelID] - return subprocess.call(command, cwd=testConfigs, env=updated_env, stdout=FNULL, stderr=subprocess.STDOUT) - #return subprocess.check_output(command, env=updated_env) + command = ["../../fabric-samples/first-network/byfn.sh", "generate", "-f", "docker-compose-explorer.yaml", "-c", channelID, "-o", consensus_type] + subprocess.call(command, cwd=testConfigs, env=updated_env, stderr=subprocess.STDOUT) + except: + print("Unable to generate crypto artifacts: {0}".format(sys.exc_info()[1])) + + try: + shutil.rmtree("{0}/fabric-samples/first-network/crypto-config".format(curpath), ignore_errors=True) + shutil.copytree("{0}/crypto-config".format(testConfigs), "{0}/fabric-samples/first-network/crypto-config".format(curpath)) + shutil.copytree("{0}/crypto-config/peerOrganizations".format(testConfigs), "{0}/peerOrganizations".format(testConfigs)) + shutil.copytree("{0}/crypto-config/ordererOrganizations".format(testConfigs), "{0}/ordererOrganizations".format(testConfigs)) + except: + print("Unable to copy crypto artifacts: {0}".format(sys.exc_info()[1])) + + try: + shutil.rmtree("{0}/fabric-samples/first-network/channel-artifacts".format(curpath), ignore_errors=True) + shutil.copytree("{0}/channel-artifacts".format(testConfigs), "{0}/fabric-samples/first-network/channel-artifacts".format(curpath)) except: - print("Unable to inspect orderer config data: {0}".format(sys.exc_info()[1])) + print("Unable to copy channel artifacts: {0}".format(sys.exc_info()[1])) + @given(u'I start balance-transfer') -def start_balancetransfer_impl(context): +@given(u'I start balance-transfer orderer network of type {consensus_type}') +def start_balancetransfer_impl(context, consensus_type="solo"): testConfigs = config_util.makeProjectConfigDir(context) curpath = os.path.realpath('.') shutil.copytree( diff --git a/client/test/e2e-setup.sh b/client/test/e2e-setup.sh index f981aab4d..cf04f6546 100755 --- a/client/test/e2e-setup.sh +++ b/client/test/e2e-setup.sh @@ -27,10 +27,11 @@ rm -rf channel-artifacts/* ordererOrganizations peerOrganizations mkdir -p ../../configs/$CORE_PEER_NETWORKID ./byfn.sh generate -c mychannel -cp -a channel-artifacts ordererOrganizations peerOrganizations ../../configs/$CORE_PEER_NETWORKID +cp -a channel-artifacts crypto-config/* ../../configs/$CORE_PEER_NETWORKID -docker-compose -f docker-compose-cli.yaml down -v -docker-compose -f docker-compose-cli.yaml up -d +docker-compose -f docker-compose-explorer.yaml down -v +docker-compose -f docker-compose-explorer.yaml up -d +docker exec -d cli scripts/script.sh # continue to poll # we either get a matched keyword, or reach TIMEOUT @@ -41,8 +42,9 @@ while do sleep $DELAY set -x - docker logs cli | grep -q "All GOOD, BYFN execution completed" - rc=$? + if [ $(docker ps -q --filter name='dev-peer1.org2' | wc -l) -eq 1 ]; then + rc=0 + fi set +x done diff --git a/scripts/verify-license.sh b/scripts/verify-license.sh index ae282c6ab..c7882e9aa 100755 --- a/scripts/verify-license.sh +++ b/scripts/verify-license.sh @@ -35,7 +35,7 @@ else fi # If you want to exclude some paths, add a keyword with an extended regular expression format to excluded_paths -excluded_paths="\.ico$ \.jpg$ \.json$ \.png$ \.svg$ \.tx$ \.crt$ \.ya*ml$ \.key$ \.pem$ _sk$ \/META-INF\/ LICENSE$ \.xml$ CHANGELOG\.md$" +excluded_paths="\.ico$ \.jpg$ \.json$ \.png$ \.svg$ \.tx$ \.crt$ \.ya*ml$ \.key$ \.pem$ _sk$ \/META-INF\/ LICENSE$ \.xml$ CHANGELOG\.md$ e2e-test/fabric-samples" for check_file in ${check_files}; do