From 579e523140725503167b2a86e9c029a977eb1b27 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Mon, 29 Mar 2021 11:05:01 +0300 Subject: [PATCH 01/17] feat: added student registration API --- .../src/gateway/fabric-ca-client-config.yaml | 162 ------------------ server/src/index.js | 5 +- server/src/routes/auth.js | 53 +++++- 3 files changed, 49 insertions(+), 171 deletions(-) delete mode 100755 server/src/gateway/fabric-ca-client-config.yaml diff --git a/server/src/gateway/fabric-ca-client-config.yaml b/server/src/gateway/fabric-ca-client-config.yaml deleted file mode 100755 index 2fdcd7a..0000000 --- a/server/src/gateway/fabric-ca-client-config.yaml +++ /dev/null @@ -1,162 +0,0 @@ - -############################################################################# -# This is a configuration file for the fabric-ca-client command. -# -# COMMAND LINE ARGUMENTS AND ENVIRONMENT VARIABLES -# ------------------------------------------------ -# Each configuration element can be overridden via command line -# arguments or environment variables. The precedence for determining -# the value of each element is as follows: -# 1) command line argument -# Examples: -# a) --url https://localhost:7054 -# To set the fabric-ca server url -# b) --tls.client.certfile certfile.pem -# To set the client certificate for TLS -# 2) environment variable -# Examples: -# a) FABRIC_CA_CLIENT_URL=https://localhost:7054 -# To set the fabric-ca server url -# b) FABRIC_CA_CLIENT_TLS_CLIENT_CERTFILE=certfile.pem -# To set the client certificate for TLS -# 3) configuration file -# 4) default value (if there is one) -# All default values are shown beside each element below. -# -# FILE NAME ELEMENTS -# ------------------ -# The value of all fields whose name ends with "file" or "files" are -# name or names of other files. -# For example, see "tls.certfiles" and "tls.client.certfile". -# The value of each of these fields can be a simple filename, a -# relative path, or an absolute path. If the value is not an -# absolute path, it is interpretted as being relative to the location -# of this configuration file. -# -############################################################################# - -############################################################################# -# Client Configuration -############################################################################# - -# URL of the Fabric-ca-server (default: http://localhost:7054) -url: http://0.0.0.0:7054 - -# Membership Service Provider (MSP) directory -# This is useful when the client is used to enroll a peer or orderer, so -# that the enrollment artifacts are stored in the format expected by MSP. -mspdir: msp - -############################################################################# -# TLS section for secure socket connection -# -# certfiles - PEM-encoded list of trusted root certificate files -# client: -# certfile - PEM-encoded certificate file for when client authentication -# is enabled on server -# keyfile - PEM-encoded key file for when client authentication -# is enabled on server -############################################################################# -tls: - # TLS section for secure socket connection - certfiles: - client: - certfile: - keyfile: - -############################################################################# -# Certificate Signing Request section for generating the CSR for an -# enrollment certificate (ECert) -# -# cn - Used by CAs to determine which domain the certificate is to be generated for -# -# serialnumber - The serialnumber field, if specified, becomes part of the issued -# certificate's DN (Distinguished Name). For example, one use case for this is -# a company with its own CA (Certificate Authority) which issues certificates -# to its employees and wants to include the employee's serial number in the DN -# of its issued certificates. -# WARNING: The serialnumber field should not be confused with the certificate's -# serial number which is set by the CA but is not a component of the -# certificate's DN. -# -# names - A list of name objects. Each name object should contain at least one -# "C", "L", "O", or "ST" value (or any combination of these) where these -# are abbreviations for the following: -# "C": country -# "L": locality or municipality (such as city or town name) -# "O": organization -# "OU": organizational unit, such as the department responsible for owning the key; -# it can also be used for a "Doing Business As" (DBS) name -# "ST": the state or province -# -# Note that the "OU" or organizational units of an ECert are always set according -# to the values of the identities type and affiliation. OUs are calculated for an enroll -# as OU=, OU=, ..., OU=. For example, an identity -# of type "client" with an affiliation of "org1.dept2.team3" would have the following -# organizational units: OU=client, OU=org1, OU=dept2, OU=team3 -# -# hosts - A list of host names for which the certificate should be valid -# -############################################################################# -csr: - cn: admin - keyrequest: - algo: ecdsa - size: 256 - serialnumber: - names: - - C: US - ST: North Carolina - L: - O: Hyperledger - OU: Fabric - hosts: - - vlad-Inspiron-5570 - -############################################################################# -# Registration section used to register a new identity with fabric-ca server -# -# name - Unique name of the identity -# type - Type of identity being registered (e.g. 'peer, app, user') -# affiliation - The identity's affiliation -# maxenrollments - The maximum number of times the secret can be reused to enroll. -# Specially, -1 means unlimited; 0 means to use CA's max enrollment -# value. -# attributes - List of name/value pairs of attribute for identity -############################################################################# -id: - name: - type: - affiliation: - maxenrollments: 0 - attributes: - # - name: - # value: - -############################################################################# -# Enrollment section used to enroll an identity with fabric-ca server -# -# profile - Name of the signing profile to use in issuing the certificate -# label - Label to use in HSM operations -############################################################################# -enrollment: - profile: - label: - -############################################################################# -# Name of the CA to connect to within the fabric-ca server -############################################################################# -caname: - -############################################################################# -# BCCSP (BlockChain Crypto Service Provider) section allows to select which -# crypto implementation library to use -############################################################################# -bccsp: - default: SW - sw: - hash: SHA2 - security: 256 - filekeystore: - # The directory used for the software file-based keystore - keystore: msp/keystore diff --git a/server/src/index.js b/server/src/index.js index bd9485f..aaa20c1 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -1,12 +1,11 @@ import express from 'express' -// import './models'; -// import { auth } from './routes'; +import { auth } from './routes'; const app = express(); app.use(express.urlencoded()); app.use(express.json()); -// app.use('/api/v1/', auth); +app.use('/api/v1/', auth); const appPort = 3000; app.listen( appPort, diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index caa4948..a02ddf5 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -1,14 +1,55 @@ import express from 'express'; -import FabricCAServices from 'fabric-ca-client'; -import fs from 'fs'; -import path from 'path'; +import FabricCAService from 'fabric-ca-client'; +import { Gateway, InMemoryWallet, X509WalletMixin } from 'fabric-network'; import yaml from 'js-yaml'; +import path from 'path'; +import * as fs from 'fs'; + const router = express.Router(); const studentRegistration = async (req, res) => { - let caInfo = yaml.safeLoad(fs.readFileSync('../gateway/fabric-ca-client-config.yaml', 'utf8')); - const caTLSCACerts = caInfo.tlsCACerts.pem; - const ca = new FabricCAServices(caInfo.url, { trustedRoots: caTLSCACerts, verify: false }, caInfo.caName); + const { login, password } = req.body; + const ca = new FabricCAService(`http://0.0.0.0:7054`); + const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); + const identity = { + label: 'client', + certificate: adminData.certificate, + privateKey: adminData.key.toBytes(), + mspId: 'NAUKMA', + }; + const wallet = new InMemoryWallet(); + const mixin = X509WalletMixin.createIdentity(identity.mspId, + identity.certificate, + identity.privateKey); + await wallet.import(identity.label, mixin); + const gateway = new Gateway(); + const connectionProfile = yaml.safeLoad( + fs.readFileSync(path.resolve(__dirname, '../gateway/networkConnection.yaml'), 'utf8'), + ); + const connectionOptions = { + identity: identity.label, + wallet, + discovery: { enabled: false, asLocalhost: true }, + }; + await gateway.connect(connectionProfile, connectionOptions); + const admin = await gateway.getCurrentIdentity(); + const secret = await ca.register({ + enrollmentID: login, + enrollmentSecret: password, + role: 'peer', + affiliation: 'naukma.student', + maxEnrollments: -1, + }, admin); + const userData = await ca.enroll({ + enrollmentID: login, + enrollmentSecret: secret, + }); + gateway.disconnect(); + res.status(201).json({ + login, + certificate: userData.certificate, + privateKey: userData.key.toBytes(), + }); }; router.post('/student', studentRegistration); From 6aee9639ae66fdea5fd8a47027790e491bd8e105 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 3 Apr 2021 00:13:55 +0300 Subject: [PATCH 02/17] refactor: Set up fabric nodes --- deploy.sh | 105 +-- network/base/docker-compose-base.yaml | 57 +- network/ca/README.md | 24 - network/ca/data/fabric-ca-client-config.yaml | 162 ----- network/ca/docker-compose.yaml | 35 - .../{data => }/fabric-ca-server-config.yaml | 16 +- network/configtx.yaml | 36 +- network/crypto-config.yaml | 9 +- network/docker-compose.yaml | 30 +- network/msp/config.yaml | 11 - network/orderer/README.md | 22 - network/orderer/data/configtx.yaml | 362 ---------- network/orderer/data/orderer.yaml | 217 ------ network/orderer/docker-compose.yaml | 17 - network/peer/README.md | 22 - network/peer/data/core.yaml | 679 ------------------ network/peer/docker-compose.yaml | 18 - network/testchannel/README.md | 15 - network/testchannel/configtx.yaml | 92 --- server/src/routes/auth.js | 2 +- 20 files changed, 55 insertions(+), 1876 deletions(-) delete mode 100644 network/ca/README.md delete mode 100755 network/ca/data/fabric-ca-client-config.yaml delete mode 100755 network/ca/docker-compose.yaml rename network/ca/{data => }/fabric-ca-server-config.yaml (98%) delete mode 100755 network/msp/config.yaml delete mode 100644 network/orderer/README.md delete mode 100755 network/orderer/data/configtx.yaml delete mode 100644 network/orderer/data/orderer.yaml delete mode 100755 network/orderer/docker-compose.yaml delete mode 100644 network/peer/README.md delete mode 100755 network/peer/data/core.yaml delete mode 100755 network/peer/docker-compose.yaml delete mode 100644 network/testchannel/README.md delete mode 100644 network/testchannel/configtx.yaml diff --git a/deploy.sh b/deploy.sh index 982773a..c8f3f3d 100755 --- a/deploy.sh +++ b/deploy.sh @@ -1,85 +1,22 @@ -#!/bin/bash -docker network rm fabric -docker network create --driver=bridge fabric - -echo -----Installing Binaries for Fabric ./scripts/bootstrap.sh - -echo -----Run Fabric CA Server -cd ./network/ca -docker-compose up -d -cd ../ - -echo -----Enroll admin msp -sleep 2 && ../bin/fabric-ca-client enroll -u http://admin:password@0.0.0.0:7054 - -echo -----Backup admin msp -mkdir -p ./admin -cp -r ~/.fabric-ca-client/msp ./admin/ - - -echo -----Create node account -../bin/fabric-ca-client register --id.name peer1 --id.affiliation naukma.teacher --id.secret passwd --id.type peer - -echo -----Enroll node msp -../bin/fabric-ca-client enroll -u http://peer1:passwd@0.0.0.0:7054 -cp -r ~/.fabric-ca-client/msp ./peer/data/ -mkdir -p ./peer/data/msp/admincerts -cp ./admin/msp/signcerts/cert.pem ./peer/data/msp/admincerts/ -cp ./msp/config.yaml ./peer/data/msp/ - -echo -----Run Fabric Peer Node -cd ./peer -docker-compose up -d -cd ../../ - -echo ----Update admin msp -rm -rf ~/.fabric-ca-client/msp -cp -r ./network/admin/msp/ ~/.fabric-ca-client/ - -echo -----Create node account -cd ./network -../bin/fabric-ca-client register --id.name orderer --id.affiliation naukma.teacher --id.secret passwd --id.type peer - -echo -----Enroll node msp -../bin/fabric-ca-client enroll -u http://orderer:passwd@0.0.0.0:7054 -cp -r ~/.fabric-ca-client/msp ./orderer/data/ -mkdir -p ./orderer/data/msp/admincerts -cp ./admin/msp/signcerts/cert.pem ./orderer/data/msp/admincerts/ -cp ./msp/config.yaml ./orderer/data/msp/ - -echo -----Run Fabric Peer Node -cd ./orderer -docker-compose up -d -cd ../../ - -echo ----Update admin msp -rm -rf ~/.fabric-ca-client/msp -cp -r ./network/admin/msp/ ~/.fabric-ca-client/ - -echo ----Change admin MSP -mkdir -p ~/.fabric-ca-client/msp/admincerts -cd network/ -cp ./admin/msp/signcerts/cert.pem ~/.fabric-ca-client/msp/admincerts -cp -r ./admin/msp ./testchannel - -cd testchannel - -echo ----Build the channel creation transaction -../../bin/configtxgen -asOrg NAUKMA -channelID naukma -configPath $(pwd) -outputCreateChannelTx ./naukma_create.pb -profile TestChannel -sleep 2 && echo ----Create the channel -cd ../ -export FABRIC_CFG_PATH=$(pwd)/peer/data -export CORE_PEER_MSPCONFIGPATH=~/.fabric-ca-client/msp -../bin/peer channel create -c naukma --file ./testchannel/naukma_create.pb --orderer 0.0.0.0:7050 -sleep 2 && echo ----Join the existing nodes to the channel - -../bin/peer channel join --orderer 172.28.0.5:7050 --blockpath ./naukma.block - -sleep 2 && echo ----Install chaincode on the node - - - - - - +cd network +../bin/cryptogen generate --config=./crypto-config.yaml +export FABRIC_CFG_PATH=$PWD +export CHANNEL_NAME=testchannel +../bin/configtxgen -profile OrdererGenesis -channelID byfn-sys-channel -outputBlock ./channel-artifacts/genesis.block +../bin/configtxgen -profile Channel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME +../bin/configtxgen -profile Channel -outputAnchorPeersUpdate ./channel-artifacts/Org1MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org1MSP + +docker-compose -f docker-compose.yaml up -d +docker exec -it cli bash +#Login as peer0 in org1 +export CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp +export CORE_PEER_ADDRESS=peer0.org1.example.com:7051 +export CORE_PEER_LOCALMSPID="Org1MSP" +export 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 + +export CHANNEL_NAME=testchannel + +peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem + +peer channel join -b testchannel.block diff --git a/network/base/docker-compose-base.yaml b/network/base/docker-compose-base.yaml index fb231e0..1117d4d 100755 --- a/network/base/docker-compose-base.yaml +++ b/network/base/docker-compose-base.yaml @@ -7,6 +7,17 @@ version: '2' services: + ca.org1.example.com: + container_name: ca.org1.example.com + image: hyperledger/fabric-ca:1.4 + environment: + - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server + volumes: + - ../ca:/etc/hyperledger/fabric-ca-server + ports: + - 7054:7054 + command: "fabric-ca-server start" + orderer.example.com: container_name: orderer.example.com extends: @@ -63,48 +74,4 @@ services: - peer1.org1.example.com:/var/hyperledger/production ports: - - 8051:8051 - - peer0.org2.example.com: - container_name: peer0.org2.example.com - extends: - file: peer-base.yaml - service: peer-base - environment: - - CORE_PEER_ID=peer0.org2.example.com - - 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/ - - ../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:9051 - - peer1.org2.example.com: - container_name: peer1.org2.example.com - extends: - file: peer-base.yaml - service: peer-base - environment: - - CORE_PEER_ID=peer1.org2.example.com - - 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/ - - ../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:10051 \ No newline at end of file + - 8051:8051 \ No newline at end of file diff --git a/network/ca/README.md b/network/ca/README.md deleted file mode 100644 index 395c557..0000000 --- a/network/ca/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Fabric CA - -## Prerequisites - -You will need Docker and Docker Compose. - -## Bootstrapping Fabric CA server - -1. Change values in `./data/fabric-ca-server-config.yaml` to the ones you are - going to use. -2. Run `docker-compose up -d`. This will bootstrap Fabric CA. - -## Data location - -- All of the Fabric CA data is located under `./data`. Fabric CA configuration - file is created here and will be used from this location in the future. - -## Firewall setup - -- You need to open port 7054: `sudo ufw allow 7054/tcp`. - -## Default passwords - -- The default password for the `admin` identity account is `password`. diff --git a/network/ca/data/fabric-ca-client-config.yaml b/network/ca/data/fabric-ca-client-config.yaml deleted file mode 100755 index 2fdcd7a..0000000 --- a/network/ca/data/fabric-ca-client-config.yaml +++ /dev/null @@ -1,162 +0,0 @@ - -############################################################################# -# This is a configuration file for the fabric-ca-client command. -# -# COMMAND LINE ARGUMENTS AND ENVIRONMENT VARIABLES -# ------------------------------------------------ -# Each configuration element can be overridden via command line -# arguments or environment variables. The precedence for determining -# the value of each element is as follows: -# 1) command line argument -# Examples: -# a) --url https://localhost:7054 -# To set the fabric-ca server url -# b) --tls.client.certfile certfile.pem -# To set the client certificate for TLS -# 2) environment variable -# Examples: -# a) FABRIC_CA_CLIENT_URL=https://localhost:7054 -# To set the fabric-ca server url -# b) FABRIC_CA_CLIENT_TLS_CLIENT_CERTFILE=certfile.pem -# To set the client certificate for TLS -# 3) configuration file -# 4) default value (if there is one) -# All default values are shown beside each element below. -# -# FILE NAME ELEMENTS -# ------------------ -# The value of all fields whose name ends with "file" or "files" are -# name or names of other files. -# For example, see "tls.certfiles" and "tls.client.certfile". -# The value of each of these fields can be a simple filename, a -# relative path, or an absolute path. If the value is not an -# absolute path, it is interpretted as being relative to the location -# of this configuration file. -# -############################################################################# - -############################################################################# -# Client Configuration -############################################################################# - -# URL of the Fabric-ca-server (default: http://localhost:7054) -url: http://0.0.0.0:7054 - -# Membership Service Provider (MSP) directory -# This is useful when the client is used to enroll a peer or orderer, so -# that the enrollment artifacts are stored in the format expected by MSP. -mspdir: msp - -############################################################################# -# TLS section for secure socket connection -# -# certfiles - PEM-encoded list of trusted root certificate files -# client: -# certfile - PEM-encoded certificate file for when client authentication -# is enabled on server -# keyfile - PEM-encoded key file for when client authentication -# is enabled on server -############################################################################# -tls: - # TLS section for secure socket connection - certfiles: - client: - certfile: - keyfile: - -############################################################################# -# Certificate Signing Request section for generating the CSR for an -# enrollment certificate (ECert) -# -# cn - Used by CAs to determine which domain the certificate is to be generated for -# -# serialnumber - The serialnumber field, if specified, becomes part of the issued -# certificate's DN (Distinguished Name). For example, one use case for this is -# a company with its own CA (Certificate Authority) which issues certificates -# to its employees and wants to include the employee's serial number in the DN -# of its issued certificates. -# WARNING: The serialnumber field should not be confused with the certificate's -# serial number which is set by the CA but is not a component of the -# certificate's DN. -# -# names - A list of name objects. Each name object should contain at least one -# "C", "L", "O", or "ST" value (or any combination of these) where these -# are abbreviations for the following: -# "C": country -# "L": locality or municipality (such as city or town name) -# "O": organization -# "OU": organizational unit, such as the department responsible for owning the key; -# it can also be used for a "Doing Business As" (DBS) name -# "ST": the state or province -# -# Note that the "OU" or organizational units of an ECert are always set according -# to the values of the identities type and affiliation. OUs are calculated for an enroll -# as OU=, OU=, ..., OU=. For example, an identity -# of type "client" with an affiliation of "org1.dept2.team3" would have the following -# organizational units: OU=client, OU=org1, OU=dept2, OU=team3 -# -# hosts - A list of host names for which the certificate should be valid -# -############################################################################# -csr: - cn: admin - keyrequest: - algo: ecdsa - size: 256 - serialnumber: - names: - - C: US - ST: North Carolina - L: - O: Hyperledger - OU: Fabric - hosts: - - vlad-Inspiron-5570 - -############################################################################# -# Registration section used to register a new identity with fabric-ca server -# -# name - Unique name of the identity -# type - Type of identity being registered (e.g. 'peer, app, user') -# affiliation - The identity's affiliation -# maxenrollments - The maximum number of times the secret can be reused to enroll. -# Specially, -1 means unlimited; 0 means to use CA's max enrollment -# value. -# attributes - List of name/value pairs of attribute for identity -############################################################################# -id: - name: - type: - affiliation: - maxenrollments: 0 - attributes: - # - name: - # value: - -############################################################################# -# Enrollment section used to enroll an identity with fabric-ca server -# -# profile - Name of the signing profile to use in issuing the certificate -# label - Label to use in HSM operations -############################################################################# -enrollment: - profile: - label: - -############################################################################# -# Name of the CA to connect to within the fabric-ca server -############################################################################# -caname: - -############################################################################# -# BCCSP (BlockChain Crypto Service Provider) section allows to select which -# crypto implementation library to use -############################################################################# -bccsp: - default: SW - sw: - hash: SHA2 - security: 256 - filekeystore: - # The directory used for the software file-based keystore - keystore: msp/keystore diff --git a/network/ca/docker-compose.yaml b/network/ca/docker-compose.yaml deleted file mode 100755 index b4a8174..0000000 --- a/network/ca/docker-compose.yaml +++ /dev/null @@ -1,35 +0,0 @@ -version: "3" - -services: - # This database is not intended to be exposed to any outer network, so the - # default user and password are left as is. For the same reason there is no - # ssl. - db: - image: postgres:11.5 - container_name: fabric_ca_db - environment: - - POSTGRES_DB=fabric_ca - volumes: - - postgres_data:/var/lib/postgresql/data - networks: - fabric: - - ca: - image: hyperledger/fabric-ca:1.4 - container_name: fabric_ca - depends_on: - - db - environment: - - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server - volumes: - - ./data:/etc/hyperledger/fabric-ca-server - ports: - - 7054:7054 - command: "fabric-ca-server start" - networks: - fabric: - -volumes: - postgres_data: -networks: - fabric: diff --git a/network/ca/data/fabric-ca-server-config.yaml b/network/ca/fabric-ca-server-config.yaml similarity index 98% rename from network/ca/data/fabric-ca-server-config.yaml rename to network/ca/fabric-ca-server-config.yaml index 689e7d9..23d5cfb 100755 --- a/network/ca/data/fabric-ca-server-config.yaml +++ b/network/ca/fabric-ca-server-config.yaml @@ -132,7 +132,7 @@ registry: - name: admin pass: password type: client - affiliation: "naukma.teacher" + affiliation: "" attrs: hf.Registrar.Roles: "*" hf.Registrar.DelegateRoles: "*" @@ -153,8 +153,8 @@ registry: # or "mysql". ############################################################################# db: - type: postgres - datasource: host=db port=5432 user=postgres password= dbname=fabric_ca sslmode=disable + type: sqlite3 + datasource: fabric-ca-server.db tls: enabled: false certfiles: @@ -243,7 +243,7 @@ ldap: # which are always stored in lower case. ############################################################################# affiliations: - naukma: + org1: - teacher - student @@ -305,7 +305,7 @@ signing: # CA certificates though it can still issue end entity certificates. ########################################################################### csr: - cn: ca.fabric.naukma + cn: ca.org1.example.com keyrequest: algo: ecdsa size: 256 @@ -313,10 +313,10 @@ csr: - C: UA ST: "Kiev region" L: Kiev - O: naukma - OU: teacher + O: org1.example.com + OU: hosts: - - ca.fabric.naukma + - org1.example.com - localhost ca: expiry: 131400h diff --git a/network/configtx.yaml b/network/configtx.yaml index 762e217..e8df309 100755 --- a/network/configtx.yaml +++ b/network/configtx.yaml @@ -73,36 +73,6 @@ Organizations: - Host: peer0.org1.example.com Port: 7051 - - &Org2 - # DefaultOrg defines the organization which is used in the sampleconfig - # of the fabric.git development environment - Name: Org2MSP - - # ID to load the MSP definition as - ID: Org2MSP - - 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 - # /Channel/// - Policies: - Readers: - Type: Signature - Rule: "OR('Org2MSP.admin', 'Org2MSP.peer', 'Org2MSP.client')" - Writers: - Type: Signature - Rule: "OR('Org2MSP.admin', 'Org2MSP.client')" - Admins: - Type: Signature - Rule: "OR('Org2MSP.admin')" - - AnchorPeers: - # AnchorPeers defines the location of peers which can be used - # 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: 9051 ################################################################################ # @@ -305,7 +275,7 @@ Channel: &ChannelDefaults ################################################################################ Profiles: - TwoOrgsOrdererGenesis: + OrdererGenesis: <<: *ChannelDefaults Orderer: <<: *OrdererDefaults @@ -317,14 +287,12 @@ Profiles: SampleConsortium: Organizations: - *Org1 - - *Org2 - TwoOrgsChannel: + Channel: Consortium: SampleConsortium <<: *ChannelDefaults Application: <<: *ApplicationDefaults Organizations: - *Org1 - - *Org2 Capabilities: <<: *ApplicationCapabilities diff --git a/network/crypto-config.yaml b/network/crypto-config.yaml index 26e0545..25304da 100755 --- a/network/crypto-config.yaml +++ b/network/crypto-config.yaml @@ -1,3 +1,4 @@ +--- # --------------------------------------------------------------------------- # Copyright IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 @@ -5,7 +6,6 @@ # --------------------------------------------------------------------------- # "OrdererOrgs" - Definition of organizations managing orderer nodes -# --------------------------------------------------------------------------- OrdererOrgs: # --------------------------------------------------------------------------- # Orderer @@ -80,10 +80,3 @@ PeerOrgs: # --------------------------------------------------------------------------- # Org2: See "Org1" for full specification # --------------------------------------------------------------------------- - - Name: Org2 - Domain: org2.example.com - EnableNodeOUs: true - Template: - Count: 2 - Users: - Count: 1 \ No newline at end of file diff --git a/network/docker-compose.yaml b/network/docker-compose.yaml index 9a9102d..b09791d 100755 --- a/network/docker-compose.yaml +++ b/network/docker-compose.yaml @@ -6,17 +6,24 @@ version: '2' volumes: + ca.org1.example.com: orderer.example.com: peer0.org1.example.com: peer1.org1.example.com: - peer0.org2.example.com: - peer1.org2.example.com: networks: byfn: services: + ca.org1.example.com: + extends: + file: base/docker-compose-base.yaml + service: ca.org1.example.com + container_name: ca.org1.example.com + networks: + - byfn + orderer.example.com: extends: file: base/docker-compose-base.yaml @@ -41,22 +48,6 @@ services: networks: - byfn - peer0.org2.example.com: - container_name: peer0.org2.example.com - extends: - file: base/docker-compose-base.yaml - service: peer0.org2.example.com - networks: - - byfn - - peer1.org2.example.com: - container_name: peer1.org2.example.com - extends: - file: base/docker-compose-base.yaml - service: peer1.org2.example.com - networks: - - byfn - cli: container_name: cli image: hyperledger/fabric-tools:$IMAGE_TAG @@ -84,10 +75,9 @@ services: - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts depends_on: + - ca.org1.example.com - orderer.example.com - peer0.org1.example.com - peer1.org1.example.com - - peer0.org2.example.com - - peer1.org2.example.com networks: - byfn \ No newline at end of file diff --git a/network/msp/config.yaml b/network/msp/config.yaml deleted file mode 100755 index 4198132..0000000 --- a/network/msp/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -NodeOUs: - Enable: true - ClientOUIdentifier: - Certificate: cacerts/0-0-0-0-7054.pem - OrganizationalUnitIdentifier: client - PeerOUIdentifier: - Certificate: cacerts/0-0-0-0-7054.pem - OrganizationalUnitIdentifier: peer - OrdererOUIdentifier: - Certificate: cacerts/0-0-0-0-7054.pem - OrganizationalUnitIdentifier: peer diff --git a/network/orderer/README.md b/network/orderer/README.md deleted file mode 100644 index 9b5ffc8..0000000 --- a/network/orderer/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Fabric Orderer - -## Prerequisites - -You will need Docker and Docker Compose. - -## Starting up - -*Note that you may need to change some configurations*. Look through -`./network/orderer/data` to examine the configuration prior to going any further. - -- You will need to register an identity of type `orderer` with the CA. - `fabric-ca-client register --id.name orderername --id.affiliation NAUKMA.teacher --id.secret passwd --id.type orderer` - (this should be done from the machine with an enrolled administrative account). -- Build MSP: - - Then enroll this identity from the host where you are going to deploy the - orderer `fabric-ca-client enroll --csr.cn orderer -u http://orderer:passwd@ca-address:7054` - - Copy `~/.fabric-ca-client/msp` to `./data`. - - Create `./data/msp/admincerts` and copy the contents of - `./data/msp/admincerts` here. - - Copy the configuration from `/network/msp/config.yaml`. -- Run `docker-compose up -d`. diff --git a/network/orderer/data/configtx.yaml b/network/orderer/data/configtx.yaml deleted file mode 100755 index 7e36cf9..0000000 --- a/network/orderer/data/configtx.yaml +++ /dev/null @@ -1,362 +0,0 @@ -################################################################################ -# -# ORGANIZATIONS -# -# This section defines the organizational identities that can be referenced -# in the configuration profiles. -# -################################################################################ -Organizations: - - # NAUKMA defines an MSP using the sampleconfig. It should never be used - # in production but may be used as a template for other definitions. - - &NAUKMA - # Name is the key by which this org will be referenced in channel - # configuration transactions. - # Name can include alphanumeric characters as well as dots and dashes. - Name: NAUKMA - - # ID is the key by which this org's MSP definition will be referenced. - # ID can include alphanumeric characters as well as dots and dashes. - ID: NAUKMA - - # MSPDir is the filesystem path which contains the MSP configuration. - MSPDir: msp - - # Policies defines the set of policies at this level of the config tree - # For organization policies, their canonical path is usually - # /Channel/// - Policies: &NAUKMAPolicies - Readers: - Type: Signature - Rule: "OR('NAUKMA.client', 'NAUKMA.peer', 'NAUKMA.admin')" - # If your MSP is configured with the new NodeOUs, you might - # want to use a more specific rule like the following: - # Rule: "OR('NAUKMA.admin', 'NAUKMA.peer', 'NAUKMA.client')" - Writers: - Type: Signature - Rule: "OR('NAUKMA.client', 'NAUKMA.peer', 'NAUKMA.admin')" - # If your MSP is configured with the new NodeOUs, you might - # want to use a more specific rule like the following: - # Rule: "OR('NAUKMA.admin', 'NAUKMA.client')" - Admins: - Type: Signature - Rule: "OR('NAUKMA.admin')" - - # OrdererEndpoints is a list of all orderers this org runs which clients - # and peers may to connect to to push transactions and receive blocks respectively. - OrdererEndpoints: - - # AnchorPeers defines the location of peers which can be used for - # cross-org gossip communication. Note, this value is only encoded in - # the genesis block in the Application section context. - AnchorPeers: - - Host: 0.0.0.0 - Port: 7051 - -################################################################################ -# -# CAPABILITIES -# -# This section defines the capabilities of fabric network. This is a new -# concept as of v1.1.0 and should not be utilized in mixed networks with -# v1.0.x peers and orderers. Capabilities define features which must be -# present in a fabric binary for that binary to safely participate in the -# fabric network. For instance, if a new MSP type is added, newer binaries -# might recognize and validate the signatures from this type, while older -# binaries without this support would be unable to validate those -# transactions. This could lead to different versions of the fabric binaries -# having different world states. Instead, defining a capability for a channel -# informs those binaries without this capability that they must cease -# processing transactions until they have been upgraded. For v1.0.x if any -# capabilities are defined (including a map with all capabilities turned off) -# then the v1.0.x peer will deliberately crash. -# -################################################################################ -Capabilities: - # Channel capabilities apply to both the orderers and the peers and must be - # supported by both. - # Set the value of the capability to true to require it. - Channel: &ChannelCapabilities - # V1.4.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.4.3 - # level, but which would be incompatible with orderers and peers from - # prior releases. - # Prior to enabling V1.4.3 channel capabilities, ensure that all - # orderers and peers on a channel are at v1.4.3 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.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.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 - -################################################################################ -# -# APPLICATION -# -# This section defines the values to encode into a config transaction or -# genesis block for application-related parameters. -# -################################################################################ -Application: &ApplicationDefaults - ACLs: &ACLsDefault - # This section provides defaults for policies for various resources - # in the system. These "resources" could be functions on system chaincodes - # (e.g., "GetBlockByNumber" on the "qscc" system chaincode) or other resources - # (e.g.,who can receive Block events). This section does NOT specify the resource's - # definition or API, but just the ACL policy for it. - # - # User's can override these defaults with their own policy mapping by defining the - # mapping under ACLs in their channel definition - - #---Lifecycle System Chaincode (lscc) function to policy mapping for access control---# - - # ACL policy for lscc's "getid" function - lscc/ChaincodeExists: /Channel/Application/Readers - - # ACL policy for lscc's "getdepspec" function - lscc/GetDeploymentSpec: /Channel/Application/Readers - - # ACL policy for lscc's "getccdata" function - lscc/GetChaincodeData: /Channel/Application/Readers - - # ACL Policy for lscc's "getchaincodes" function - lscc/GetInstantiatedChaincodes: /Channel/Application/Readers - - #---Query System Chaincode (qscc) function to policy mapping for access control---# - - # ACL policy for qscc's "GetChainInfo" function - qscc/GetChainInfo: /Channel/Application/Readers - - # ACL policy for qscc's "GetBlockByNumber" function - qscc/GetBlockByNumber: /Channel/Application/Readers - - # ACL policy for qscc's "GetBlockByHash" function - qscc/GetBlockByHash: /Channel/Application/Readers - - # ACL policy for qscc's "GetTransactionByID" function - qscc/GetTransactionByID: /Channel/Application/Readers - - # ACL policy for qscc's "GetBlockByTxID" function - qscc/GetBlockByTxID: /Channel/Application/Readers - - #---Configuration System Chaincode (cscc) function to policy mapping for access control---# - - # ACL policy for cscc's "GetConfigBlock" function - cscc/GetConfigBlock: /Channel/Application/Readers - - # ACL policy for cscc's "GetConfigTree" function - cscc/GetConfigTree: /Channel/Application/Readers - - # ACL policy for cscc's "SimulateConfigTreeUpdate" function - cscc/SimulateConfigTreeUpdate: /Channel/Application/Readers - - #---Miscellanesous peer function to policy mapping for access control---# - - # ACL policy for invoking chaincodes on peer - peer/Propose: /Channel/Application/Writers - - # ACL policy for chaincode to chaincode invocation - peer/ChaincodeToChaincode: /Channel/Application/Readers - - #---Events resource to policy mapping for access control###---# - - # ACL policy for sending block events - event/Block: /Channel/Application/Readers - - # ACL policy for sending filtered block events - event/FilteredBlock: /Channel/Application/Readers - - # Organizations lists the orgs participating on the application side of the - # network. - Organizations: - - # Policies defines the set of policies at this level of the config tree - # For Application policies, their canonical path is - # /Channel/Application/ - Policies: &ApplicationDefaultPolicies - Readers: - Type: ImplicitMeta - Rule: "ANY Readers" - Writers: - Type: ImplicitMeta - Rule: "ANY Writers" - Admins: - Type: ImplicitMeta - Rule: "MAJORITY Admins" - - # Capabilities describes the application level capabilities, see the - # dedicated Capabilities section elsewhere in this file for a full - # description - Capabilities: - <<: *ApplicationCapabilities - -################################################################################ -# -# ORDERER -# -# This section defines the values to encode into a config transaction or -# genesis block for orderer related parameters. -# -################################################################################ -Orderer: &OrdererDefaults - - # Orderer Type: The orderer implementation to start. - # Available types are "solo" and "kafka". - OrdererType: solo - - # Addresses used to be the list of orderer addresses that clients and peers - # could connect to. However, this does not allow clients to associate orderer - # addresses and orderer organizations which can be useful for things such - # as TLS validation. The preferred way to specify orderer addresses is now - # to include the OrdererEndpoints item in your org definition - Addresses: - - # Batch Timeout: The amount of time to wait before creating a batch. - BatchTimeout: 2s - - # Batch Size: Controls the number of messages batched into a block. - # The orderer views messages opaquely, but typically, messages may - # be considered to be Fabric transactions. The 'batch' is the group - # of messages in the 'data' field of the block. Blocks will be a few kb - # larger than the batch size, when signatures, hashes, and other metadata - # is applied. - BatchSize: - - # Max Message Count: The maximum number of messages to permit in a - # batch. No block will contain more than this number of messages. - MaxMessageCount: 500 - - # Absolute Max Bytes: The absolute maximum number of bytes allowed for - # the serialized messages in a batch. The maximum block size is this value - # plus the size of the associated metadata (usually a few KB depending - # upon the size of the signing identities). Any transaction larger than - # this value will be rejected by ordering. If the "kafka" OrdererType is - # selected, set 'message.max.bytes' and 'replica.fetch.max.bytes' on - # the Kafka brokers to a value that is larger than this one. - AbsoluteMaxBytes: 10 MB - - # Preferred Max Bytes: The preferred maximum number of bytes allowed - # for the serialized messages in a batch. Roughly, this field may be considered - # the best effort maximum size of a batch. A batch will fill with messages - # until this size is reached (or the max message count, or batch timeout is - # exceeded). If adding a new message to the batch would cause the batch to - # exceed the preferred max bytes, then the current batch is closed and written - # to a block, and a new batch containing the new message is created. If a - # message larger than the preferred max bytes is received, then its batch - # will contain only that message. Because messages may be larger than - # preferred max bytes (up to AbsoluteMaxBytes), some batches may exceed - # the preferred max bytes, but will always contain exactly one transaction. - PreferredMaxBytes: 2 MB - - # Max Channels is the maximum number of channels to allow on the ordering - # network. When set to 0, this implies no maximum number of channels. - MaxChannels: 0 - - # Organizations lists the orgs participating on the orderer side of the - # network. - Organizations: - - # Policies defines the set of policies at this level of the config tree - # For Orderer policies, their canonical path is - # /Channel/Orderer/ - Policies: - Readers: - Type: ImplicitMeta - Rule: "ANY Readers" - Writers: - Type: ImplicitMeta - Rule: "ANY Writers" - Admins: - Type: ImplicitMeta - Rule: "MAJORITY Admins" - # BlockValidation specifies what signatures must be included in the block - # from the orderer for the peer to validate it. - BlockValidation: - Type: ImplicitMeta - Rule: "ANY Writers" - - # Capabilities describes the orderer level capabilities, see the - # dedicated Capabilities section elsewhere in this file for a full - # description - Capabilities: - <<: *OrdererCapabilities - -################################################################################ -# -# CHANNEL -# -# This section defines the values to encode into a config transaction or -# genesis block for channel related parameters. -# -################################################################################ -Channel: &ChannelDefaults - # Policies defines the set of policies at this level of the config tree - # For Channel policies, their canonical path is - # /Channel/ - Policies: - # Who may invoke the 'Deliver' API - Readers: - Type: ImplicitMeta - Rule: "ANY Readers" - # Who may invoke the 'Broadcast' API - Writers: - Type: ImplicitMeta - Rule: "ANY Writers" - # By default, who may modify elements at this config level - Admins: - Type: ImplicitMeta - Rule: "MAJORITY Admins" - - - # Capabilities describes the channel level capabilities, see the - # dedicated Capabilities section elsewhere in this file for a full - # description - Capabilities: - <<: *ChannelCapabilities - -################################################################################ -# -# PROFILES -# -# Different configuration profiles may be encoded here to be specified as -# parameters to the configtxgen tool. The profiles which specify consortiums -# are to be used for generating the orderer genesis block. With the correct -# consortium members defined in the orderer genesis block, channel creation -# requests may be generated with only the org member names and a consortium -# name. -# -################################################################################ -Profiles: - - # SampleSingleMSPSolo defines a configuration which uses the Solo orderer, - # and contains a single MSP definition (the MSP sampleconfig). - # The Consortium SampleConsortium has only a single member, NAUKMA. - SampleSingleMSPSolo: - <<: *ChannelDefaults - Orderer: - <<: *OrdererDefaults - Addresses: - - 0.0.0.0:7050 - Organizations: - - *NAUKMA - - Consortiums: - SampleConsortium: - Organizations: - - *NAUKMA diff --git a/network/orderer/data/orderer.yaml b/network/orderer/data/orderer.yaml deleted file mode 100644 index 5704076..0000000 --- a/network/orderer/data/orderer.yaml +++ /dev/null @@ -1,217 +0,0 @@ -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 -# - ---- -################################################################################ -# -# Orderer Configuration -# -# - This controls the type and configuration of the orderer. -# -################################################################################ -General: - - # Ledger Type: The ledger type to provide to the orderer. - # Two non-production ledger types are provided for test purposes only: - # - ram: An in-memory ledger whose contents are lost on restart. - # - json: A simple file ledger that writes blocks to disk in JSON format. - # Only one production ledger type is provided: - # - file: A production file-based ledger. - LedgerType: file - - # Listen address: The IP on which to bind to listen. - ListenAddress: 0.0.0.0 - - # Listen port: The port on which to bind to listen. - ListenPort: 7050 - - # TLS: TLS settings for the GRPC server. - TLS: - Enabled: false - # PrivateKey governs the file location of the private key of the TLS certificate. - PrivateKey: tls/server.key - # Certificate governs the file location of the server TLS certificate. - Certificate: tls/server.crt - RootCAs: - - tls/ca.crt - ClientAuthRequired: false - ClientRootCAs: - # Keepalive settings for the GRPC server. - Keepalive: - # ServerMinInterval is the minimum permitted time between client pings. - # If clients send pings more frequently, the server will - # disconnect them. - ServerMinInterval: 60s - # ServerInterval is the time between pings to clients. - ServerInterval: 7200s - # ServerTimeout is the duration the server waits for a response from - # a client before closing the connection. - ServerTimeout: 20s - # Cluster settings for ordering service nodes that communicate with other ordering service nodes - # such as Raft based ordering service. - Cluster: - # SendBufferSize is the maximum number of messages in the egress buffer. - # Consensus messages are dropped if the buffer is full, and transaction - # messages are waiting for space to be freed. - SendBufferSize: 10 - # ClientCertificate governs the file location of the client TLS certificate - # used to establish mutual TLS connections with other ordering service nodes. - ClientCertificate: - # ClientPrivateKey governs the file location of the private key of the client TLS certificate. - ClientPrivateKey: - # The below 4 properties should be either set together, or be unset together. - # If they are set, then the orderer node uses a separate listener for intra-cluster - # communication. If they are unset, then the general orderer listener is used. - # This is useful if you want to use a different TLS server certificates on the - # client-facing and the intra-cluster listeners. - - # ListenPort defines the port on which the cluster listens to connections. - ListenPort: - # ListenAddress defines the IP on which to listen to intra-cluster communication. - ListenAddress: - # ServerCertificate defines the file location of the server TLS certificate used for intra-cluster - # communication. - ServerCertificate: - # ServerPrivateKey defines the file location of the private key of the TLS certificate. - ServerPrivateKey: - # Genesis method: The method by which the genesis block for the orderer - # system channel is specified. Available options are "provisional", "file": - # - provisional: Utilizes a genesis profile, specified by GenesisProfile, - # to dynamically generate a new genesis block. - # - file: Uses the file provided by GenesisFile as the genesis block. - GenesisMethod: provisional - - # Genesis profile: The profile to use to dynamically generate the genesis - # block to use when initializing the orderer system channel and - # GenesisMethod is set to "provisional". See the configtx.yaml file for the - # descriptions of the available profiles. Ignored if GenesisMethod is set to - # "file". - GenesisProfile: SampleSingleMSPSolo - - # Genesis file: The file containing the genesis block to use when - # initializing the orderer system channel and GenesisMethod is set to - # "file". Ignored if GenesisMethod is set to "provisional". - GenesisFile: genesisblock - - # LocalMSPDir is where to find the private crypto material needed by the - # orderer. It is set relative here as a default for dev environments but - # should be changed to the real location in production. - LocalMSPDir: /etc/hyperledger/fabric/msp - - # LocalMSPID is the identity to register the local MSP material with the MSP - # manager. IMPORTANT: The local MSP ID of an orderer needs to match the MSP - # ID of one of the organizations defined in the orderer system channel's - # /Channel/Orderer configuration. The sample organization defined in the - # sample configuration provided has an MSP ID of "SampleOrg". - LocalMSPID: NAUKMA - - # Enable an HTTP service for Go "pprof" profiling as documented at: - # https://golang.org/pkg/net/http/pprof - Profile: - Enabled: false - Address: 0.0.0.0:6060 - - # BCCSP configures the blockchain crypto service providers. - BCCSP: - # Default specifies the preferred blockchain crypto service provider - # to use. If the preferred provider is not available, the software - # based provider ("SW") will be used. - # Valid providers are: - # - SW: a software based crypto provider - # - PKCS11: a CA hardware security module crypto provider. - Default: SW - - # SW configures the software based blockchain crypto provider. - SW: - # TODO: The default Hash and Security level needs refactoring to be - # fully configurable. Changing these defaults requires coordination - # SHA2 is hardcoded in several places, not only BCCSP - Hash: SHA2 - Security: 256 - # Location of key store. If this is unset, a location will be - # chosen using: 'LocalMSPDir'/keystore - FileKeyStore: - KeyStore: - - # Authentication contains configuration parameters related to authenticating - # client messages - Authentication: - # the acceptable difference between the current server time and the - # client's time as specified in a client request message - TimeWindow: 15m - -################################################################################ -# -# SECTION: File Ledger -# -# - This section applies to the configuration of the file or json ledgers. -# -################################################################################ -FileLedger: - - # Location: The directory to store the blocks in. - # NOTE: If this is unset, a new temporary location will be chosen every time - # the orderer is restarted, using the prefix specified by Prefix. - Location: /etc/hyperledger/fabric - - # The prefix to use when generating a ledger directory in temporary space. - # Otherwise, this value is ignored. - Prefix: hyperledger-fabric-ordererledger - -################################################################################ -# -# Operations Configuration -# -# - This configures the operations server endpoint for the orderer -# -################################################################################ -Operations: - # host and port for the operations server - ListenAddress: 127.0.0.1:8443 - - # TLS configuration for the operations endpoint - TLS: - # TLS enabled - Enabled: false - - # Certificate is the location of the PEM encoded TLS certificate - Certificate: - - # PrivateKey points to the location of the PEM-encoded key - PrivateKey: - - # Most operations service endpoints require client authentication when TLS - # is enabled. ClientAuthRequired requires client certificate authentication - # at the TLS layer to access all resources. - ClientAuthRequired: false - - # Paths to PEM encoded ca certificates to trust for client authentication - ClientRootCAs: [] - -################################################################################ -# -# Metrics Configuration -# -# - This configures metrics collection for the orderer -# -################################################################################ -Metrics: - # The metrics provider is one of statsd, prometheus, or disabled - Provider: disabled - - # The statsd configuration - Statsd: - # network type: tcp or udp - Network: udp - - # the statsd server address - Address: 127.0.0.1:8125 - - # The interval at which locally cached counters and gauges are pushed - # to statsd; timings are pushed immediately - WriteInterval: 30s - - # The prefix is prepended to all emitted statsd metrics - Prefix: diff --git a/network/orderer/docker-compose.yaml b/network/orderer/docker-compose.yaml deleted file mode 100755 index 7243751..0000000 --- a/network/orderer/docker-compose.yaml +++ /dev/null @@ -1,17 +0,0 @@ -version: "3" - -services: - orderer: - image: hyperledger/fabric-orderer:1.4 - container_name: fabric_orderer - working_dir: /etc/hyperledger/fabric - volumes: - - ./data:/etc/hyperledger/fabric - ports: - - 7050:7050 - command: orderer - networks: - fabric: - -networks: - fabric: diff --git a/network/peer/README.md b/network/peer/README.md deleted file mode 100644 index 3d1bda6..0000000 --- a/network/peer/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Fabric Peer - -## Prerequisites - -You will need Docker and Docker Compose. - -## Starting up - -*Note that you may need to change some configurations*. Look through -`data/fabric-peer` to examine the configuration prior to going any further. - -- You will need to register an identity of type `peer` with the CA. - `fabric-ca-client register --id.name peername --id.affiliation naukma.teather --id.secret passwd --id.type peer` (this should be done from the machine with an - enrolled administrative account). -- Build MSP: - - Then enroll this identity from the host where you are going to deploy the - peer `fabric-ca-client enroll --csr.cn peername -u http://peername:passwd@ca-address:7054` - - Copy `~/.fabric-ca-client/msp` to `./data`. - - Create `./data/msp/admincerts` and copy the contents of - `./data/msp/admincerts` here. - - Copy the configuration from `/network/msp/config.yaml`. -- Run `docker-compose up -d`. diff --git a/network/peer/data/core.yaml b/network/peer/data/core.yaml deleted file mode 100755 index ec52865..0000000 --- a/network/peer/data/core.yaml +++ /dev/null @@ -1,679 +0,0 @@ -############################################################################### -# -# Peer section -# -############################################################################### -peer: - # The Peer id is used for identifying this Peer instance. - id: peer1 - - # The networkId allows for logical seperation of networks - networkId: dev - - # The Address at local network interface this Peer will listen on. - # By default, it will listen on all network interfaces - listenAddress: 0.0.0.0:7051 - - # The endpoint this peer uses to listen for inbound chaincode connections. - # If this is commented-out, the listen address is selected to be - # the peer's address (see below) with port 7052 - # chaincodeListenAddress: 0.0.0.0:7052 - - # The endpoint the chaincode for this peer uses to connect to the peer. - # If this is not specified, the chaincodeListenAddress address is selected. - # And if chaincodeListenAddress is not specified, address is selected from - # peer listenAddress. - # chaincodeAddress: 0.0.0.0:7052 - - # When used as peer config, this represents the endpoint to other peers - # in the same organization. For peers in other organization, see - # gossip.externalEndpoint for more info. - # When used as CLI config, this means the peer's endpoint to interact with - address: 0.0.0.0:7051 - - # Whether the Peer should programmatically determine its address - # This case is useful for docker containers. - addressAutoDetect: true - - # Setting for runtime.GOMAXPROCS(n). If n < 1, it does not change the - # current setting - gomaxprocs: -1 - - # Keepalive settings for peer server and clients - keepalive: - # MinInterval is the minimum permitted time between client pings. - # If clients send pings more frequently, the peer server will - # disconnect them - minInterval: 60s - # Client keepalive settings for communicating with other peer nodes - client: - # Interval is the time between pings to peer nodes. This must - # greater than or equal to the minInterval specified by peer - # nodes - interval: 60s - # Timeout is the duration the client waits for a response from - # peer nodes before closing the connection - timeout: 20s - # DeliveryClient keepalive settings for communication with ordering - # nodes. - deliveryClient: - # Interval is the time between pings to ordering nodes. This must - # greater than or equal to the minInterval specified by ordering - # nodes. - interval: 60s - # Timeout is the duration the client waits for a response from - # ordering nodes before closing the connection - timeout: 20s - - # Gossip related configuration - gossip: - # Bootstrap set to initialize gossip with. - # This is a list of other peers that this peer reaches out to at startup. - # Important: The endpoints here have to be endpoints of peers in the same - # organization, because the peer would refuse connecting to these endpoints - # unless they are in the same organization as the peer. - bootstrap: 127.0.0.1:7051 - - # NOTE: orgLeader and useLeaderElection parameters are mutual exclusive. - # Setting both to true would result in the termination of the peer - # since this is undefined state. If the peers are configured with - # useLeaderElection=false, make sure there is at least 1 peer in the - # organization that its orgLeader is set to true. - - # Defines whenever peer will initialize dynamic algorithm for - # "leader" selection, where leader is the peer to establish - # connection with ordering service and use delivery protocol - # to pull ledger blocks from ordering service. It is recommended to - # use leader election for large networks of peers. - useLeaderElection: true - # Statically defines peer to be an organization "leader", - # where this means that current peer will maintain connection - # with ordering service and disseminate block across peers in - # its own organization - orgLeader: false - - # Interval for membershipTracker polling - membershipTrackerInterval: 5s - - # Overrides the endpoint that the peer publishes to peers - # in its organization. For peers in foreign organizations - # see 'externalEndpoint' - endpoint: - # Maximum count of blocks stored in memory - maxBlockCountToStore: 100 - # Max time between consecutive message pushes(unit: millisecond) - maxPropagationBurstLatency: 10ms - # Max number of messages stored until a push is triggered to remote peers - maxPropagationBurstSize: 10 - # Number of times a message is pushed to remote peers - propagateIterations: 1 - # Number of peers selected to push messages to - propagatePeerNum: 3 - # Determines frequency of pull phases(unit: second) - # Must be greater than digestWaitTime + responseWaitTime - pullInterval: 4s - # Number of peers to pull from - pullPeerNum: 3 - # Determines frequency of pulling state info messages from peers(unit: second) - requestStateInfoInterval: 4s - # Determines frequency of pushing state info messages to peers(unit: second) - publishStateInfoInterval: 4s - # Maximum time a stateInfo message is kept until expired - stateInfoRetentionInterval: - # Time from startup certificates are included in Alive messages(unit: second) - publishCertPeriod: 10s - # Should we skip verifying block messages or not (currently not in use) - skipBlockVerification: false - # Dial timeout(unit: second) - dialTimeout: 3s - # Connection timeout(unit: second) - connTimeout: 2s - # Buffer size of received messages - recvBuffSize: 20 - # Buffer size of sending messages - sendBuffSize: 200 - # Time to wait before pull engine processes incoming digests (unit: second) - # Should be slightly smaller than requestWaitTime - digestWaitTime: 1s - # Time to wait before pull engine removes incoming nonce (unit: milliseconds) - # Should be slightly bigger than digestWaitTime - requestWaitTime: 1500ms - # Time to wait before pull engine ends pull (unit: second) - responseWaitTime: 2s - # Alive check interval(unit: second) - aliveTimeInterval: 5s - # Alive expiration timeout(unit: second) - aliveExpirationTimeout: 25s - # Reconnect interval(unit: second) - reconnectInterval: 25s - # This is an endpoint that is published to peers outside of the organization. - # If this isn't set, the peer will not be known to other organizations. - externalEndpoint: - # Leader election service configuration - election: - # Longest time peer waits for stable membership during leader election startup (unit: second) - startupGracePeriod: 15s - # Interval gossip membership samples to check its stability (unit: second) - membershipSampleInterval: 1s - # Time passes since last declaration message before peer decides to perform leader election (unit: second) - leaderAliveThreshold: 10s - # Time between peer sends propose message and declares itself as a leader (sends declaration message) (unit: second) - leaderElectionDuration: 5s - - pvtData: - # pullRetryThreshold determines the maximum duration of time private data corresponding for a given block - # would be attempted to be pulled from peers until the block would be committed without the private data - pullRetryThreshold: 60s - # As private data enters the transient store, it is associated with the peer's ledger's height at that time. - # transientstoreMaxBlockRetention defines the maximum difference between the current ledger's height upon commit, - # and the private data residing inside the transient store that is guaranteed not to be purged. - # Private data is purged from the transient store when blocks with sequences that are multiples - # of transientstoreMaxBlockRetention are committed. - transientstoreMaxBlockRetention: 1000 - # pushAckTimeout is the maximum time to wait for an acknowledgement from each peer - # at private data push at endorsement time. - pushAckTimeout: 3s - # Block to live pulling margin, used as a buffer - # to prevent peer from trying to pull private data - # from peers that is soon to be purged in next N blocks. - # This helps a newly joined peer catch up to current - # blockchain height quicker. - btlPullMargin: 10 - # the process of reconciliation is done in an endless loop, while in each iteration reconciler tries to - # pull from the other peers the most recent missing blocks with a maximum batch size limitation. - # reconcileBatchSize determines the maximum batch size of missing private data that will be reconciled in a - # single iteration. - reconcileBatchSize: 10 - # reconcileSleepInterval determines the time reconciler sleeps from end of an iteration until the beginning - # of the next reconciliation iteration. - reconcileSleepInterval: 1m - # reconciliationEnabled is a flag that indicates whether private data reconciliation is enable or not. - reconciliationEnabled: true - # skipPullingInvalidTransactionsDuringCommit is a flag that indicates whether pulling of invalid - # transaction's private data from other peers need to be skipped during the commit time and pulled - # only through reconciler. - skipPullingInvalidTransactionsDuringCommit: false - - # Gossip state transfer related configuration - state: - # indicates whenever state transfer is enabled or not - # default value is true, i.e. state transfer is active - # and takes care to sync up missing blocks allowing - # lagging peer to catch up to speed with rest network - enabled: true - # checkInterval interval to check whether peer is lagging behind enough to - # request blocks via state transfer from another peer. - checkInterval: 10s - # responseTimeout amount of time to wait for state transfer response from - # other peers - responseTimeout: 3s - # batchSize the number of blocks to request via state transfer from another peer - batchSize: 10 - # blockBufferSize reflect the maximum distance between lowest and - # highest block sequence number state buffer to avoid holes. - # In order to ensure absence of the holes actual buffer size - # is twice of this distance - blockBufferSize: 100 - # maxRetries maximum number of re-tries to ask - # for single state transfer request - maxRetries: 3 - - # TLS Settings - # Note that peer-chaincode connections through chaincodeListenAddress is - # not mutual TLS auth. See comments on chaincodeListenAddress for more info - tls: - # Require server-side TLS - enabled: false - # Require client certificates / mutual TLS. - # Note that clients that are not configured to use a certificate will - # fail to connect to the peer. - clientAuthRequired: false - # X.509 certificate used for TLS server - cert: - file: tls/server.crt - # Private key used for TLS server (and client if clientAuthEnabled - # is set to true - key: - file: tls/server.key - # Trusted root certificate chain for tls.cert - rootcert: - file: tls/ca.crt - # Set of root certificate authorities used to verify client certificates - clientRootCAs: - files: - - tls/ca.crt - # Private key used for TLS when making client connections. If - # not set, peer.tls.key.file will be used instead - clientKey: - file: - # X.509 certificate used for TLS when making client connections. - # If not set, peer.tls.cert.file will be used instead - clientCert: - file: - - # Authentication contains configuration parameters related to authenticating - # client messages - authentication: - # the acceptable difference between the current server time and the - # client's time as specified in a client request message - timewindow: 15m - - # Path on the file system where peer will store data (eg ledger). This - # location must be access control protected to prevent unintended - # modification that might corrupt the peer operations. - fileSystemPath: /etc/hyperledger/fabric - - # BCCSP (Blockchain crypto provider): Select which crypto implementation or - # library to use - BCCSP: - Default: SW - # Settings for the SW crypto provider (i.e. when DEFAULT: SW) - SW: - # TODO: The default Hash and Security level needs refactoring to be - # fully configurable. Changing these defaults requires coordination - # SHA2 is hardcoded in several places, not only BCCSP - Hash: SHA2 - Security: 256 - # Location of Key Store - FileKeyStore: - # If "", defaults to 'mspConfigPath'/keystore - KeyStore: - # Settings for the PKCS#11 crypto provider (i.e. when DEFAULT: PKCS11) - PKCS11: - # Location of the PKCS11 module library - Library: - # Token Label - Label: - # User PIN - Pin: - Hash: - Security: - FileKeyStore: - KeyStore: - - # Path on the file system where peer will find MSP local configurations - mspConfigPath: msp - - # Identifier of the local MSP - # ----!!!!IMPORTANT!!!-!!!IMPORTANT!!!-!!!IMPORTANT!!!!---- - # Deployers need to change the value of the localMspId string. - # In particular, the name of the local MSP ID of a peer needs - # to match the name of one of the MSPs in each of the channel - # that this peer is a member of. Otherwise this peer's messages - # will not be identified as valid by other nodes. - localMspId: NAUKMA - - # CLI common client config options - client: - # connection timeout - connTimeout: 3s - - # Delivery service related config - deliveryclient: - # It sets the total time the delivery service may spend in reconnection - # attempts until its retry logic gives up and returns an error - reconnectTotalTimeThreshold: 3600s - - # It sets the delivery service <-> ordering service node connection timeout - connTimeout: 3s - - # It sets the delivery service maximal delay between consecutive retries - reConnectBackoffThreshold: 3600s - - # Type for the local MSP - by default it's of type bccsp - localMspType: bccsp - - # Used with Go profiling tools only in none production environment. In - # production, it should be disabled (eg enabled: false) - profile: - enabled: false - listenAddress: 0.0.0.0:6060 - - # The admin service is used for administrative operations such as - # control over logger levels, etc. - # Only peer administrators can use the service. - adminService: - # The interface and port on which the admin server will listen on. - # If this is commented out, or the port number is equal to the port - # of the peer listen address - the admin service is attached to the - # peer's service (defaults to 7051). - #listenAddress: 0.0.0.0:7055 - - # Handlers defines custom handlers that can filter and mutate - # objects passing within the peer, such as: - # Auth filter - reject or forward proposals from clients - # Decorators - append or mutate the chaincode input passed to the chaincode - # Endorsers - Custom signing over proposal response payload and its mutation - # Valid handler definition contains: - # - A name which is a factory method name defined in - # core/handlers/library/library.go for statically compiled handlers - # - library path to shared object binary for pluggable filters - # Auth filters and decorators are chained and executed in the order that - # they are defined. For example: - # authFilters: - # - - # name: FilterOne - # library: /opt/lib/filter.so - # - - # name: FilterTwo - # decorators: - # - - # name: DecoratorOne - # - - # name: DecoratorTwo - # library: /opt/lib/decorator.so - # Endorsers are configured as a map that its keys are the endorsement system chaincodes that are being overridden. - # Below is an example that overrides the default ESCC and uses an endorsement plugin that has the same functionality - # as the default ESCC. - # If the 'library' property is missing, the name is used as the constructor method in the builtin library similar - # to auth filters and decorators. - # endorsers: - # escc: - # name: DefaultESCC - # library: /etc/hyperledger/fabric/plugin/escc.so - handlers: - authFilters: - - name: DefaultAuth - - name: ExpirationCheck # This filter checks identity x509 certificate expiration - decorators: - - name: DefaultDecorator - endorsers: - escc: - name: DefaultEndorsement - library: - validators: - vscc: - name: DefaultValidation - library: - - # library: /etc/hyperledger/fabric/plugin/escc.so - # Number of goroutines that will execute transaction validation in parallel. - # By default, the peer chooses the number of CPUs on the machine. Set this - # variable to override that choice. - # NOTE: overriding this value might negatively influence the performance of - # the peer so please change this value only if you know what you're doing - validatorPoolSize: - - # The discovery service is used by clients to query information about peers, - # such as - which peers have joined a certain channel, what is the latest - # channel config, and most importantly - given a chaincode and a channel, - # what possible sets of peers satisfy the endorsement policy. - discovery: - enabled: true - # Whether the authentication cache is enabled or not. - authCacheEnabled: true - # The maximum size of the cache, after which a purge takes place - authCacheMaxSize: 1000 - # The proportion (0 to 1) of entries that remain in the cache after the cache is purged due to overpopulation - authCachePurgeRetentionRatio: 0.75 - # Whether to allow non-admins to perform non channel scoped queries. - # When this is false, it means that only peer admins can perform non channel scoped queries. - orgMembersAllowedAccess: false -############################################################################### -# -# VM section -# -############################################################################### -vm: - # Endpoint of the vm management system. For docker can be one of the following in general - # unix:///var/run/docker.sock - # http://localhost:2375 - # https://localhost:2376 - endpoint: unix:///host/var/run/docker.sock - - # settings for docker vms - docker: - tls: - enabled: false - ca: - file: docker/ca.crt - cert: - file: docker/tls.crt - key: - file: docker/tls.key - - # Enables/disables the standard out/err from chaincode containers for - # debugging purposes - attachStdout: true - - # Parameters on creating docker container. - # Container may be efficiently created using ipam & dns-server for cluster - # NetworkMode - sets the networking mode for the container. Supported - # standard values are: `host`(default),`bridge`,`ipvlan`,`none`. - # Dns - a list of DNS servers for the container to use. - # Note: `Privileged` `Binds` `Links` and `PortBindings` properties of - # Docker Host Config are not supported and will not be used if set. - # LogConfig - sets the logging driver (Type) and related options - # (Config) for Docker. For more info, - # https://docs.docker.com/engine/admin/logging/overview/ - # Note: Set LogConfig using Environment Variables is not supported. - hostConfig: - NetworkMode: host - Dns: - # - 192.168.0.1 - LogConfig: - Type: json-file - Config: - max-size: "50m" - max-file: "5" - Memory: 2147483648 - -############################################################################### -# -# Chaincode section -# -############################################################################### -chaincode: - # The id is used by the Chaincode stub to register the executing Chaincode - # ID with the Peer and is generally supplied through ENV variables - # the `path` form of ID is provided when installing the chaincode. - # The `name` is used for all other requests and can be any string. - id: - path: - name: - - # Generic builder environment, suitable for most chaincode types - builder: $(DOCKER_NS)/fabric-ccenv:latest - - # Enables/disables force pulling of the base docker images (listed below) - # during user chaincode instantiation. - # Useful when using moving image tags (such as :latest) - pull: false - - golang: - # golang will never need more than baseos - runtime: $(BASE_DOCKER_NS)/fabric-baseos:$(ARCH)-$(BASE_VERSION) - - # whether or not golang chaincode should be linked dynamically - dynamicLink: false - - car: - # car may need more facilities (JVM, etc) in the future as the catalog - # of platforms are expanded. For now, we can just use baseos - runtime: $(BASE_DOCKER_NS)/fabric-baseos:$(ARCH)-$(BASE_VERSION) - - java: - # This is an image based on java:openjdk-8 with addition compiler - # tools added for java shim layer packaging. - # This image is packed with shim layer libraries that are necessary - # for Java chaincode runtime. - runtime: $(DOCKER_NS)/fabric-javaenv:$(ARCH)-$(PROJECT_VERSION) - - node: - # need node.js engine at runtime, currently available in baseimage - # but not in baseos - runtime: $(BASE_DOCKER_NS)/fabric-baseimage:$(ARCH)-$(BASE_VERSION) - - # Timeout duration for starting up a container and waiting for Register - # to come through. 1sec should be plenty for chaincode unit tests - startuptimeout: 300s - - # Timeout duration for Invoke and Init calls to prevent runaway. - # This timeout is used by all chaincodes in all the channels, including - # system chaincodes. - # Note that during Invoke, if the image is not available (e.g. being - # cleaned up when in development environment), the peer will automatically - # build the image, which might take more time. In production environment, - # the chaincode image is unlikely to be deleted, so the timeout could be - # reduced accordingly. - executetimeout: 30s - - # There are 2 modes: "dev" and "net". - # In dev mode, user runs the chaincode after starting peer from - # command line on local machine. - # In net mode, peer will run chaincode in a docker container. - mode: net - - # keepalive in seconds. In situations where the communiction goes through a - # proxy that does not support keep-alive, this parameter will maintain connection - # between peer and chaincode. - # A value <= 0 turns keepalive off - keepalive: 0 - - # system chaincodes whitelist. To add system chaincode "myscc" to the - # whitelist, add "myscc: enable" to the list below, and register in - # chaincode/importsysccs.go - system: - cscc: enable - lscc: enable - escc: enable - vscc: enable - qscc: enable - - # System chaincode plugins: - # System chaincodes can be loaded as shared objects compiled as Go plugins. - # See examples/plugins/scc for an example. - # Plugins must be white listed in the chaincode.system section above. - systemPlugins: - # example configuration: - # - enabled: true - # name: myscc - # path: /opt/lib/myscc.so - # invokableExternal: true - # invokableCC2CC: true - - # Logging section for the chaincode container - logging: - # Default level for all loggers within the chaincode container - level: info - # Override default level for the 'shim' logger - shim: warning - # Format for the chaincode container logs - format: "%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}" - -############################################################################### -# -# Ledger section - ledger configuration encompases both the blockchain -# and the state -# -############################################################################### -ledger: - blockchain: - - state: - # stateDatabase - options are "goleveldb", "CouchDB" - # goleveldb - default state database stored in goleveldb. - # CouchDB - store state database in CouchDB - stateDatabase: goleveldb - # Limit on the number of records to return per query - totalQueryLimit: 100000 - couchDBConfig: - # It is recommended to run CouchDB on the same server as the peer, and - # not map the CouchDB container port to a server port in docker-compose. - # Otherwise proper security must be provided on the connection between - # CouchDB client (on the peer) and server. - couchDBAddress: 127.0.0.1:5984 - # This username must have read and write authority on CouchDB - username: - # The password is recommended to pass as an environment variable - # during start up (eg CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD). - # If it is stored here, the file must be access control protected - # to prevent unintended users from discovering the password. - password: - # Number of retries for CouchDB errors - maxRetries: 3 - # Number of retries for CouchDB errors during peer startup - maxRetriesOnStartup: 12 - # CouchDB request timeout (unit: duration, e.g. 20s) - requestTimeout: 35s - # Limit on the number of records per each CouchDB query - # Note that chaincode queries are only bound by totalQueryLimit. - # Internally the chaincode may execute multiple CouchDB queries, - # each of size internalQueryLimit. - internalQueryLimit: 1000 - # Limit on the number of records per CouchDB bulk update batch - maxBatchUpdateSize: 1000 - # Warm indexes after every N blocks. - # This option warms any indexes that have been - # deployed to CouchDB after every N blocks. - # A value of 1 will warm indexes after every block commit, - # to ensure fast selector queries. - # Increasing the value may improve write efficiency of peer and CouchDB, - # but may degrade query response time. - warmIndexesAfterNBlocks: 1 - # Create the _global_changes system database - # This is optional. Creating the global changes database will require - # additional system resources to track changes and maintain the database - createGlobalChangesDB: false - - history: - # enableHistoryDatabase - options are true or false - # Indicates if the history of key updates should be stored. - # All history 'index' will be stored in goleveldb, regardless if using - # CouchDB or alternate database for the state. - enableHistoryDatabase: true - -############################################################################### -# -# Operations section -# -############################################################################### -operations: - # host and port for the operations server - listenAddress: 127.0.0.1:9443 - - # TLS configuration for the operations endpoint - tls: - # TLS enabled - enabled: false - - # path to PEM encoded server certificate for the operations server - cert: - file: - - # path to PEM encoded server key for the operations server - key: - file: - - # most operations service endpoints require client authentication when TLS - # is enabled. clientAuthRequired requires client certificate authentication - # at the TLS layer to access all resources. - clientAuthRequired: false - - # paths to PEM encoded ca certificates to trust for client authentication - clientRootCAs: - files: [] - -############################################################################### -# -# Metrics section -# -############################################################################### -metrics: - # metrics provider is one of statsd, prometheus, or disabled - provider: disabled - - # statsd configuration - statsd: - # network type: tcp or udp - network: udp - - # statsd server address - address: 127.0.0.1:8125 - - # the interval at which locally cached counters and gauges are pushed - # to statsd; timings are pushed immediately - writeInterval: 10s - - # prefix is prepended to all emitted statsd metrics - prefix: diff --git a/network/peer/docker-compose.yaml b/network/peer/docker-compose.yaml deleted file mode 100755 index 42d2746..0000000 --- a/network/peer/docker-compose.yaml +++ /dev/null @@ -1,18 +0,0 @@ -version: "3" - -services: - orderer: - image: hyperledger/fabric-peer:1.4 - container_name: fabric_peer - working_dir: /etc/hyperledger/fabric - volumes: - - ./data:/etc/hyperledger/fabric - - /var/run/:/host/var/run/ - ports: - - 7051:7051 - - 7052:7052 - command: peer node start - networks: - fabric: -networks: - fabric: diff --git a/network/testchannel/README.md b/network/testchannel/README.md deleted file mode 100644 index 366547c..0000000 --- a/network/testchannel/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# Channel for testing chaincodes - -This configuration defines a channel named `naukma` with the write access -for all members of `NAUKMA` organization. - -## Creating a channel - -To create a channel: - -- Create the genesis transaction: - `configtxgen -asOrg NAUKMA -channelID naukma -configPath -outputCreateChannelTx ./naukma_create.pb -profile TestChannel` -- Submit this transaction with: - `peer channel create -c naukma --file ./naukma_create.pb --orderer :7050`. - This command will download the genesis block of this channel. -- Add a node to a newly created channel: `peer channel join --orderer :7050 --blockpath ./naukma.block` diff --git a/network/testchannel/configtx.yaml b/network/testchannel/configtx.yaml deleted file mode 100644 index 549dd27..0000000 --- a/network/testchannel/configtx.yaml +++ /dev/null @@ -1,92 +0,0 @@ -################################################################################ -# -# ORGANIZATIONS -# -# This section defines the organizational identities that can be referenced -# in the configuration profiles. -# -################################################################################ -Organizations: - # NAUKMA defines an MSP using the sampleconfig. It should never be used - # in production but may be used as a template for other definitions. - - &NAUKMA - # Name is the key by which this org will be referenced in channel - # configuration transactions. - # Name can include alphanumeric characters as well as dots and dashes. - Name: NAUKMA - - # ID is the key by which this org's MSP definition will be referenced. - # ID can include alphanumeric characters as well as dots and dashes. - ID: NAUKMA - - # MSPDir is the filesystem path which contains the MSP configuration. - MSPDir: msp - - # Policies defines the set of policies at this level of the config tree - # For organization policies, their canonical path is usually - # /Channel/// - Policies: &NAUKMAPolicies - Readers: - Type: Signature - Rule: "OR('NAUKMA.client', 'NAUKMA.admin', 'NAUKMA.peer')" - Writers: - Type: Signature - Rule: "OR('NAUKMA.client', 'NAUKMA.admin', 'NAUKMA.peer')" - Admins: - Type: Signature - Rule: "OR('NAUKMA.admin')" - - # OrdererEndpoints is a list of all orderers this org runs which clients - # and peers may to connect to to push transactions and receive blocks respectively. - OrdererEndpoints: - - "0.0.0.0:7050" - - # AnchorPeers defines the location of peers which can be used for - # cross-org gossip communication. Note, this value is only encoded in - # the genesis block in the Application section context. - AnchorPeers: - -################################################################################ -# -# SECTION: Application -# -# - This section defines the values to encode into a config transaction or -# genesis block for application related parameters -# -################################################################################ -Application: &ApplicationDefaults - # Organizations is the list of orgs which are defined as participants on - # the application side of the network - Policies: &ApplicationDefaultPolicies - Readers: - Type: ImplicitMeta - Rule: "ANY Readers" - Writers: - Type: ImplicitMeta - Rule: "ANY Writers" - Admins: - Type: ImplicitMeta - Rule: "MAJORITY Admins" - Organizations: - -Capabilities: - Application: &ApplicationCapabilities - V1_4_2: true - -################################################################################ -# -# Profile -# -# - Different configuration profiles may be encoded here to be specified -# as parameters to the configtxgen tool -# -################################################################################ -Profiles: - TestChannel: - Consortium: SampleConsortium - Application: - <<: *ApplicationDefaults - Organizations: - - *NAUKMA - Capabilities: - <<: *ApplicationCapabilities diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index a02ddf5..295e181 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -37,7 +37,7 @@ const studentRegistration = async (req, res) => { enrollmentID: login, enrollmentSecret: password, role: 'peer', - affiliation: 'naukma.student', + affiliation: 'org1.student', maxEnrollments: -1, }, admin); const userData = await ca.enroll({ From e59ec178104109e76ebd0b41b1a556cfacd5d888 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 3 Apr 2021 02:38:02 +0300 Subject: [PATCH 03/17] refactor: decomposed functions in utils --- server/src/routes/auth.js | 75 +++++++++++++++------------------------ server/src/utils/index.js | 44 +++++++++++++++++++++++ 2 files changed, 72 insertions(+), 47 deletions(-) create mode 100644 server/src/utils/index.js diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 295e181..193d371 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -1,55 +1,36 @@ import express from 'express'; -import FabricCAService from 'fabric-ca-client'; -import { Gateway, InMemoryWallet, X509WalletMixin } from 'fabric-network'; -import yaml from 'js-yaml'; -import path from 'path'; -import * as fs from 'fs'; - +import { X509WalletMixin } from 'fabric-network'; +import { getCA, getConnectedWallet, registerUser } from '../utils'; const router = express.Router(); const studentRegistration = async (req, res) => { const { login, password } = req.body; - const ca = new FabricCAService(`http://0.0.0.0:7054`); - const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); - const identity = { - label: 'client', - certificate: adminData.certificate, - privateKey: adminData.key.toBytes(), - mspId: 'NAUKMA', - }; - const wallet = new InMemoryWallet(); - const mixin = X509WalletMixin.createIdentity(identity.mspId, - identity.certificate, - identity.privateKey); - await wallet.import(identity.label, mixin); - const gateway = new Gateway(); - const connectionProfile = yaml.safeLoad( - fs.readFileSync(path.resolve(__dirname, '../gateway/networkConnection.yaml'), 'utf8'), - ); - const connectionOptions = { - identity: identity.label, - wallet, - discovery: { enabled: false, asLocalhost: true }, - }; - await gateway.connect(connectionProfile, connectionOptions); - const admin = await gateway.getCurrentIdentity(); - const secret = await ca.register({ - enrollmentID: login, - enrollmentSecret: password, - role: 'peer', - affiliation: 'org1.student', - maxEnrollments: -1, - }, admin); - const userData = await ca.enroll({ - enrollmentID: login, - enrollmentSecret: secret, - }); - gateway.disconnect(); - res.status(201).json({ - login, - certificate: userData.certificate, - privateKey: userData.key.toBytes(), - }); + try { + const ca = getCA(); + const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); + const mixin = X509WalletMixin.createIdentity( + 'NAUKMA', + adminData.certificate, + adminData.key.toBytes() + ); + const gateway = await getConnectedWallet('client', mixin); + const admin = await gateway.getCurrentIdentity() + await registerUser(ca, admin, { login, password, affiliation: 'student' }); + + const userData = await ca.enroll({ + enrollmentID: login, + enrollmentSecret: password, + }); + gateway.disconnect(); + res.status(201).json({ + login, + certificate: userData.certificate, + privateKey: userData.key.toBytes(), + }); + } + catch (e) { + res.status(400).json({ message: e.message }); + } }; router.post('/student', studentRegistration); diff --git a/server/src/utils/index.js b/server/src/utils/index.js new file mode 100644 index 0000000..22b4583 --- /dev/null +++ b/server/src/utils/index.js @@ -0,0 +1,44 @@ +import { Gateway, InMemoryWallet } from 'fabric-network'; +import FabricCAService from 'fabric-ca-client'; +import fs from 'fs'; +import path from 'path'; +import yaml from 'js-yaml'; + +export const getCA = () =>{ + try { + return new FabricCAService(`http://192.168.88.88:7054`) + }catch (e){ + console.error(e) + throw new Error(e.message) + } +} +export const getConnectedWallet = async (label, mixin) => { + const wallet = new InMemoryWallet(); + await wallet.import(label, mixin); + const gateway = new Gateway(); + const connectionProfile = yaml.safeLoad( + fs.readFileSync(path.resolve(__dirname, '../gateway/networkConnection.yaml'), 'utf8'), + ); + const connectionOptions = { + identity: label, + wallet, + discovery: { enabled: false, asLocalhost: true }, + }; + await gateway.connect(connectionProfile, connectionOptions); + return gateway; +} +export const registerUser = async (ca, adminWallet, userData) => { + try { + await ca.register({ + enrollmentID: userData.login, + enrollmentSecret: userData.password, + role: 'peer', + affiliation: `org1.${userData.affiliation}`, + maxEnrollments: -1, + }, adminWallet); + } + catch (e) { + console.error(e.message) + throw new Error(e.message); + } +} From bc65abf5f333688ef330826ce7813104c6c58860 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 3 Apr 2021 03:39:19 +0300 Subject: [PATCH 04/17] feat: added explorer --- chaincode/src/contracts/index.js | 6 +- chaincode/src/contracts/key-value-storage.js | 12 ---- .../src/contracts/student-records-storage.js | 19 +++++++ chaincode/src/index.js | 6 +- deploy.sh | 16 +++++- network/explorer/config.json | 9 +++ network/explorer/docker-compose.yaml | 57 +++++++++++++++++++ network/explorer/test-network.json | 50 ++++++++++++++++ 8 files changed, 156 insertions(+), 19 deletions(-) delete mode 100644 chaincode/src/contracts/key-value-storage.js create mode 100644 chaincode/src/contracts/student-records-storage.js create mode 100644 network/explorer/config.json create mode 100644 network/explorer/docker-compose.yaml create mode 100644 network/explorer/test-network.json diff --git a/chaincode/src/contracts/index.js b/chaincode/src/contracts/index.js index 144435b..4a39b35 100644 --- a/chaincode/src/contracts/index.js +++ b/chaincode/src/contracts/index.js @@ -1,5 +1,5 @@ -const KeyValueStorageContract = require('./key-value-storage'); +const StudentRecordsStorageContract = require('./student-records-storage'); module.exports = { - KeyValueStorageContract -}; \ No newline at end of file + StudentRecordsStorageContract +}; diff --git a/chaincode/src/contracts/key-value-storage.js b/chaincode/src/contracts/key-value-storage.js deleted file mode 100644 index f5e0ae5..0000000 --- a/chaincode/src/contracts/key-value-storage.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -const { Contract } = require('fabric-contract-api'); - -class KeyValueStorage extends Contract { - constructor() { - super('org.fabric.keyvaluestorage'); - } - -} - -module.exports = KeyValueStorage; diff --git a/chaincode/src/contracts/student-records-storage.js b/chaincode/src/contracts/student-records-storage.js new file mode 100644 index 0000000..682d928 --- /dev/null +++ b/chaincode/src/contracts/student-records-storage.js @@ -0,0 +1,19 @@ +'use strict'; + +const { Contract } = require('fabric-contract-api'); +const { ClientIdentity } = require('fabric-shim'); + +class StudentRecordsStorage extends Contract { + constructor() { + super('org.fabric.studentRecordsStorage'); + } + + async createStudentRecord(ctx) { + const identity = new ClientIdentity(ctx.stub); + console.log(JSON.stringify(identity, null, 2)) + console.log(JSON.stringify(identity.cert, null, 2)) + + } +} + +module.exports = StudentRecordsStorage; diff --git a/chaincode/src/index.js b/chaincode/src/index.js index d445f88..722fdd2 100644 --- a/chaincode/src/index.js +++ b/chaincode/src/index.js @@ -1,5 +1,5 @@ -const { KeyValueStorageContract } = require('./contracts'); +const { StudentRecordsStorageContract } = require('./contracts'); module.exports.contracts = [ - KeyValueStorageContract, -]; \ No newline at end of file + StudentRecordsStorageContract, +]; diff --git a/deploy.sh b/deploy.sh index c8f3f3d..2aa442d 100755 --- a/deploy.sh +++ b/deploy.sh @@ -9,7 +9,7 @@ export CHANNEL_NAME=testchannel docker-compose -f docker-compose.yaml up -d docker exec -it cli bash -#Login as peer0 in org1 +#Login as peer0 in org1 export CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp export CORE_PEER_ADDRESS=peer0.org1.example.com:7051 export CORE_PEER_LOCALMSPID="Org1MSP" @@ -20,3 +20,17 @@ export CHANNEL_NAME=testchannel peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem peer channel join -b testchannel.block + +#Install chaincode +peer chaincode install -n recordcontract -v 1.0 -l node -p /opt/gopath/src/github.com/chaincode + +#Initiate chaincode +peer chaincode instantiate -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract -l node -v 1.0 -c '{"Args":[]}' + +peer chaincode invoke -o orderer.example.com:7050 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt -c '{"Args":["createStudentRecord"]}' + +#Update chaincode - Change version +peer chaincode install -n recordcontract -v 1.1 -l node -p /opt/gopath/src/github.com/chaincode + +peer chaincode upgrade -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract -l node -v 1.1 -c '{"Args":[]}' + diff --git a/network/explorer/config.json b/network/explorer/config.json new file mode 100644 index 0000000..5535506 --- /dev/null +++ b/network/explorer/config.json @@ -0,0 +1,9 @@ +{ + "network-configs": { + "test-network": { + "name": "Test Network", + "profile": "./test-network.json" + } + }, + "license": "Apache-2.0" +} diff --git a/network/explorer/docker-compose.yaml b/network/explorer/docker-compose.yaml new file mode 100644 index 0000000..e34baf9 --- /dev/null +++ b/network/explorer/docker-compose.yaml @@ -0,0 +1,57 @@ + +# SPDX-License-Identifier: Apache-2.0 +version: '2.1' + +volumes: + pgdata: + walletstore: + +networks: + byfn: + +services: + + explorerdb.mynetwork.com: + image: hyperledger/explorer-db:latest + container_name: explorerdb.mynetwork.com + hostname: explorerdb.mynetwork.com + environment: + - DATABASE_DATABASE=fabricexplorer + - DATABASE_USERNAME=hppoc + - DATABASE_PASSWORD=password + healthcheck: + test: "pg_isready -h localhost -p 5432 -q -U postgres" + interval: 30s + timeout: 10s + retries: 5 + volumes: + - pgdata:/var/lib/postgresql/data + networks: + - byfn + + explorer.mynetwork.com: + image: hyperledger/explorer:latest + container_name: explorer.mynetwork.com + hostname: explorer.mynetwork.com + environment: + - DATABASE_HOST=explorerdb.mynetwork.com + - DATABASE_DATABASE=fabricexplorer + - DATABASE_USERNAME=hppoc + - DATABASE_PASSWD=password + - LOG_LEVEL_APP=debug + - LOG_LEVEL_DB=debug + - LOG_LEVEL_CONSOLE=info + - LOG_CONSOLE_STDOUT=true + - DISCOVERY_AS_LOCALHOST=false + volumes: + - ./config.json:/opt/explorer/app/platform/fabric/config.json + - ./connection-profile:/opt/explorer/app/platform/fabric/connection-profile + - ../crypto-config:/tmp/crypto + - walletstore:/opt/explorer/wallet + ports: + - 8080:8080 + depends_on: + explorerdb.mynetwork.com: + condition: service_healthy + networks: + - byfn diff --git a/network/explorer/test-network.json b/network/explorer/test-network.json new file mode 100644 index 0000000..967d319 --- /dev/null +++ b/network/explorer/test-network.json @@ -0,0 +1,50 @@ +{ + "name": "test-network", + "version": "1.0.0", + "client": { + "tlsEnable": true, + "adminCredential": { + "id": "admin", + "password": "password" + }, + "enableAuthentication": true, + "organization": "Org1MSP", + "connection": { + "timeout": { + "peer": { + "endorser": "300" + }, + "orderer": "300" + } + } + }, + "channels": { + "mychannel": { + "peers": { + "peer0.org1.example.com": {} + } + } + }, + "organizations": { + "Org1MSP": { + "mspid": "Org1MSP", + "adminPrivateKey": { + "path": "/tmp/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/06358ff75f0dcf60eeabd50b02e8641c987437f56ff527b1a778fe64260f2c1f_sk" + }, + "peers": [ + "peer0.org1.example.com" + ], + "signedCert": { + "path": "/tmp/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem" + } + } + }, + "peers": { + "peer0.org1.example.com": { + "tlsCACerts": { + "path": "/tmp/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" + }, + "url": "grpcs://peer0.org1.example.com:7051" + } + } +} From 6181083ef5f01e063fb065e4be2858a70cf50efa Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 3 Apr 2021 05:05:00 +0300 Subject: [PATCH 05/17] feat: fixed profile --- .../src/contracts/student-records-storage.js | 3 +- deploy.sh | 2 +- server/src/gateway/networkConnection.yaml | 22 ++++++++------ server/src/index.js | 5 ++-- server/src/routes/auth.js | 2 +- server/src/routes/index.js | 1 + server/src/routes/record.js | 29 +++++++++++++++++++ server/src/utils/index.js | 19 +++++++++++- 8 files changed, 67 insertions(+), 16 deletions(-) create mode 100644 server/src/routes/record.js diff --git a/chaincode/src/contracts/student-records-storage.js b/chaincode/src/contracts/student-records-storage.js index 682d928..c1f79bf 100644 --- a/chaincode/src/contracts/student-records-storage.js +++ b/chaincode/src/contracts/student-records-storage.js @@ -10,8 +10,7 @@ class StudentRecordsStorage extends Contract { async createStudentRecord(ctx) { const identity = new ClientIdentity(ctx.stub); - console.log(JSON.stringify(identity, null, 2)) - console.log(JSON.stringify(identity.cert, null, 2)) + } } diff --git a/deploy.sh b/deploy.sh index 2aa442d..a0ac6b9 100755 --- a/deploy.sh +++ b/deploy.sh @@ -28,7 +28,7 @@ peer chaincode install -n recordcontract -v 1.0 -l node -p /opt/gopath/src/githu peer chaincode instantiate -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract -l node -v 1.0 -c '{"Args":[]}' peer chaincode invoke -o orderer.example.com:7050 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt -c '{"Args":["createStudentRecord"]}' - +peer chaincode query -C $CHANNEL_NAME -n recordcontract -c '{"Args":["createStudentRecord"]}' #Update chaincode - Change version peer chaincode install -n recordcontract -v 1.1 -l node -p /opt/gopath/src/github.com/chaincode diff --git a/server/src/gateway/networkConnection.yaml b/server/src/gateway/networkConnection.yaml index 2b5bf07..415c093 100644 --- a/server/src/gateway/networkConnection.yaml +++ b/server/src/gateway/networkConnection.yaml @@ -43,7 +43,7 @@ channels: # Required. list of peers from participating orgs peers: - peer1: + peer0.org1.example.com: # [Optional]. will this peer be sent transaction proposals for endorsement? The peer must # have the chaincode installed. The app can also use this property to decide which peers # to send the chaincode install request. Default: true @@ -67,11 +67,11 @@ channels: # list of participating organizations in this network # organizations: - NAUKMA: - mspid: NAUKMA + Org1: + mspid: Org1 peers: - - peer1 + - peer0.org1.example.com # # List of orderers to send transaction and channel create/update requests to. For the time @@ -80,25 +80,29 @@ organizations: # orderers: orderer_n1: - url: grpc://172.28.0.5:7050 + url: grpc://192.168.88.88:7050 # these are standard properties defined by the gRPC library # they will be passed in as-is to gRPC client constructor grpcOptions: ssl-target-name-override: orderer_n1 + tlsCACerts: + path: ../../../network/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem # # List of peers to send various requests to, including endorsement, query # and event listener registration. # peers: - peer1: + peer0.org1.example.com: # this URL is used to send endorsement and query requests - url: grpc://172.28.0.4:7051 + url: grpc://192.168.88.88:7051 grpcOptions: - ssl-target-name-override: peer1 + ssl-target-name-override: peer0.org1.example.com request-timeout: 120001 + tlsCACerts: + path: ../../../network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem # Fabric-CA is a special kind of Certificate Authority provided by Hyperledger Fabric which allows # certificate management to be done via REST APIs. Application may choose to use a standard @@ -106,7 +110,7 @@ peers: # certificateAuthorities: ca-org1: - url: http://172.28.0.3:7054 + url: http://192.168.88.88:7054 # the properties specified under this object are passed to the 'http' client verbatim when # making the request to the Fabric-CA server httpOptions: diff --git a/server/src/index.js b/server/src/index.js index aaa20c1..30154fd 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -1,11 +1,12 @@ import express from 'express' -import { auth } from './routes'; +import { auth, record } from './routes'; const app = express(); app.use(express.urlencoded()); app.use(express.json()); -app.use('/api/v1/', auth); +app.use('/api/v1/auth/', auth); +app.use('/api/v1/record/', record); const appPort = 3000; app.listen( appPort, diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 193d371..24f5486 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -9,7 +9,7 @@ const studentRegistration = async (req, res) => { const ca = getCA(); const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); const mixin = X509WalletMixin.createIdentity( - 'NAUKMA', + 'Org1', adminData.certificate, adminData.key.toBytes() ); diff --git a/server/src/routes/index.js b/server/src/routes/index.js index a2c97a3..413c198 100644 --- a/server/src/routes/index.js +++ b/server/src/routes/index.js @@ -1 +1,2 @@ export { default as auth } from './auth'; +export { default as record } from './record'; diff --git a/server/src/routes/record.js b/server/src/routes/record.js new file mode 100644 index 0000000..c1e04e4 --- /dev/null +++ b/server/src/routes/record.js @@ -0,0 +1,29 @@ +import express from 'express'; +import { X509WalletMixin } from 'fabric-network'; +import { getCA, getConnectedWallet, sendTransaction } from '../utils'; + +const router = express.Router(); +const createStudentRecord = async (req, res) => { + const { certificate, privateKey } = req.body; + try { + const ca = getCA(); + const mixin = X509WalletMixin.createIdentity( + 'Org1', + certificate, + privateKey + ); + const gateway = await getConnectedWallet('client', mixin); + const result = await sendTransaction(gateway, { + name: 'createStudentRecord', + props: [], + }); + gateway.disconnect(); + res.status(201).json(result); + } + catch (e) { + res.status(400).json({ message: e.message }); + } +}; +router.post('/student', createStudentRecord); + +export default router; diff --git a/server/src/utils/index.js b/server/src/utils/index.js index 22b4583..cfc3729 100644 --- a/server/src/utils/index.js +++ b/server/src/utils/index.js @@ -22,7 +22,7 @@ export const getConnectedWallet = async (label, mixin) => { const connectionOptions = { identity: label, wallet, - discovery: { enabled: false, asLocalhost: true }, + discovery: { enabled: true, asLocalhost: true }, }; await gateway.connect(connectionProfile, connectionOptions); return gateway; @@ -42,3 +42,20 @@ export const registerUser = async (ca, adminWallet, userData) => { throw new Error(e.message); } } + +export const sendTransaction = async(gateway, transaction) => { + try { + // console.log(await gateway.getChannel()) + + const network = await gateway.getNetwork('testchannel'); + const contract = await network.getContract('recordcontract', + 'org.fabric.studentRecordsStorage'); + const issueResponse = await contract.submitTransaction(transaction.name, ...transaction.props); + return JSON.parse(issueResponse.toString()); + } + catch (error) { + console.log(`Error processing transaction. ${error.stack}`); + gateway.disconnect(); + return null; + } +} From 1ddded3dab6c2fc3984461f56352d36ae2adf870 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 3 Apr 2021 05:15:39 +0300 Subject: [PATCH 06/17] feat: fixed profile --- server/src/gateway/networkConnection.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server/src/gateway/networkConnection.yaml b/server/src/gateway/networkConnection.yaml index 415c093..c6f57e4 100644 --- a/server/src/gateway/networkConnection.yaml +++ b/server/src/gateway/networkConnection.yaml @@ -80,14 +80,14 @@ organizations: # orderers: orderer_n1: - url: grpc://192.168.88.88:7050 + url: grpc://0.0.0.0:7050 # these are standard properties defined by the gRPC library # they will be passed in as-is to gRPC client constructor grpcOptions: ssl-target-name-override: orderer_n1 tlsCACerts: - path: ../../../network/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem + path: ../network/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem # # List of peers to send various requests to, including endorsement, query @@ -96,13 +96,13 @@ orderers: peers: peer0.org1.example.com: # this URL is used to send endorsement and query requests - url: grpc://192.168.88.88:7051 + url: grpc://0.0.0.0:7051 grpcOptions: ssl-target-name-override: peer0.org1.example.com request-timeout: 120001 tlsCACerts: - path: ../../../network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem + path: ../network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem # Fabric-CA is a special kind of Certificate Authority provided by Hyperledger Fabric which allows # certificate management to be done via REST APIs. Application may choose to use a standard @@ -110,7 +110,7 @@ peers: # certificateAuthorities: ca-org1: - url: http://192.168.88.88:7054 + url: http://0.0.0.0:7054 # the properties specified under this object are passed to the 'http' client verbatim when # making the request to the Fabric-CA server httpOptions: From 0961a3df20ebaeaabb0bcc7e78e78707e4a4d486 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 3 Apr 2021 09:40:43 +0300 Subject: [PATCH 07/17] feat: fixed profile --- .../src/contracts/student-records-storage.js | 1 - deploy.sh | 22 +++---- network/explorer/config.json | 9 --- network/explorer/docker-compose.yaml | 57 ------------------- network/explorer/test-network.json | 50 ---------------- server/src/gateway/networkConnection.yaml | 3 - server/src/routes/auth.js | 2 +- server/src/routes/record.js | 29 ---------- 8 files changed, 12 insertions(+), 161 deletions(-) delete mode 100644 network/explorer/config.json delete mode 100644 network/explorer/docker-compose.yaml delete mode 100644 network/explorer/test-network.json delete mode 100644 server/src/routes/record.js diff --git a/chaincode/src/contracts/student-records-storage.js b/chaincode/src/contracts/student-records-storage.js index c1f79bf..8efd828 100644 --- a/chaincode/src/contracts/student-records-storage.js +++ b/chaincode/src/contracts/student-records-storage.js @@ -11,7 +11,6 @@ class StudentRecordsStorage extends Contract { async createStudentRecord(ctx) { const identity = new ClientIdentity(ctx.stub); - } } diff --git a/deploy.sh b/deploy.sh index a0ac6b9..4d29482 100755 --- a/deploy.sh +++ b/deploy.sh @@ -22,15 +22,15 @@ peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-ar peer channel join -b testchannel.block #Install chaincode -peer chaincode install -n recordcontract -v 1.0 -l node -p /opt/gopath/src/github.com/chaincode - -#Initiate chaincode -peer chaincode instantiate -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract -l node -v 1.0 -c '{"Args":[]}' - -peer chaincode invoke -o orderer.example.com:7050 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt -c '{"Args":["createStudentRecord"]}' -peer chaincode query -C $CHANNEL_NAME -n recordcontract -c '{"Args":["createStudentRecord"]}' -#Update chaincode - Change version -peer chaincode install -n recordcontract -v 1.1 -l node -p /opt/gopath/src/github.com/chaincode - -peer chaincode upgrade -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract -l node -v 1.1 -c '{"Args":[]}' +#peer chaincode install -n recordcontract -v 1.0 -l node -p /opt/gopath/src/github.com/chaincode +# +##Initiate chaincode +#peer chaincode instantiate -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract -l node -v 1.0 -c '{"Args":[]}' +# +#peer chaincode invoke -o orderer.example.com:7050 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt -c '{"Args":["createStudentRecord"]}' +#peer chaincode query -C $CHANNEL_NAME -n recordcontract -c '{"Args":["createStudentRecord"]}' +##Update chaincode - Change version +#peer chaincode install -n recordcontract -v 1.1 -l node -p /opt/gopath/src/github.com/chaincode +# +#peer chaincode upgrade -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n recordcontract -l node -v 1.1 -c '{"Args":[]}' diff --git a/network/explorer/config.json b/network/explorer/config.json deleted file mode 100644 index 5535506..0000000 --- a/network/explorer/config.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "network-configs": { - "test-network": { - "name": "Test Network", - "profile": "./test-network.json" - } - }, - "license": "Apache-2.0" -} diff --git a/network/explorer/docker-compose.yaml b/network/explorer/docker-compose.yaml deleted file mode 100644 index e34baf9..0000000 --- a/network/explorer/docker-compose.yaml +++ /dev/null @@ -1,57 +0,0 @@ - -# SPDX-License-Identifier: Apache-2.0 -version: '2.1' - -volumes: - pgdata: - walletstore: - -networks: - byfn: - -services: - - explorerdb.mynetwork.com: - image: hyperledger/explorer-db:latest - container_name: explorerdb.mynetwork.com - hostname: explorerdb.mynetwork.com - environment: - - DATABASE_DATABASE=fabricexplorer - - DATABASE_USERNAME=hppoc - - DATABASE_PASSWORD=password - healthcheck: - test: "pg_isready -h localhost -p 5432 -q -U postgres" - interval: 30s - timeout: 10s - retries: 5 - volumes: - - pgdata:/var/lib/postgresql/data - networks: - - byfn - - explorer.mynetwork.com: - image: hyperledger/explorer:latest - container_name: explorer.mynetwork.com - hostname: explorer.mynetwork.com - environment: - - DATABASE_HOST=explorerdb.mynetwork.com - - DATABASE_DATABASE=fabricexplorer - - DATABASE_USERNAME=hppoc - - DATABASE_PASSWD=password - - LOG_LEVEL_APP=debug - - LOG_LEVEL_DB=debug - - LOG_LEVEL_CONSOLE=info - - LOG_CONSOLE_STDOUT=true - - DISCOVERY_AS_LOCALHOST=false - volumes: - - ./config.json:/opt/explorer/app/platform/fabric/config.json - - ./connection-profile:/opt/explorer/app/platform/fabric/connection-profile - - ../crypto-config:/tmp/crypto - - walletstore:/opt/explorer/wallet - ports: - - 8080:8080 - depends_on: - explorerdb.mynetwork.com: - condition: service_healthy - networks: - - byfn diff --git a/network/explorer/test-network.json b/network/explorer/test-network.json deleted file mode 100644 index 967d319..0000000 --- a/network/explorer/test-network.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "test-network", - "version": "1.0.0", - "client": { - "tlsEnable": true, - "adminCredential": { - "id": "admin", - "password": "password" - }, - "enableAuthentication": true, - "organization": "Org1MSP", - "connection": { - "timeout": { - "peer": { - "endorser": "300" - }, - "orderer": "300" - } - } - }, - "channels": { - "mychannel": { - "peers": { - "peer0.org1.example.com": {} - } - } - }, - "organizations": { - "Org1MSP": { - "mspid": "Org1MSP", - "adminPrivateKey": { - "path": "/tmp/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/06358ff75f0dcf60eeabd50b02e8641c987437f56ff527b1a778fe64260f2c1f_sk" - }, - "peers": [ - "peer0.org1.example.com" - ], - "signedCert": { - "path": "/tmp/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem" - } - } - }, - "peers": { - "peer0.org1.example.com": { - "tlsCACerts": { - "path": "/tmp/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" - }, - "url": "grpcs://peer0.org1.example.com:7051" - } - } -} diff --git a/server/src/gateway/networkConnection.yaml b/server/src/gateway/networkConnection.yaml index c6f57e4..cc41bdb 100644 --- a/server/src/gateway/networkConnection.yaml +++ b/server/src/gateway/networkConnection.yaml @@ -87,7 +87,6 @@ orderers: grpcOptions: ssl-target-name-override: orderer_n1 tlsCACerts: - path: ../network/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem # # List of peers to send various requests to, including endorsement, query @@ -101,8 +100,6 @@ peers: grpcOptions: ssl-target-name-override: peer0.org1.example.com request-timeout: 120001 - tlsCACerts: - path: ../network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem # Fabric-CA is a special kind of Certificate Authority provided by Hyperledger Fabric which allows # certificate management to be done via REST APIs. Application may choose to use a standard diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 24f5486..1b6a599 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -9,7 +9,7 @@ const studentRegistration = async (req, res) => { const ca = getCA(); const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); const mixin = X509WalletMixin.createIdentity( - 'Org1', + 'Org1MSP', adminData.certificate, adminData.key.toBytes() ); diff --git a/server/src/routes/record.js b/server/src/routes/record.js deleted file mode 100644 index c1e04e4..0000000 --- a/server/src/routes/record.js +++ /dev/null @@ -1,29 +0,0 @@ -import express from 'express'; -import { X509WalletMixin } from 'fabric-network'; -import { getCA, getConnectedWallet, sendTransaction } from '../utils'; - -const router = express.Router(); -const createStudentRecord = async (req, res) => { - const { certificate, privateKey } = req.body; - try { - const ca = getCA(); - const mixin = X509WalletMixin.createIdentity( - 'Org1', - certificate, - privateKey - ); - const gateway = await getConnectedWallet('client', mixin); - const result = await sendTransaction(gateway, { - name: 'createStudentRecord', - props: [], - }); - gateway.disconnect(); - res.status(201).json(result); - } - catch (e) { - res.status(400).json({ message: e.message }); - } -}; -router.post('/student', createStudentRecord); - -export default router; From a00a7176529e41663fd7e954473e8e87569ba782 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 3 Apr 2021 12:07:00 +0300 Subject: [PATCH 08/17] feat: create student's record and add subject --- .../src/contracts/student-records-storage.js | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/chaincode/src/contracts/student-records-storage.js b/chaincode/src/contracts/student-records-storage.js index 8efd828..126dc20 100644 --- a/chaincode/src/contracts/student-records-storage.js +++ b/chaincode/src/contracts/student-records-storage.js @@ -8,9 +8,38 @@ class StudentRecordsStorage extends Contract { super('org.fabric.studentRecordsStorage'); } - async createStudentRecord(ctx) { + async createStudentRecord(ctx, studentEmail, fullName) { const identity = new ClientIdentity(ctx.stub); + if(identity.cert.subject.organizationalUnitName !== 'admin'){ + throw new Error('Current subject is not have access to this function'); + } + const recordAsBytes = await ctx.stub.getState(studentEmail); + // if(!recordAsBytes || recordAsBytes.toString().length !== 0){ + // throw new Error('Student with the current email already exist'); + // } + const recordExample = { + fullName: fullName, + semesters: [] + } + const newRecordInBytes = Buffer.from(JSON.stringify(recordExample)); + await ctx.stub.putState(studentEmail, newRecordInBytes); + return JSON.stringify(recordExample, null, 2); + } + async addSubjectToStudentRecord(ctx, studentEmail, semesterNumber, subjectName) { + const identity = new ClientIdentity(ctx.stub); + if(identity.cert.subject.organizationalUnitName !== 'admin'){ + throw new Error('Current subject is not have access to this function'); + } + const recordAsBytes = await ctx.stub.getState(studentEmail); + const recordAsObject = JSON.parse(recordAsBytes.toString()); + recordAsObject.semesters[semesterNumber][subjectName] = { + lector: identity.cert.subject.commonName, + themes: [] + } + const newRecordInBytes = Buffer.from(JSON.stringify(recordAsObject)); + await ctx.stub.putState(studentEmail, newRecordInBytes); + return JSON.stringify(recordAsObject, null, 2); } } From 25769fdc2ec4405c0b1ec98dbee4014e93b077c6 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 10 Apr 2021 00:03:24 +0300 Subject: [PATCH 09/17] fix: fixed bug --- network/configtx.yaml | 2 +- server/src/gateway/cert.pem | 14 +++++++ server/src/gateway/networkConnection.yaml | 47 +++++++++++++++++++---- server/src/gateway/privateKey.pem | 5 +++ server/src/routes/auth.js | 4 +- server/src/routes/record.js | 43 +++++++++++++++++++++ server/src/utils/index.js | 8 ++-- 7 files changed, 107 insertions(+), 16 deletions(-) create mode 100644 server/src/gateway/cert.pem create mode 100644 server/src/gateway/privateKey.pem create mode 100644 server/src/routes/record.js diff --git a/network/configtx.yaml b/network/configtx.yaml index e8df309..630d1bf 100755 --- a/network/configtx.yaml +++ b/network/configtx.yaml @@ -60,7 +60,7 @@ Organizations: Rule: "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')" Writers: Type: Signature - Rule: "OR('Org1MSP.admin', 'Org1MSP.client')" + Rule: "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')" Admins: Type: Signature Rule: "OR('Org1MSP.admin')" diff --git a/server/src/gateway/cert.pem b/server/src/gateway/cert.pem new file mode 100644 index 0000000..8e0c90a --- /dev/null +++ b/server/src/gateway/cert.pem @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICKTCCAc+gAwIBAgIQTn6S2qGdc2v5QZDPCNk15TAKBggqhkjOPQQDAjBzMQsw +CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy +YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMTY2Eu +b3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5MDBa +MGsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1T +YW4gRnJhbmNpc2NvMQ4wDAYDVQQLEwVhZG1pbjEfMB0GA1UEAwwWQWRtaW5Ab3Jn +MS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNnvug5vljzY +4Lv++56mFILT/hIv5COA0fXGs/1Le7ZWhe0+LlOYCkyx74LosjJew55NU9t5pXqV +WageufPXX2WjTTBLMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1Ud +IwQkMCKAIMKW3AF+//QqKgHzNVIsNq4foUA5U7mjJ1WurlyRJcIpMAoGCCqGSM49 +BAMCA0gAMEUCIQD1Q+W54OgV2zwviCLx410c1Zt50oo7q+YdQb4FWEiDDgIgadx2 +hPJufDDeMoSbqFO8UrGey5q/veDBMJpDhc1NJOw= +-----END CERTIFICATE----- diff --git a/server/src/gateway/networkConnection.yaml b/server/src/gateway/networkConnection.yaml index cc41bdb..c967e1b 100644 --- a/server/src/gateway/networkConnection.yaml +++ b/server/src/gateway/networkConnection.yaml @@ -67,9 +67,8 @@ channels: # list of participating organizations in this network # organizations: - Org1: - mspid: Org1 - + Org1MSP: + mspid: Org1MSP peers: - peer0.org1.example.com @@ -80,13 +79,28 @@ organizations: # orderers: orderer_n1: - url: grpc://0.0.0.0:7050 - + url: grpc://192.168.88.85:7050 + "tlsCACerts": + "pem": | + -----BEGIN CERTIFICATE----- + MIICVzCCAf2gAwIBAgIQMgm0fjz4rB+98u8oxSjDRDAKBggqhkjOPQQDAjB2MQsw + CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy + YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz + Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5 + MDBaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH + Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmV4YW1wbGUuY29tMR8wHQYD + VQQDExZ0bHNjYS5vcmcxLmV4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0D + AQcDQgAEXy9jdYsUOIqp+Oh6va+zOWz86V2G12bJxMuTU3M/apyD2sFr/LKHaJFH + xs9ZNt3CCxR3yzKIZe3+Mu9TyjNj26NtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1Ud + JQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1Ud + DgQiBCCX75+3cdq0QWzcknD3o4bbsHIrQIqvOZqvx42ncnyHNjAKBggqhkjOPQQD + AgNIADBFAiEAlYyTxjIJCWA1AuAgJk1Gsp5o0uuPoCYex2GPY0h7VU8CIBHPE4UM + V0cf6nIKi/GPtzb414i/rRKs3mTsDJX+WdAQ + -----END CERTIFICATE----- # these are standard properties defined by the gRPC library # they will be passed in as-is to gRPC client constructor grpcOptions: ssl-target-name-override: orderer_n1 - tlsCACerts: # # List of peers to send various requests to, including endorsement, query @@ -95,7 +109,24 @@ orderers: peers: peer0.org1.example.com: # this URL is used to send endorsement and query requests - url: grpc://0.0.0.0:7051 + url: grpcs://192.168.88.85:7051 + "tlsCACerts": + "pem": | + -----BEGIN CERTIFICATE----- + MIICVzCCAf2gAwIBAgIQMgm0fjz4rB+98u8oxSjDRDAKBggqhkjOPQQDAjB2MQsw + CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy + YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz + Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5 + MDBaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH + Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmV4YW1wbGUuY29tMR8wHQYD + VQQDExZ0bHNjYS5vcmcxLmV4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0D + AQcDQgAEXy9jdYsUOIqp+Oh6va+zOWz86V2G12bJxMuTU3M/apyD2sFr/LKHaJFH + xs9ZNt3CCxR3yzKIZe3+Mu9TyjNj26NtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1Ud + JQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1Ud + DgQiBCCX75+3cdq0QWzcknD3o4bbsHIrQIqvOZqvx42ncnyHNjAKBggqhkjOPQQD + AgNIADBFAiEAlYyTxjIJCWA1AuAgJk1Gsp5o0uuPoCYex2GPY0h7VU8CIBHPE4UM + V0cf6nIKi/GPtzb414i/rRKs3mTsDJX+WdAQ + -----END CERTIFICATE----- grpcOptions: ssl-target-name-override: peer0.org1.example.com @@ -107,7 +138,7 @@ peers: # certificateAuthorities: ca-org1: - url: http://0.0.0.0:7054 + url: http://192.168.88.85:7054 # the properties specified under this object are passed to the 'http' client verbatim when # making the request to the Fabric-CA server httpOptions: diff --git a/server/src/gateway/privateKey.pem b/server/src/gateway/privateKey.pem new file mode 100644 index 0000000..d0f71a4 --- /dev/null +++ b/server/src/gateway/privateKey.pem @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg5HdKWVWU/uzNgK0P +BJ41XmeqmIIxOZ6LWBxaUiTbIJShRANCAATZ77oOb5Y82OC7/vuephSC0/4SL+Qj +gNH1xrP9S3u2VoXtPi5TmApMse+C6LIyXsOeTVPbeaV6lVmoHrnz119l +-----END PRIVATE KEY----- diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 1b6a599..684e03e 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -9,11 +9,11 @@ const studentRegistration = async (req, res) => { const ca = getCA(); const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); const mixin = X509WalletMixin.createIdentity( - 'Org1MSP', + 'Org1', adminData.certificate, adminData.key.toBytes() ); - const gateway = await getConnectedWallet('client', mixin); + const gateway = await getConnectedWallet('Org1MSP', mixin); const admin = await gateway.getCurrentIdentity() await registerUser(ca, admin, { login, password, affiliation: 'student' }); diff --git a/server/src/routes/record.js b/server/src/routes/record.js new file mode 100644 index 0000000..6c983d3 --- /dev/null +++ b/server/src/routes/record.js @@ -0,0 +1,43 @@ +import express from 'express'; +import { getCA, getConnectedWallet, sendTransaction } from '../utils'; +import { X509WalletMixin } from 'fabric-network'; +import fs from 'fs'; +import path from 'path'; + +const router = express.Router(); +const test = async (req, res) => { + // const { certificate, privateKey } = req.body; + const certificate = fs.readFileSync(path.resolve(__dirname, '../gateway/cert.pem'), 'utf8'); + const privateKey = fs.readFileSync(path.resolve(__dirname, '../gateway/privateKey.pem'), 'utf8'); + console.log(certificate) + console.log(privateKey) + // const certificate = "-----BEGIN CERTIFICATE-----MIICKTCCAc+gAwIBAgIQTn6S2qGdc2v5QZDPCNk15TAKBggqhkjOPQQDAjBzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMTY2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5MDBaMGsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMQ4wDAYDVQQLEwVhZG1pbjEfMB0GA1UEAwwWQWRtaW5Ab3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNnvug5vljzY4Lv++56mFILT/hIv5COA0fXGs/1Le7ZWhe0+LlOYCkyx74LosjJew55NU9t5pXqVWageufPXX2WjTTBLMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIMKW3AF+//QqKgHzNVIsNq4foUA5U7mjJ1WurlyRJcIpMAoGCCqGSM49BAMCA0gAMEUCIQD1Q+W54OgV2zwviCLx410c1Zt50oo7q+YdQb4FWEiDDgIgadx2hPJufDDeMoSbqFO8UrGey5q/veDBMJpDhc1NJOw=-----END CERTIFICATE-----"; + // const privateKey = "-----BEGIN PRIVATE KEY-----MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg5HdKWVWU/uzNgK0PBJ41XmeqmIIxOZ6LWBxaUiTbIJShRANCAATZ77oOb5Y82OC7/vuephSC0/4SL+QjgNH1xrP9S3u2VoXtPi5TmApMse+C6LIyXsOeTVPbeaV6lVmoHrnz119l-----END PRIVATE KEY-----"; + try { + // const ca = getCA(); + // const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); + // const mixin = X509WalletMixin.createIdentity( + // 'Org1MSP', + // adminData.certificate, + // adminData.key.toBytes() + // ); + const mixin = X509WalletMixin.createIdentity( + 'Org1MSP', + certificate, + privateKey + ); + const gateway = await getConnectedWallet('Org1MSP', mixin); + const result = await sendTransaction(gateway, { + name: 'test', + props: ["20"], + }) + console.log(result) + gateway.disconnect(); + } + catch (e) { + res.status(400).json({ message: e.message }); + } +}; +router.get('/test', test); + +export default router; diff --git a/server/src/utils/index.js b/server/src/utils/index.js index cfc3729..654a8b4 100644 --- a/server/src/utils/index.js +++ b/server/src/utils/index.js @@ -6,7 +6,7 @@ import yaml from 'js-yaml'; export const getCA = () =>{ try { - return new FabricCAService(`http://192.168.88.88:7054`) + return new FabricCAService(`http://192.168.88.85:7054`) }catch (e){ console.error(e) throw new Error(e.message) @@ -22,7 +22,7 @@ export const getConnectedWallet = async (label, mixin) => { const connectionOptions = { identity: label, wallet, - discovery: { enabled: true, asLocalhost: true }, + discovery: { enabled: false, asLocalhost: true }, }; await gateway.connect(connectionProfile, connectionOptions); return gateway; @@ -32,7 +32,7 @@ export const registerUser = async (ca, adminWallet, userData) => { await ca.register({ enrollmentID: userData.login, enrollmentSecret: userData.password, - role: 'peer', + role: 'client', affiliation: `org1.${userData.affiliation}`, maxEnrollments: -1, }, adminWallet); @@ -45,8 +45,6 @@ export const registerUser = async (ca, adminWallet, userData) => { export const sendTransaction = async(gateway, transaction) => { try { - // console.log(await gateway.getChannel()) - const network = await gateway.getNetwork('testchannel'); const contract = await network.getContract('recordcontract', 'org.fabric.studentRecordsStorage'); From 272e7758e2fae167a0c62ef103352526ecd418e3 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 10 Apr 2021 02:44:03 +0300 Subject: [PATCH 10/17] fix: fixed bug --- network/base/docker-compose-base.yaml | 37 ++++++--------- network/base/docker-compose-ca.yaml | 26 +++++++++++ network/docker-compose-ca.yaml | 22 +++++++++ network/docker-compose.yaml | 20 ++------ server/src/gateway/caAdmin/cert.pem | 15 ++++++ server/src/gateway/caAdmin/privateKey.pem | 5 ++ server/src/gateway/cert.pem | 16 +++---- server/src/gateway/networkConnection.yaml | 57 ++++++++++++----------- server/src/gateway/privateKey.pem | 6 +-- server/src/routes/auth.js | 14 ++++-- server/src/routes/record.js | 10 ++-- server/src/utils/index.js | 1 + 12 files changed, 142 insertions(+), 87 deletions(-) create mode 100755 network/base/docker-compose-ca.yaml create mode 100755 network/docker-compose-ca.yaml create mode 100644 server/src/gateway/caAdmin/cert.pem create mode 100644 server/src/gateway/caAdmin/privateKey.pem diff --git a/network/base/docker-compose-base.yaml b/network/base/docker-compose-base.yaml index 1117d4d..1f5b0e0 100755 --- a/network/base/docker-compose-base.yaml +++ b/network/base/docker-compose-base.yaml @@ -7,27 +7,16 @@ version: '2' services: - ca.org1.example.com: - container_name: ca.org1.example.com - image: hyperledger/fabric-ca:1.4 - environment: - - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server - volumes: - - ../ca:/etc/hyperledger/fabric-ca-server - ports: - - 7054:7054 - command: "fabric-ca-server start" - orderer.example.com: container_name: orderer.example.com extends: file: peer-base.yaml service: orderer-base volumes: - - ../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 + - ../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 @@ -46,10 +35,10 @@ services: - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051 - CORE_PEER_LOCALMSPID=Org1MSP volumes: - - /var/run/:/host/var/run/ - - ../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 + - /var/run/:/host/var/run/ + - ../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 @@ -68,10 +57,10 @@ services: - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org1.example.com:7051 - CORE_PEER_LOCALMSPID=Org1MSP volumes: - - /var/run/:/host/var/run/ - - ../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 + - /var/run/:/host/var/run/ + - ../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:8051 \ No newline at end of file + - 8051:8051 diff --git a/network/base/docker-compose-ca.yaml b/network/base/docker-compose-ca.yaml new file mode 100755 index 0000000..d9cccd9 --- /dev/null +++ b/network/base/docker-compose-ca.yaml @@ -0,0 +1,26 @@ +# Copyright IBM Corp. All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# + +version: '2' + +services: + + ca.org1.example.com: + container_name: ca.org1.example.com + image: hyperledger/fabric-ca:1.4 + environment: + - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server + - FABRIC_CA_SERVER_CA_NAME=ca.org1.example.com + - FABRIC_CA_SERVER_CA_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org1.example.com-cert.pem + - FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/8ddc8a5bd63d60c2df8dcea1b024e42a3084033065b8429877784c723f7a289c_sk + - 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/8ddc8a5bd63d60c2df8dcea1b024e42a3084033065b8429877784c723f7a289c_sk + volumes: + - ../crypto-config/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config + - ../crypto-config/peerOrganizations/org1.example.com/tlsca/:/etc/hyperledger/fabric-ca-server-tls + ports: + - 7054:7054 + command: "sh -c 'fabric-ca-server start -b admin:password -d" diff --git a/network/docker-compose-ca.yaml b/network/docker-compose-ca.yaml new file mode 100755 index 0000000..9197984 --- /dev/null +++ b/network/docker-compose-ca.yaml @@ -0,0 +1,22 @@ +# Copyright IBM Corp. All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# + +version: '2' + +volumes: + ca.org1.example.com: + +networks: + byfn: + +services: + + ca.org1.example.com: + extends: + file: base/docker-compose-ca.yaml + service: ca.org1.example.com + container_name: ca.org1.example.com + networks: + - byfn diff --git a/network/docker-compose.yaml b/network/docker-compose.yaml index b09791d..2a314a4 100755 --- a/network/docker-compose.yaml +++ b/network/docker-compose.yaml @@ -6,7 +6,6 @@ version: '2' volumes: - ca.org1.example.com: orderer.example.com: peer0.org1.example.com: peer1.org1.example.com: @@ -16,14 +15,6 @@ networks: services: - ca.org1.example.com: - extends: - file: base/docker-compose-base.yaml - service: ca.org1.example.com - container_name: ca.org1.example.com - networks: - - byfn - orderer.example.com: extends: file: base/docker-compose-base.yaml @@ -70,14 +61,13 @@ services: working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer command: /bin/bash volumes: - - /var/run/:/host/var/run/ - - ./../chaincode/:/opt/gopath/src/github.com/chaincode - - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ - - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts + - /var/run/:/host/var/run/ + - ./../chaincode/:/opt/gopath/src/github.com/chaincode + - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ + - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts depends_on: - - ca.org1.example.com - orderer.example.com - peer0.org1.example.com - peer1.org1.example.com networks: - - byfn \ No newline at end of file + - byfn diff --git a/server/src/gateway/caAdmin/cert.pem b/server/src/gateway/caAdmin/cert.pem new file mode 100644 index 0000000..2e1ce36 --- /dev/null +++ b/server/src/gateway/caAdmin/cert.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICUjCCAfigAwIBAgIRAPWpfynCkvueEy/YGAycqzcwCgYIKoZIzj0EAwIwczEL +MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG +cmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh +Lm9yZzEuZXhhbXBsZS5jb20wHhcNMjEwNDA5MjE1MjAwWhcNMzEwNDA3MjE1MjAw +WjBzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN +U2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UE +AxMTY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA +BEn4BEHnBHryAemgMPZjkcRLulHGDm2PoOkP2Q2YHt0Tfya5hmB6TSSlMbWNRCfM +xdWcgQrOiNMssoWsJEHjGVGjbTBrMA4GA1UdDwEB/wQEAwIBpjAdBgNVHSUEFjAU +BggrBgEFBQcDAgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUwAwEB/zApBgNVHQ4EIgQg +lwOZEagGAVfGhdtd6B1XlRSqxnqacESX6LXacDcTMr0wCgYIKoZIzj0EAwIDSAAw +RQIhAP8vTXi+LvrY6T9ICEyx4am06A3oZVnLrZ4lTMBYe8LGAiA4tNm28MkGY17b +mTqoOENC4XK44AzcY7WFGq9xstpv2g== +-----END CERTIFICATE----- diff --git a/server/src/gateway/caAdmin/privateKey.pem b/server/src/gateway/caAdmin/privateKey.pem new file mode 100644 index 0000000..475e846 --- /dev/null +++ b/server/src/gateway/caAdmin/privateKey.pem @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgT4WTsytKF+ZqNj89 +P3pMBfQXmdYOgCYoeUl+CTsQvOyhRANCAARJ+ARB5wR68gHpoDD2Y5HES7pRxg5t +j6DpD9kNmB7dE38muYZgek0kpTG1jUQnzMXVnIEKzojTLLKFrCRB4xlR +-----END PRIVATE KEY----- diff --git a/server/src/gateway/cert.pem b/server/src/gateway/cert.pem index 8e0c90a..a6c1646 100644 --- a/server/src/gateway/cert.pem +++ b/server/src/gateway/cert.pem @@ -1,14 +1,14 @@ -----BEGIN CERTIFICATE----- -MIICKTCCAc+gAwIBAgIQTn6S2qGdc2v5QZDPCNk15TAKBggqhkjOPQQDAjBzMQsw +MIICKTCCAc+gAwIBAgIQW5um9wHaxIQQ2V9Eg5Vf2DAKBggqhkjOPQQDAjBzMQsw CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMTY2Eu -b3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5MDBa +b3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMTUyMDBaFw0zMTA0MDcyMTUyMDBa MGsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1T YW4gRnJhbmNpc2NvMQ4wDAYDVQQLEwVhZG1pbjEfMB0GA1UEAwwWQWRtaW5Ab3Jn -MS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNnvug5vljzY -4Lv++56mFILT/hIv5COA0fXGs/1Le7ZWhe0+LlOYCkyx74LosjJew55NU9t5pXqV -WageufPXX2WjTTBLMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1Ud -IwQkMCKAIMKW3AF+//QqKgHzNVIsNq4foUA5U7mjJ1WurlyRJcIpMAoGCCqGSM49 -BAMCA0gAMEUCIQD1Q+W54OgV2zwviCLx410c1Zt50oo7q+YdQb4FWEiDDgIgadx2 -hPJufDDeMoSbqFO8UrGey5q/veDBMJpDhc1NJOw= +MS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD1UwBXoqXL6 +YBjaK0Z4z+CkznD/b7Yq0FaECEHX4q2i7FwwK3ohoIy184auzP1BI1eNNCcIkwZi +W1NiKm+BpQKjTTBLMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1Ud +IwQkMCKAIJcDmRGoBgFXxoXbXegdV5UUqsZ6mnBEl+i12nA3EzK9MAoGCCqGSM49 +BAMCA0gAMEUCIQCoYS1DCi5/2m0OZecp6aY4LtcxNzNqwmtvgGVZWrwoFgIgC0VF +FbVKfmlCBlYQliun19MhbVGYHyGvLvnKRx7UGEE= -----END CERTIFICATE----- diff --git a/server/src/gateway/networkConnection.yaml b/server/src/gateway/networkConnection.yaml index c967e1b..3caf757 100644 --- a/server/src/gateway/networkConnection.yaml +++ b/server/src/gateway/networkConnection.yaml @@ -39,7 +39,7 @@ channels: # operational decisions to share loads from applications among the orderers. The values must # be "names" of orgs defined under "organizations/peers" orderers: - - orderer + - orderer.example.com # Required. list of peers from participating orgs peers: @@ -78,29 +78,30 @@ organizations: # SDK is implementation specific. Consult each SDK's documentation for its handling of orderers. # orderers: - orderer_n1: - url: grpc://192.168.88.85:7050 - "tlsCACerts": - "pem": | - -----BEGIN CERTIFICATE----- - MIICVzCCAf2gAwIBAgIQMgm0fjz4rB+98u8oxSjDRDAKBggqhkjOPQQDAjB2MQsw - CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy - YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz - Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5 - MDBaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH - Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmV4YW1wbGUuY29tMR8wHQYD - VQQDExZ0bHNjYS5vcmcxLmV4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0D - AQcDQgAEXy9jdYsUOIqp+Oh6va+zOWz86V2G12bJxMuTU3M/apyD2sFr/LKHaJFH - xs9ZNt3CCxR3yzKIZe3+Mu9TyjNj26NtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1Ud - JQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1Ud - DgQiBCCX75+3cdq0QWzcknD3o4bbsHIrQIqvOZqvx42ncnyHNjAKBggqhkjOPQQD - AgNIADBFAiEAlYyTxjIJCWA1AuAgJk1Gsp5o0uuPoCYex2GPY0h7VU8CIBHPE4UM - V0cf6nIKi/GPtzb414i/rRKs3mTsDJX+WdAQ - -----END CERTIFICATE----- + orderer.example.com: + url: grpcs://192.168.88.85:7050 # these are standard properties defined by the gRPC library # they will be passed in as-is to gRPC client constructor + tlsCACerts: + pem: | + -----BEGIN CERTIFICATE----- + MIICRDCCAeqgAwIBAgIRAOlpSSH8njFZb3K9eUZ2AfwwCgYIKoZIzj0EAwIwbDEL + MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG + cmFuY2lzY28xFDASBgNVBAoTC2V4YW1wbGUuY29tMRowGAYDVQQDExF0bHNjYS5l + eGFtcGxlLmNvbTAeFw0yMTA0MDkyMTUyMDBaFw0zMTA0MDcyMTUyMDBaMGwxCzAJ + BgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJh + bmNpc2NvMRQwEgYDVQQKEwtleGFtcGxlLmNvbTEaMBgGA1UEAxMRdGxzY2EuZXhh + bXBsZS5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARObm10VDeDJSK9wu85 + UAvbqg4w3Tu6s3Em00qOArx32EWdMfa5XEF7Pu47ih4ncPieAmyVAXLvitzMfiNQ + 9woio20wazAOBgNVHQ8BAf8EBAMCAaYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsG + AQUFBwMBMA8GA1UdEwEB/wQFMAMBAf8wKQYDVR0OBCIEIGT0A4Jr0v5RIkloRJrX + IHsX+qtTWr6msV12Y6bPeABaMAoGCCqGSM49BAMCA0gAMEUCIQD8k8jsc9MFsYdK + FUkF8HyhbXgWC9VXUzdENAxpgIdOHAIgUnidpZCOAt3O9Up0hEC2tOCdHcIMLTR+ + em9jgcU46Kw= + -----END CERTIFICATE----- + grpcOptions: - ssl-target-name-override: orderer_n1 + ssl-target-name-override: orderer.example.com # # List of peers to send various requests to, including endorsement, query @@ -113,19 +114,19 @@ peers: "tlsCACerts": "pem": | -----BEGIN CERTIFICATE----- - MIICVzCCAf2gAwIBAgIQMgm0fjz4rB+98u8oxSjDRDAKBggqhkjOPQQDAjB2MQsw + MIICVjCCAf2gAwIBAgIQDfHCgOBKptyRG4OID6pNdDAKBggqhkjOPQQDAjB2MQsw CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz - Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5 + Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMTUyMDBaFw0zMTA0MDcyMTUy MDBaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmV4YW1wbGUuY29tMR8wHQYD VQQDExZ0bHNjYS5vcmcxLmV4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0D - AQcDQgAEXy9jdYsUOIqp+Oh6va+zOWz86V2G12bJxMuTU3M/apyD2sFr/LKHaJFH - xs9ZNt3CCxR3yzKIZe3+Mu9TyjNj26NtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1Ud + AQcDQgAEobO4XVzgQt5WEzoyWSsAWq/11HKuMYP3eDsInxn4+C/t9YOME36LkALe + sOfhQJMzA8a5GSlVjRSLCW5tmSs0IqNtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1Ud JQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1Ud - DgQiBCCX75+3cdq0QWzcknD3o4bbsHIrQIqvOZqvx42ncnyHNjAKBggqhkjOPQQD - AgNIADBFAiEAlYyTxjIJCWA1AuAgJk1Gsp5o0uuPoCYex2GPY0h7VU8CIBHPE4UM - V0cf6nIKi/GPtzb414i/rRKs3mTsDJX+WdAQ + DgQiBCDiaKbL+LTkb/pjrVrPqJXXROL+vtrrVU04Fmn9JLy1LTAKBggqhkjOPQQD + AgNHADBEAiANZY3TVyDL4fSPs5rwN0ZxcFRdnl1nP16DMqeyB4dZwAIgQzWJXXOw + OPogeUshmqftxx5kdWs3/hL+bLcNM7mXizs= -----END CERTIFICATE----- grpcOptions: diff --git a/server/src/gateway/privateKey.pem b/server/src/gateway/privateKey.pem index d0f71a4..12a0770 100644 --- a/server/src/gateway/privateKey.pem +++ b/server/src/gateway/privateKey.pem @@ -1,5 +1,5 @@ -----BEGIN PRIVATE KEY----- -MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg5HdKWVWU/uzNgK0P -BJ41XmeqmIIxOZ6LWBxaUiTbIJShRANCAATZ77oOb5Y82OC7/vuephSC0/4SL+Qj -gNH1xrP9S3u2VoXtPi5TmApMse+C6LIyXsOeTVPbeaV6lVmoHrnz119l +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgj7n8a1aUVOpdWgwk +9+jbfccgxY5c9TUXIrGnUcYsnzihRANCAAQ9VMAV6Kly+mAY2itGeM/gpM5w/2+2 +KtBWhAhB1+KtouxcMCt6IaCMtfOGrsz9QSNXjTQnCJMGYltTYipvgaUC -----END PRIVATE KEY----- diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 684e03e..6a6a3db 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -1,17 +1,23 @@ import express from 'express'; import { X509WalletMixin } from 'fabric-network'; import { getCA, getConnectedWallet, registerUser } from '../utils'; +import fs from 'fs'; +import path from 'path'; const router = express.Router(); const studentRegistration = async (req, res) => { const { login, password } = req.body; try { const ca = getCA(); - const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); + // const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); + const adminCertificate = fs.readFileSync(path.resolve(__dirname, '../gateway/caAdmin/cert.pem'), 'utf8'); + const adminPrivateKey = fs.readFileSync(path.resolve(__dirname, '../gateway/caAdmin/privateKey.pem'), 'utf8'); + console.log(adminCertificate) + console.log(adminPrivateKey) const mixin = X509WalletMixin.createIdentity( - 'Org1', - adminData.certificate, - adminData.key.toBytes() + 'Org1MSP', + adminCertificate, + adminPrivateKey ); const gateway = await getConnectedWallet('Org1MSP', mixin); const admin = await gateway.getCurrentIdentity() diff --git a/server/src/routes/record.js b/server/src/routes/record.js index 6c983d3..783ac49 100644 --- a/server/src/routes/record.js +++ b/server/src/routes/record.js @@ -6,9 +6,9 @@ import path from 'path'; const router = express.Router(); const test = async (req, res) => { - // const { certificate, privateKey } = req.body; - const certificate = fs.readFileSync(path.resolve(__dirname, '../gateway/cert.pem'), 'utf8'); - const privateKey = fs.readFileSync(path.resolve(__dirname, '../gateway/privateKey.pem'), 'utf8'); + const { certificate, privateKey } = req.body; + // const certificate = fs.readFileSync(path.resolve(__dirname, '../gateway/cert.pem'), 'utf8'); + // const privateKey = fs.readFileSync(path.resolve(__dirname, '../gateway/privateKey.pem'), 'utf8'); console.log(certificate) console.log(privateKey) // const certificate = "-----BEGIN CERTIFICATE-----MIICKTCCAc+gAwIBAgIQTn6S2qGdc2v5QZDPCNk15TAKBggqhkjOPQQDAjBzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMTY2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5MDBaMGsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMQ4wDAYDVQQLEwVhZG1pbjEfMB0GA1UEAwwWQWRtaW5Ab3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNnvug5vljzY4Lv++56mFILT/hIv5COA0fXGs/1Le7ZWhe0+LlOYCkyx74LosjJew55NU9t5pXqVWageufPXX2WjTTBLMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIMKW3AF+//QqKgHzNVIsNq4foUA5U7mjJ1WurlyRJcIpMAoGCCqGSM49BAMCA0gAMEUCIQD1Q+W54OgV2zwviCLx410c1Zt50oo7q+YdQb4FWEiDDgIgadx2hPJufDDeMoSbqFO8UrGey5q/veDBMJpDhc1NJOw=-----END CERTIFICATE-----"; @@ -29,9 +29,9 @@ const test = async (req, res) => { const gateway = await getConnectedWallet('Org1MSP', mixin); const result = await sendTransaction(gateway, { name: 'test', - props: ["20"], + props: ["198"], }) - console.log(result) + res.status(200).json({ data: result }); gateway.disconnect(); } catch (e) { diff --git a/server/src/utils/index.js b/server/src/utils/index.js index 654a8b4..1e63a18 100644 --- a/server/src/utils/index.js +++ b/server/src/utils/index.js @@ -50,6 +50,7 @@ export const sendTransaction = async(gateway, transaction) => { 'org.fabric.studentRecordsStorage'); const issueResponse = await contract.submitTransaction(transaction.name, ...transaction.props); return JSON.parse(issueResponse.toString()); + // return true; } catch (error) { console.log(`Error processing transaction. ${error.stack}`); From 157de635200f258038c29b4e5166ef1631a2f73d Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 10 Apr 2021 02:44:56 +0300 Subject: [PATCH 11/17] fix: fixed bug --- chaincode/src/contracts/student-records-storage.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/chaincode/src/contracts/student-records-storage.js b/chaincode/src/contracts/student-records-storage.js index 126dc20..260f208 100644 --- a/chaincode/src/contracts/student-records-storage.js +++ b/chaincode/src/contracts/student-records-storage.js @@ -8,9 +8,13 @@ class StudentRecordsStorage extends Contract { super('org.fabric.studentRecordsStorage'); } + async test(ctx, val) { + return +val * 2; + } + async createStudentRecord(ctx, studentEmail, fullName) { const identity = new ClientIdentity(ctx.stub); - if(identity.cert.subject.organizationalUnitName !== 'admin'){ + if (identity.cert.subject.organizationalUnitName !== 'admin') { throw new Error('Current subject is not have access to this function'); } const recordAsBytes = await ctx.stub.getState(studentEmail); @@ -28,7 +32,7 @@ class StudentRecordsStorage extends Contract { async addSubjectToStudentRecord(ctx, studentEmail, semesterNumber, subjectName) { const identity = new ClientIdentity(ctx.stub); - if(identity.cert.subject.organizationalUnitName !== 'admin'){ + if (identity.cert.subject.organizationalUnitName !== 'admin') { throw new Error('Current subject is not have access to this function'); } const recordAsBytes = await ctx.stub.getState(studentEmail); From 5b2270f5e31331812b2a0bb8daf50e1c584d20bb Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 10 Apr 2021 03:48:35 +0300 Subject: [PATCH 12/17] fix: fixed bug --- network/base/docker-compose-base.yaml | 16 +++++++ network/base/docker-compose-ca.yaml | 2 +- network/docker-compose.yaml | 10 +++++ server/src/gateway/caAdmin/cert.pem | 15 ------- server/src/gateway/caAdmin/privateKey.pem | 5 --- server/src/gateway/cert.pem | 14 ------ server/src/gateway/networkConnection.yaml | 53 ++++++++++++----------- server/src/gateway/privateKey.pem | 5 --- server/src/routes/auth.js | 12 ++--- server/src/routes/record.js | 27 +++--------- server/src/utils/index.js | 2 +- 11 files changed, 64 insertions(+), 97 deletions(-) delete mode 100644 server/src/gateway/caAdmin/cert.pem delete mode 100644 server/src/gateway/caAdmin/privateKey.pem delete mode 100644 server/src/gateway/cert.pem delete mode 100644 server/src/gateway/privateKey.pem diff --git a/network/base/docker-compose-base.yaml b/network/base/docker-compose-base.yaml index 1f5b0e0..af10cce 100755 --- a/network/base/docker-compose-base.yaml +++ b/network/base/docker-compose-base.yaml @@ -7,6 +7,22 @@ version: '2' services: + ca.org1.example.com: + container_name: ca.org1.example.com + image: hyperledger/fabric-ca:1.4 + environment: + - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server + - FABRIC_CA_SERVER_CA_NAME=ca.org1.example.com + - FABRIC_CA_SERVER_CA_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org1.example.com-cert.pem + - FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/e5ff1ec118c67c202acb265a6704aa521cdeb2ee15ee2cc10d374c37148c8305_sk + volumes: + - ../ca:/etc/hyperledger/fabric-ca-server + - ../crypto-config/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config + - ../crypto-config/peerOrganizations/org1.example.com/tlsca/:/etc/hyperledger/fabric-ca-server-tls + ports: + - 7054:7054 + command: "sh -c 'fabric-ca-server start -b admin:password -d'" + orderer.example.com: container_name: orderer.example.com extends: diff --git a/network/base/docker-compose-ca.yaml b/network/base/docker-compose-ca.yaml index d9cccd9..d16ad8f 100755 --- a/network/base/docker-compose-ca.yaml +++ b/network/base/docker-compose-ca.yaml @@ -23,4 +23,4 @@ services: - ../crypto-config/peerOrganizations/org1.example.com/tlsca/:/etc/hyperledger/fabric-ca-server-tls ports: - 7054:7054 - command: "sh -c 'fabric-ca-server start -b admin:password -d" + command: "sh -c 'fabric-ca-server start -b admin:password -d'" diff --git a/network/docker-compose.yaml b/network/docker-compose.yaml index 2a314a4..26bb45c 100755 --- a/network/docker-compose.yaml +++ b/network/docker-compose.yaml @@ -6,6 +6,7 @@ version: '2' volumes: + ca.org1.example.com: orderer.example.com: peer0.org1.example.com: peer1.org1.example.com: @@ -15,6 +16,14 @@ networks: services: + ca.org1.example.com: + extends: + file: base/docker-compose-ca.yaml + service: ca.org1.example.com + container_name: ca.org1.example.com + networks: + - byfn + orderer.example.com: extends: file: base/docker-compose-base.yaml @@ -66,6 +75,7 @@ services: - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts depends_on: + - ca.org1.example.com - orderer.example.com - peer0.org1.example.com - peer1.org1.example.com diff --git a/server/src/gateway/caAdmin/cert.pem b/server/src/gateway/caAdmin/cert.pem deleted file mode 100644 index 2e1ce36..0000000 --- a/server/src/gateway/caAdmin/cert.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICUjCCAfigAwIBAgIRAPWpfynCkvueEy/YGAycqzcwCgYIKoZIzj0EAwIwczEL -MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG -cmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh -Lm9yZzEuZXhhbXBsZS5jb20wHhcNMjEwNDA5MjE1MjAwWhcNMzEwNDA3MjE1MjAw -WjBzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN -U2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UE -AxMTY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA -BEn4BEHnBHryAemgMPZjkcRLulHGDm2PoOkP2Q2YHt0Tfya5hmB6TSSlMbWNRCfM -xdWcgQrOiNMssoWsJEHjGVGjbTBrMA4GA1UdDwEB/wQEAwIBpjAdBgNVHSUEFjAU -BggrBgEFBQcDAgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUwAwEB/zApBgNVHQ4EIgQg -lwOZEagGAVfGhdtd6B1XlRSqxnqacESX6LXacDcTMr0wCgYIKoZIzj0EAwIDSAAw -RQIhAP8vTXi+LvrY6T9ICEyx4am06A3oZVnLrZ4lTMBYe8LGAiA4tNm28MkGY17b -mTqoOENC4XK44AzcY7WFGq9xstpv2g== ------END CERTIFICATE----- diff --git a/server/src/gateway/caAdmin/privateKey.pem b/server/src/gateway/caAdmin/privateKey.pem deleted file mode 100644 index 475e846..0000000 --- a/server/src/gateway/caAdmin/privateKey.pem +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgT4WTsytKF+ZqNj89 -P3pMBfQXmdYOgCYoeUl+CTsQvOyhRANCAARJ+ARB5wR68gHpoDD2Y5HES7pRxg5t -j6DpD9kNmB7dE38muYZgek0kpTG1jUQnzMXVnIEKzojTLLKFrCRB4xlR ------END PRIVATE KEY----- diff --git a/server/src/gateway/cert.pem b/server/src/gateway/cert.pem deleted file mode 100644 index a6c1646..0000000 --- a/server/src/gateway/cert.pem +++ /dev/null @@ -1,14 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICKTCCAc+gAwIBAgIQW5um9wHaxIQQ2V9Eg5Vf2DAKBggqhkjOPQQDAjBzMQsw -CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy -YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMTY2Eu -b3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMTUyMDBaFw0zMTA0MDcyMTUyMDBa -MGsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1T -YW4gRnJhbmNpc2NvMQ4wDAYDVQQLEwVhZG1pbjEfMB0GA1UEAwwWQWRtaW5Ab3Jn -MS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD1UwBXoqXL6 -YBjaK0Z4z+CkznD/b7Yq0FaECEHX4q2i7FwwK3ohoIy184auzP1BI1eNNCcIkwZi -W1NiKm+BpQKjTTBLMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1Ud -IwQkMCKAIJcDmRGoBgFXxoXbXegdV5UUqsZ6mnBEl+i12nA3EzK9MAoGCCqGSM49 -BAMCA0gAMEUCIQCoYS1DCi5/2m0OZecp6aY4LtcxNzNqwmtvgGVZWrwoFgIgC0VF -FbVKfmlCBlYQliun19MhbVGYHyGvLvnKRx7UGEE= ------END CERTIFICATE----- diff --git a/server/src/gateway/networkConnection.yaml b/server/src/gateway/networkConnection.yaml index 3caf757..9df4045 100644 --- a/server/src/gateway/networkConnection.yaml +++ b/server/src/gateway/networkConnection.yaml @@ -85,21 +85,22 @@ orderers: tlsCACerts: pem: | -----BEGIN CERTIFICATE----- - MIICRDCCAeqgAwIBAgIRAOlpSSH8njFZb3K9eUZ2AfwwCgYIKoZIzj0EAwIwbDEL - MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG - cmFuY2lzY28xFDASBgNVBAoTC2V4YW1wbGUuY29tMRowGAYDVQQDExF0bHNjYS5l - eGFtcGxlLmNvbTAeFw0yMTA0MDkyMTUyMDBaFw0zMTA0MDcyMTUyMDBaMGwxCzAJ - BgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJh - bmNpc2NvMRQwEgYDVQQKEwtleGFtcGxlLmNvbTEaMBgGA1UEAxMRdGxzY2EuZXhh - bXBsZS5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARObm10VDeDJSK9wu85 - UAvbqg4w3Tu6s3Em00qOArx32EWdMfa5XEF7Pu47ih4ncPieAmyVAXLvitzMfiNQ - 9woio20wazAOBgNVHQ8BAf8EBAMCAaYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsG - AQUFBwMBMA8GA1UdEwEB/wQFMAMBAf8wKQYDVR0OBCIEIGT0A4Jr0v5RIkloRJrX - IHsX+qtTWr6msV12Y6bPeABaMAoGCCqGSM49BAMCA0gAMEUCIQD8k8jsc9MFsYdK - FUkF8HyhbXgWC9VXUzdENAxpgIdOHAIgUnidpZCOAt3O9Up0hEC2tOCdHcIMLTR+ - em9jgcU46Kw= + MIICQjCCAemgAwIBAgIQdrfZ1pyvqnT3U+zfreYLATAKBggqhkjOPQQDAjBsMQsw + CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy + YW5jaXNjbzEUMBIGA1UEChMLZXhhbXBsZS5jb20xGjAYBgNVBAMTEXRsc2NhLmV4 + YW1wbGUuY29tMB4XDTIxMDQwOTIzNDEwMFoXDTMxMDQwNzIzNDEwMFowbDELMAkG + A1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFu + Y2lzY28xFDASBgNVBAoTC2V4YW1wbGUuY29tMRowGAYDVQQDExF0bHNjYS5leGFt + cGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEmO9dcDCcVXeq7sORfZ + gJiFjsLNbOIoW03TWn+Fs9j1yAznTJ+fxtR5NOjSHHq54FQGuoPenq4LgHRQzrRR + VeCjbTBrMA4GA1UdDwEB/wQEAwIBpjAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYB + BQUHAwEwDwYDVR0TAQH/BAUwAwEB/zApBgNVHQ4EIgQgrllbVdzXhUpXNfSAVwKC + Az5wwgxfv49HsM+Lac939xQwCgYIKoZIzj0EAwIDRwAwRAIgXR5xJvEeoxqIbJHi + vD84ry3rRQjt2vGtpoRZ55XfD5UCICJIvGIEgvRuyuI7C8AMFbKc1tWUsuBM4rlI + MJ6IQtGW -----END CERTIFICATE----- + grpcOptions: ssl-target-name-override: orderer.example.com @@ -114,19 +115,19 @@ peers: "tlsCACerts": "pem": | -----BEGIN CERTIFICATE----- - MIICVjCCAf2gAwIBAgIQDfHCgOBKptyRG4OID6pNdDAKBggqhkjOPQQDAjB2MQsw - CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy - YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz - Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMTUyMDBaFw0zMTA0MDcyMTUy - MDBaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH - Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmV4YW1wbGUuY29tMR8wHQYD - VQQDExZ0bHNjYS5vcmcxLmV4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0D - AQcDQgAEobO4XVzgQt5WEzoyWSsAWq/11HKuMYP3eDsInxn4+C/t9YOME36LkALe - sOfhQJMzA8a5GSlVjRSLCW5tmSs0IqNtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1Ud - JQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1Ud - DgQiBCDiaKbL+LTkb/pjrVrPqJXXROL+vtrrVU04Fmn9JLy1LTAKBggqhkjOPQQD - AgNHADBEAiANZY3TVyDL4fSPs5rwN0ZxcFRdnl1nP16DMqeyB4dZwAIgQzWJXXOw - OPogeUshmqftxx5kdWs3/hL+bLcNM7mXizs= + MIICWDCCAf6gAwIBAgIRAOYNkGbXzKW1i4mltluQfHUwCgYIKoZIzj0EAwIwdjEL + MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG + cmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHzAdBgNVBAMTFnRs + c2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMjEwNDA5MjM0MTAwWhcNMzEwNDA3MjM0 + MTAwWjB2MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UE + BxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0G + A1UEAxMWdGxzY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49 + AwEHA0IABI5Vw6+CWZ/sYTB6I1qNogBRWY80f8SEeqvIl8Vm3JIKTuBF22LU8LEY + Q4g1nXbpjiiK8gWTdFM7YCI6aGp3A0WjbTBrMA4GA1UdDwEB/wQEAwIBpjAdBgNV + HSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUwAwEB/zApBgNV + HQ4EIgQgErte9O3FPE6AqitmQ8TPu5mtt2kqQAeStILtpMF7lk8wCgYIKoZIzj0E + AwIDSAAwRQIhAKLqgW+jXiI4SMRxerMy+a+3t/INk0jFhz20hqzpWwlaAiA4QeIT + BawhYxLD6FgPbXBHts3Sle847lvP90WnLwzk1Q== -----END CERTIFICATE----- grpcOptions: diff --git a/server/src/gateway/privateKey.pem b/server/src/gateway/privateKey.pem deleted file mode 100644 index 12a0770..0000000 --- a/server/src/gateway/privateKey.pem +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgj7n8a1aUVOpdWgwk -9+jbfccgxY5c9TUXIrGnUcYsnzihRANCAAQ9VMAV6Kly+mAY2itGeM/gpM5w/2+2 -KtBWhAhB1+KtouxcMCt6IaCMtfOGrsz9QSNXjTQnCJMGYltTYipvgaUC ------END PRIVATE KEY----- diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 6a6a3db..5e6d510 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -1,23 +1,17 @@ import express from 'express'; import { X509WalletMixin } from 'fabric-network'; import { getCA, getConnectedWallet, registerUser } from '../utils'; -import fs from 'fs'; -import path from 'path'; const router = express.Router(); const studentRegistration = async (req, res) => { const { login, password } = req.body; try { const ca = getCA(); - // const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); - const adminCertificate = fs.readFileSync(path.resolve(__dirname, '../gateway/caAdmin/cert.pem'), 'utf8'); - const adminPrivateKey = fs.readFileSync(path.resolve(__dirname, '../gateway/caAdmin/privateKey.pem'), 'utf8'); - console.log(adminCertificate) - console.log(adminPrivateKey) + const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); const mixin = X509WalletMixin.createIdentity( 'Org1MSP', - adminCertificate, - adminPrivateKey + adminData.certificate, + adminData.key.toBytes() ); const gateway = await getConnectedWallet('Org1MSP', mixin); const admin = await gateway.getCurrentIdentity() diff --git a/server/src/routes/record.js b/server/src/routes/record.js index 783ac49..6438fae 100644 --- a/server/src/routes/record.js +++ b/server/src/routes/record.js @@ -1,26 +1,11 @@ import express from 'express'; -import { getCA, getConnectedWallet, sendTransaction } from '../utils'; +import { getConnectedWallet, sendTransaction } from '../utils'; import { X509WalletMixin } from 'fabric-network'; -import fs from 'fs'; -import path from 'path'; const router = express.Router(); -const test = async (req, res) => { - const { certificate, privateKey } = req.body; - // const certificate = fs.readFileSync(path.resolve(__dirname, '../gateway/cert.pem'), 'utf8'); - // const privateKey = fs.readFileSync(path.resolve(__dirname, '../gateway/privateKey.pem'), 'utf8'); - console.log(certificate) - console.log(privateKey) - // const certificate = "-----BEGIN CERTIFICATE-----MIICKTCCAc+gAwIBAgIQTn6S2qGdc2v5QZDPCNk15TAKBggqhkjOPQQDAjBzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMTY2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MDkyMDA5MDBaFw0zMTA0MDcyMDA5MDBaMGsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMQ4wDAYDVQQLEwVhZG1pbjEfMB0GA1UEAwwWQWRtaW5Ab3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNnvug5vljzY4Lv++56mFILT/hIv5COA0fXGs/1Le7ZWhe0+LlOYCkyx74LosjJew55NU9t5pXqVWageufPXX2WjTTBLMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIMKW3AF+//QqKgHzNVIsNq4foUA5U7mjJ1WurlyRJcIpMAoGCCqGSM49BAMCA0gAMEUCIQD1Q+W54OgV2zwviCLx410c1Zt50oo7q+YdQb4FWEiDDgIgadx2hPJufDDeMoSbqFO8UrGey5q/veDBMJpDhc1NJOw=-----END CERTIFICATE-----"; - // const privateKey = "-----BEGIN PRIVATE KEY-----MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg5HdKWVWU/uzNgK0PBJ41XmeqmIIxOZ6LWBxaUiTbIJShRANCAATZ77oOb5Y82OC7/vuephSC0/4SL+QjgNH1xrP9S3u2VoXtPi5TmApMse+C6LIyXsOeTVPbeaV6lVmoHrnz119l-----END PRIVATE KEY-----"; +const createStudentRecord = async (req, res) => { + const { certificate, privateKey, studentEmail, studentFullName } = req.body; try { - // const ca = getCA(); - // const adminData = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'password' }); - // const mixin = X509WalletMixin.createIdentity( - // 'Org1MSP', - // adminData.certificate, - // adminData.key.toBytes() - // ); const mixin = X509WalletMixin.createIdentity( 'Org1MSP', certificate, @@ -28,8 +13,8 @@ const test = async (req, res) => { ); const gateway = await getConnectedWallet('Org1MSP', mixin); const result = await sendTransaction(gateway, { - name: 'test', - props: ["198"], + name: 'createStudentRecord', + props: [studentEmail, studentFullName], }) res.status(200).json({ data: result }); gateway.disconnect(); @@ -38,6 +23,6 @@ const test = async (req, res) => { res.status(400).json({ message: e.message }); } }; -router.get('/test', test); +router.post('/', createStudentRecord); export default router; diff --git a/server/src/utils/index.js b/server/src/utils/index.js index 1e63a18..1247395 100644 --- a/server/src/utils/index.js +++ b/server/src/utils/index.js @@ -32,7 +32,7 @@ export const registerUser = async (ca, adminWallet, userData) => { await ca.register({ enrollmentID: userData.login, enrollmentSecret: userData.password, - role: 'client', + role: 'admin', affiliation: `org1.${userData.affiliation}`, maxEnrollments: -1, }, adminWallet); From 9219318536106ab34a795f18d34ca15371dbcc38 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 10 Apr 2021 04:35:53 +0300 Subject: [PATCH 13/17] fix: fixed bug --- network/base/docker-compose-base.yaml | 40 ++++++++------------------- network/base/docker-compose-ca.yaml | 4 +-- network/docker-compose.yaml | 10 ------- 3 files changed, 13 insertions(+), 41 deletions(-) diff --git a/network/base/docker-compose-base.yaml b/network/base/docker-compose-base.yaml index af10cce..4b64fbf 100755 --- a/network/base/docker-compose-base.yaml +++ b/network/base/docker-compose-base.yaml @@ -7,32 +7,16 @@ version: '2' services: - ca.org1.example.com: - container_name: ca.org1.example.com - image: hyperledger/fabric-ca:1.4 - environment: - - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server - - FABRIC_CA_SERVER_CA_NAME=ca.org1.example.com - - FABRIC_CA_SERVER_CA_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org1.example.com-cert.pem - - FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/e5ff1ec118c67c202acb265a6704aa521cdeb2ee15ee2cc10d374c37148c8305_sk - volumes: - - ../ca:/etc/hyperledger/fabric-ca-server - - ../crypto-config/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config - - ../crypto-config/peerOrganizations/org1.example.com/tlsca/:/etc/hyperledger/fabric-ca-server-tls - ports: - - 7054:7054 - command: "sh -c 'fabric-ca-server start -b admin:password -d'" - orderer.example.com: container_name: orderer.example.com extends: file: peer-base.yaml service: orderer-base volumes: - - ../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 + - ../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 @@ -51,10 +35,10 @@ services: - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051 - CORE_PEER_LOCALMSPID=Org1MSP volumes: - - /var/run/:/host/var/run/ - - ../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 + - /var/run/:/host/var/run/ + - ../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 @@ -73,10 +57,10 @@ services: - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org1.example.com:7051 - CORE_PEER_LOCALMSPID=Org1MSP volumes: - - /var/run/:/host/var/run/ - - ../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 + - /var/run/:/host/var/run/ + - ../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:8051 diff --git a/network/base/docker-compose-ca.yaml b/network/base/docker-compose-ca.yaml index d16ad8f..6a49a86 100755 --- a/network/base/docker-compose-ca.yaml +++ b/network/base/docker-compose-ca.yaml @@ -15,10 +15,8 @@ services: - FABRIC_CA_SERVER_CA_NAME=ca.org1.example.com - FABRIC_CA_SERVER_CA_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org1.example.com-cert.pem - FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/8ddc8a5bd63d60c2df8dcea1b024e42a3084033065b8429877784c723f7a289c_sk - - 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/8ddc8a5bd63d60c2df8dcea1b024e42a3084033065b8429877784c723f7a289c_sk volumes: + - ../ca:/etc/hyperledger/fabric-ca-server - ../crypto-config/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config - ../crypto-config/peerOrganizations/org1.example.com/tlsca/:/etc/hyperledger/fabric-ca-server-tls ports: diff --git a/network/docker-compose.yaml b/network/docker-compose.yaml index 26bb45c..2a314a4 100755 --- a/network/docker-compose.yaml +++ b/network/docker-compose.yaml @@ -6,7 +6,6 @@ version: '2' volumes: - ca.org1.example.com: orderer.example.com: peer0.org1.example.com: peer1.org1.example.com: @@ -16,14 +15,6 @@ networks: services: - ca.org1.example.com: - extends: - file: base/docker-compose-ca.yaml - service: ca.org1.example.com - container_name: ca.org1.example.com - networks: - - byfn - orderer.example.com: extends: file: base/docker-compose-base.yaml @@ -75,7 +66,6 @@ services: - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts depends_on: - - ca.org1.example.com - orderer.example.com - peer0.org1.example.com - peer1.org1.example.com From 7e9c4c394191aa30b2d8b927c316879c508a2279 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 10 Apr 2021 04:51:46 +0300 Subject: [PATCH 14/17] fix: fixed bug --- .../src/contracts/student-records-storage.js | 8 +-- server/src/gateway/networkConnection.yaml | 59 +++++++++---------- server/src/routes/auth.js | 2 +- server/src/utils/index.js | 2 +- 4 files changed, 33 insertions(+), 38 deletions(-) diff --git a/chaincode/src/contracts/student-records-storage.js b/chaincode/src/contracts/student-records-storage.js index 260f208..a73236b 100644 --- a/chaincode/src/contracts/student-records-storage.js +++ b/chaincode/src/contracts/student-records-storage.js @@ -8,13 +8,9 @@ class StudentRecordsStorage extends Contract { super('org.fabric.studentRecordsStorage'); } - async test(ctx, val) { - return +val * 2; - } - async createStudentRecord(ctx, studentEmail, fullName) { const identity = new ClientIdentity(ctx.stub); - if (identity.cert.subject.organizationalUnitName !== 'admin') { + if (identity.cert.subject.organizationalUnitName !== 'teacher') { throw new Error('Current subject is not have access to this function'); } const recordAsBytes = await ctx.stub.getState(studentEmail); @@ -32,7 +28,7 @@ class StudentRecordsStorage extends Contract { async addSubjectToStudentRecord(ctx, studentEmail, semesterNumber, subjectName) { const identity = new ClientIdentity(ctx.stub); - if (identity.cert.subject.organizationalUnitName !== 'admin') { + if (identity.cert.subject.organizationalUnitName !== 'teacher') { throw new Error('Current subject is not have access to this function'); } const recordAsBytes = await ctx.stub.getState(studentEmail); diff --git a/server/src/gateway/networkConnection.yaml b/server/src/gateway/networkConnection.yaml index 9df4045..7f829f8 100644 --- a/server/src/gateway/networkConnection.yaml +++ b/server/src/gateway/networkConnection.yaml @@ -79,28 +79,27 @@ organizations: # orderers: orderer.example.com: - url: grpcs://192.168.88.85:7050 + url: grpcs://0.0.0.0:7050 # these are standard properties defined by the gRPC library # they will be passed in as-is to gRPC client constructor tlsCACerts: pem: | -----BEGIN CERTIFICATE----- - MIICQjCCAemgAwIBAgIQdrfZ1pyvqnT3U+zfreYLATAKBggqhkjOPQQDAjBsMQsw - CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy - YW5jaXNjbzEUMBIGA1UEChMLZXhhbXBsZS5jb20xGjAYBgNVBAMTEXRsc2NhLmV4 - YW1wbGUuY29tMB4XDTIxMDQwOTIzNDEwMFoXDTMxMDQwNzIzNDEwMFowbDELMAkG - A1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFu - Y2lzY28xFDASBgNVBAoTC2V4YW1wbGUuY29tMRowGAYDVQQDExF0bHNjYS5leGFt - cGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEmO9dcDCcVXeq7sORfZ - gJiFjsLNbOIoW03TWn+Fs9j1yAznTJ+fxtR5NOjSHHq54FQGuoPenq4LgHRQzrRR - VeCjbTBrMA4GA1UdDwEB/wQEAwIBpjAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYB - BQUHAwEwDwYDVR0TAQH/BAUwAwEB/zApBgNVHQ4EIgQgrllbVdzXhUpXNfSAVwKC - Az5wwgxfv49HsM+Lac939xQwCgYIKoZIzj0EAwIDRwAwRAIgXR5xJvEeoxqIbJHi - vD84ry3rRQjt2vGtpoRZ55XfD5UCICJIvGIEgvRuyuI7C8AMFbKc1tWUsuBM4rlI - MJ6IQtGW + MIICQzCCAeqgAwIBAgIRANGzDRMdLG4CRty3qb461KowCgYIKoZIzj0EAwIwbDEL + MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG + cmFuY2lzY28xFDASBgNVBAoTC2V4YW1wbGUuY29tMRowGAYDVQQDExF0bHNjYS5l + eGFtcGxlLmNvbTAeFw0yMTA0MTAwMTM0MDBaFw0zMTA0MDgwMTM0MDBaMGwxCzAJ + BgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJh + bmNpc2NvMRQwEgYDVQQKEwtleGFtcGxlLmNvbTEaMBgGA1UEAxMRdGxzY2EuZXhh + bXBsZS5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARayXtjQkb3jon7eOfc + DhpRbFe9Lth9sc6cZh7BZEJKmB6Vayt/5fvJVniir0pYIaplM/3cJqcLGSuHfBr1 + BGrqo20wazAOBgNVHQ8BAf8EBAMCAaYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsG + AQUFBwMBMA8GA1UdEwEB/wQFMAMBAf8wKQYDVR0OBCIEIHoFQsyUoqiio4UFH14+ + v8k+liZi7zJOHlDTSOMNJ5G6MAoGCCqGSM49BAMCA0cAMEQCIGmFKfBiId7plZ2k + f7HD3POekOAVb6g5ZuZ8d5SbFrp2AiBjM/oq8715cxKL9vfK+CRYqFG7iMY7y3bN + mqrXK1C+FA== -----END CERTIFICATE----- - grpcOptions: ssl-target-name-override: orderer.example.com @@ -111,23 +110,23 @@ orderers: peers: peer0.org1.example.com: # this URL is used to send endorsement and query requests - url: grpcs://192.168.88.85:7051 + url: grpcs://0.0.0.0:7051 "tlsCACerts": "pem": | -----BEGIN CERTIFICATE----- - MIICWDCCAf6gAwIBAgIRAOYNkGbXzKW1i4mltluQfHUwCgYIKoZIzj0EAwIwdjEL - MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG - cmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHzAdBgNVBAMTFnRs - c2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMjEwNDA5MjM0MTAwWhcNMzEwNDA3MjM0 - MTAwWjB2MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UE - BxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0G - A1UEAxMWdGxzY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49 - AwEHA0IABI5Vw6+CWZ/sYTB6I1qNogBRWY80f8SEeqvIl8Vm3JIKTuBF22LU8LEY - Q4g1nXbpjiiK8gWTdFM7YCI6aGp3A0WjbTBrMA4GA1UdDwEB/wQEAwIBpjAdBgNV - HSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUwAwEB/zApBgNV - HQ4EIgQgErte9O3FPE6AqitmQ8TPu5mtt2kqQAeStILtpMF7lk8wCgYIKoZIzj0E - AwIDSAAwRQIhAKLqgW+jXiI4SMRxerMy+a+3t/INk0jFhz20hqzpWwlaAiA4QeIT - BawhYxLD6FgPbXBHts3Sle847lvP90WnLwzk1Q== + MIICVjCCAf2gAwIBAgIQUvVwOOA5OkmDFvZ2QcaalTAKBggqhkjOPQQDAjB2MQsw + CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy + YW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz + Y2Eub3JnMS5leGFtcGxlLmNvbTAeFw0yMTA0MTAwMTM0MDBaFw0zMTA0MDgwMTM0 + MDBaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH + Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmV4YW1wbGUuY29tMR8wHQYD + VQQDExZ0bHNjYS5vcmcxLmV4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0D + AQcDQgAEBlyZ3i533b1w4+TlQXya6mOeQlLQHdPqYG9ZSYbIyLjDlScyaXfo293X + bDaymTe6yoDsZkQyH2NkNX5MmSjjeqNtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1Ud + JQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1Ud + DgQiBCAOH2rpHwOTy8EQ+Wtfzi6YD0TG312Ya+w59XdnWfvINjAKBggqhkjOPQQD + AgNHADBEAiAX6tZot3WIz8sWX6eX7BGyhWnCNxVut1QhG190ljUBSwIgUi0FXU72 + a0iCnIniDd2qjogDtSd1jBMeHe1/1Lf8KDA= -----END CERTIFICATE----- grpcOptions: @@ -140,7 +139,7 @@ peers: # certificateAuthorities: ca-org1: - url: http://192.168.88.85:7054 + url: http://0.0.0.0:7054 # the properties specified under this object are passed to the 'http' client verbatim when # making the request to the Fabric-CA server httpOptions: diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 5e6d510..efb3939 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -15,7 +15,7 @@ const studentRegistration = async (req, res) => { ); const gateway = await getConnectedWallet('Org1MSP', mixin); const admin = await gateway.getCurrentIdentity() - await registerUser(ca, admin, { login, password, affiliation: 'student' }); + await registerUser(ca, admin, { login, password, affiliation: 'teacher' }); const userData = await ca.enroll({ enrollmentID: login, diff --git a/server/src/utils/index.js b/server/src/utils/index.js index 1247395..1e63a18 100644 --- a/server/src/utils/index.js +++ b/server/src/utils/index.js @@ -32,7 +32,7 @@ export const registerUser = async (ca, adminWallet, userData) => { await ca.register({ enrollmentID: userData.login, enrollmentSecret: userData.password, - role: 'admin', + role: 'client', affiliation: `org1.${userData.affiliation}`, maxEnrollments: -1, }, adminWallet); From 86f9fcb3418c34d3ab18d1dcd5ed80324c679336 Mon Sep 17 00:00:00 2001 From: Vlad Boichenko Date: Sat, 10 Apr 2021 04:52:46 +0300 Subject: [PATCH 15/17] fix: fixed bug --- server/src/index.js | 3 +-- server/src/routes/index.js | 1 - server/src/routes/record.js | 28 ---------------------------- 3 files changed, 1 insertion(+), 31 deletions(-) delete mode 100644 server/src/routes/record.js diff --git a/server/src/index.js b/server/src/index.js index 30154fd..a6713a9 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -1,12 +1,11 @@ import express from 'express' -import { auth, record } from './routes'; +import { auth } from './routes'; const app = express(); app.use(express.urlencoded()); app.use(express.json()); app.use('/api/v1/auth/', auth); -app.use('/api/v1/record/', record); const appPort = 3000; app.listen( appPort, diff --git a/server/src/routes/index.js b/server/src/routes/index.js index 413c198..a2c97a3 100644 --- a/server/src/routes/index.js +++ b/server/src/routes/index.js @@ -1,2 +1 @@ export { default as auth } from './auth'; -export { default as record } from './record'; diff --git a/server/src/routes/record.js b/server/src/routes/record.js deleted file mode 100644 index 6438fae..0000000 --- a/server/src/routes/record.js +++ /dev/null @@ -1,28 +0,0 @@ -import express from 'express'; -import { getConnectedWallet, sendTransaction } from '../utils'; -import { X509WalletMixin } from 'fabric-network'; - -const router = express.Router(); -const createStudentRecord = async (req, res) => { - const { certificate, privateKey, studentEmail, studentFullName } = req.body; - try { - const mixin = X509WalletMixin.createIdentity( - 'Org1MSP', - certificate, - privateKey - ); - const gateway = await getConnectedWallet('Org1MSP', mixin); - const result = await sendTransaction(gateway, { - name: 'createStudentRecord', - props: [studentEmail, studentFullName], - }) - res.status(200).json({ data: result }); - gateway.disconnect(); - } - catch (e) { - res.status(400).json({ message: e.message }); - } -}; -router.post('/', createStudentRecord); - -export default router; From 2f27ebd04bbf30ed19cfe571e36f1c636dc5eabc Mon Sep 17 00:00:00 2001 From: BananchickPasha Date: Tue, 20 Apr 2021 11:24:37 +0300 Subject: [PATCH 16/17] auth teacher/user and password validation --- server/src/routes/auth.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index aba4b57..c913a4c 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -1,13 +1,16 @@ import express from 'express'; import FabricCAServices from 'fabric-ca-client'; import fs from 'fs'; -import path from 'path'; import yaml from 'js-yaml'; const router = express.Router(); -const teacherRegistration = async (req, res) => { - const {login, password} = req.body; - +const registration = async ({login, password}, user) => { + if(!login || !password) { + return { + status: 401, + result: "No login or password" + }; + } const ca = new FabricCAServices('http://0.0.0.0:7054'); let adminData; @@ -62,7 +65,7 @@ const teacherRegistration = async (req, res) => { enrollmentID: login, enrollmentSecret: password, role: 'peer', - affiliation: 'naukma.teacher', + affiliation: `naukma.${user}`, maxEnrollments: -1 }, admin); } catch (registerErr) { @@ -71,8 +74,9 @@ const teacherRegistration = async (req, res) => { } + const userData; try { - const userData = await ca.enroll({enrollmentID: login, enrollmentSecret: password}); + userData = await ca.enroll({enrollmentID: login, enrollmentSecret: password}); } catch (enrollmentErr) { res.status(400).json({ message: 'Error while enrolling admin', error: err.message }); } @@ -86,6 +90,14 @@ const teacherRegistration = async (req, res) => { }; -router.post('/teacher', teacherRegistration); +router.post('/student', async (req, res) => { + const response = await registration(req.body, 'student'); + res.status(response.status).json(response.result); +}); + +router.post('/teacher', async (req, res) => { + const response = await registration(req.body, 'teacher'); + res.status(response.status).json(response.result); +}); -export default router; \ No newline at end of file +export default router; From 574bf378d30ed984fe3424743b89abc7deb9e436 Mon Sep 17 00:00:00 2001 From: BananchickPasha Date: Tue, 20 Apr 2021 14:54:46 +0300 Subject: [PATCH 17/17] aditional features --- .../src/contracts/student-records-storage.js | 64 +++++++++++++++---- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/chaincode/src/contracts/student-records-storage.js b/chaincode/src/contracts/student-records-storage.js index a73236b..91d0561 100644 --- a/chaincode/src/contracts/student-records-storage.js +++ b/chaincode/src/contracts/student-records-storage.js @@ -8,31 +8,42 @@ class StudentRecordsStorage extends Contract { super('org.fabric.studentRecordsStorage'); } - async createStudentRecord(ctx, studentEmail, fullName) { + isAdmin(ctx) { const identity = new ClientIdentity(ctx.stub); - if (identity.cert.subject.organizationalUnitName !== 'teacher') { + if (identity.cert.subject.organizationalUnitName !== 'teacher') throw new Error('Current subject is not have access to this function'); - } + } + async createStudentRecord(ctx, studentEmail, fullName) { + this.isAdmin(ctx); const recordAsBytes = await ctx.stub.getState(studentEmail); - // if(!recordAsBytes || recordAsBytes.toString().length !== 0){ - // throw new Error('Student with the current email already exist'); - // } - const recordExample = { + if(!recordAsBytes || recordAsBytes.toString().length !== 0){ + throw new Error('Student with the current email already exist'); + } + const newStudent = { fullName: fullName, semesters: [] } - const newRecordInBytes = Buffer.from(JSON.stringify(recordExample)); + const newRecordInBytes = Buffer.from(JSON.stringify(newStudent)); await ctx.stub.putState(studentEmail, newRecordInBytes); return JSON.stringify(recordExample, null, 2); } - async addSubjectToStudentRecord(ctx, studentEmail, semesterNumber, subjectName) { - const identity = new ClientIdentity(ctx.stub); - if (identity.cert.subject.organizationalUnitName !== 'teacher') { - throw new Error('Current subject is not have access to this function'); + async getStudentRecord(ctx, studentEmail) { + const recordAsBytes = await ctx.stub.getState(studentEmail); + if(!recordAsBytes || recordAsBytes.toString().length === 0){ + throw new Error('Student with current email does not exist'); } + return JSON.parse(recordAsBytes.toString()); + } + + async addSubjectToStudentRecord(ctx, studentEmail, semesterNumber, subjectName) { + this.isAdmin(ctx); const recordAsBytes = await ctx.stub.getState(studentEmail); const recordAsObject = JSON.parse(recordAsBytes.toString()); + if(!recordAsObject.semesters[semesterNumber]) + recordAsObject.semesters[semesterNumber] = {}; + if(recordAsObject.semesters[semesterNumber][subjectName]) + throw new Error('This subject already exists'); recordAsObject.semesters[semesterNumber][subjectName] = { lector: identity.cert.subject.commonName, themes: [] @@ -41,6 +52,35 @@ class StudentRecordsStorage extends Contract { await ctx.stub.putState(studentEmail, newRecordInBytes); return JSON.stringify(recordAsObject, null, 2); } + + async addGradeToStudentRecord(ctx, studentEmail, semesterNumber, subjectName, grade, themeName){ + this.verifyIdentity(ctx); + + const recordAsObject = this.getStudentRecord(ctx, studentEmail); + if(!recordAsObject.semesters[semesterNumber]){ + throw new Error('Semester does not exist') + } + if(!recordAsObject.semesters[semesterNumber][subjectName]){ + throw new Error(`No such subject in ${semesterNumber} semester for this student`) + } + recordAsObject.semesters[semesterNumber][subjectName].themes.push([ + { + title: themeName, + rating: grade, + date: ctx.stub.getTxTimestamp().seconds.low + } + ]); + } + + async getStudentGrades(ctx, studentEmail) { + const recordAsObject = await this.getStudentRecord(ctx, studentEmail); + return JSON.stringify(recordAsObject.semesters, null, 2); + } + + async getStudentGradesBySemester(ctx, studentEmail, semesterNumber) { + const recordAsObject = await this.getStudentRecord(ctx, studentEmail); + return JSON.stringify(recordAsObject.semesters[semesterNumber] || [], null, 2); + } } module.exports = StudentRecordsStorage;