1. Hyperledger Fabric 조직구조
2. Dapp 흐름
- 데이터 조회
- 데이터 삽입
3. Dapp 블록 생성자변경
데이터 삽입시 블록을 생성하고 트랜잭션을 기록하는 조직을 변경해야 위·변조가 불가능하게 기록한 생성자를 알 수 있음
수정 파일 경로
fabric-samples/my-network/application-javascript/app.js
fabric-samples/test-application/connection.json
fabric-samples/test-application/javascript/AppUtil.js
fabric-samples/test-application/javascript/CAUtils.js
- app.js
필요 변수 및 함수 설명
const mspOrg1 = '조직의MSP이름'
-> 블록체인에서 생성한 MSP의 조직이름으로 넣어야함 안하면 'access denied' 에러
const org1UserId = '생성할 조직 UserID'
-> 특수문자 없이 작성
const ccp = buildCCPOrg2();
-> AppUtil.js 파일에서 조직을 빌드함 이때 ccpPath값의 경로를 'connection.json'으로 변경
const caClient = buildCAClient(FabricCAServices, ccp, 'ca.org2.example.com');
-> 'ca.org2.example.com' 매개변수 부분을 설정한 fabric-ca의 이름값으로 변경
await registerAndEnrollUser(caClient, wallet, mspOrg1, org1UserId, 'org2.department1');
※ 이미 생성한 org1UserId ID값이 겹치거나
/*
* Copyright IBM Corp. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const { Gateway, Wallets } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const path = require('path');
const { buildCAClient, registerAndEnrollUser, enrollAdmin } = require('../../test-application/javascript/CAUtil.js');
const { buildCCPOrg1, buildCCPOrg2, buildWallet } = require('../../test-application/javascript/AppUtil.js');
const channelName = 'mychannel';
//const chaincodeName = 'basic';
const chaincodeName = 'newsc8';
const mspOrg1 = 'Org2MSP';
const walletPath = path.join(__dirname, 'wallet');
const org1UserId = 'org2User';
const template = require('./server/views/template.js')
function prettyJSONString(inputString) {
return JSON.stringify(JSON.parse(inputString), null, 2);
}
async function send(type, func, args, res) {
try {
// build an in memory object with the network configuration (also known as a connection profile)
const ccp = buildCCPOrg2();
// console.log(ccp);
console.log("************END CCP*************");
// build an instance of the fabric ca services client based on
// the information in the network configuration
const caClient = buildCAClient(FabricCAServices, ccp, 'ca.org2.example.com');
// console.log(caClient);
// setup the wallet to hold the credentials of the application user
const wallet = await buildWallet(Wallets, walletPath);
// console.log(wallet);
console.log("****************EnrollAdmin Start********************");
// in a real application this would be done on an administrative flow, and only once
await enrollAdmin(caClient, wallet, mspOrg1);
// in a real application this would be done only when a new user was required to be added
// and would be part of an administrative flow
console.log("****************** EnrollUser ******************")
await registerAndEnrollUser(caClient, wallet, mspOrg1, org1UserId, 'org2.department1');
// await registerAndEnrollUser(caClient, wallet, mspOrg1, "appuser3", 'org2.department2');
console.log("*****************END Register User*********************");
// a user that has been verified.
const gateway = new Gateway();
try {
// setup the gateway instance
// The user will now be able to create connections to the fabric network and be able to
// submit transactions and query. All transactions submitted by this gateway will be
// signed by this user using the credentials stored in the wallet.
await gateway.connect(ccp, {
wallet,
identity: org1UserId,
discovery: { enabled: true, asLocalhost: true } // using asLocalhost as this gateway is us$
});
// Build a network instance based on the channel where the smart contract is deployed
const network = await gateway.getNetwork(channelName);
// Get the contract from the network.
const contract = network.getContract(chaincodeName);
if(type == true) { // type true : submit transaction, not only query
await contract.submitTransaction(func, ...args);
console.log('Submit transaction success');
console.log("$$$$$$$$$$$$$$$$$$$$$$$ TTTEESSTTT $$$$$$$$$$$$")
console.log(func)
console.log(args)
console.log("$$$$$$$$$$$$$$$$$$$$$$$ END $$$$$$$$$$$$")
const resultString = 'Submit Transcation success!!!';
const html = template.HTML(func, type, resultString);
res.send(html);
}else {
const result = await contract.evaluateTransaction(func, ...args);
const resultString = result.toString();
console.log(`*** Result: ${resultString}`);
const html = template.HTML(func, type, resultString);
res.send(html);
}
} finally {
// Disconnect from the gateway when the application is closing
// This will close all connections to the network
gateway.disconnect();
}
} catch (error) {
console.error(`******** FAILED to run the application: ${error}`);
res.send(error);
}
}
module.exports = {
send:send
}
- docker/docker-compose-ca.yaml
사용자의 CA(Certificate Authority)을 위해 Docker를 통해 구축
command: sh -c 'fabric-ca-server start -b admin2:adminpw2 -d'
-> 생성할때 sh -c 'fabric-ca-server start -b '관리자계정id':'관리자pw' -d' 관리자 id, pw지정
※ 알수없는 에러가 났었는데 특수문자 없이 하니까 에러가 안나오긴했습니다. 참고하시길 바랍니다.
version: '2'
networks:
test:
external:
name: fabric_test
services:
ca.org1.example.com:
image: hyperledger/fabric-ca
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/priv_sk
ports:
- "7054:7054"
command: sh -c 'fabric-ca-server start -b admin:adminpw -d'
volumes:
- ../organizations/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config
container_name: ca.org1.example.com
networks:
- test
ca.org2.example.com:
image: hyperledger/fabric-ca
environment:
- FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
- FABRIC_CA_SERVER_CA_NAME=ca.org2.example.com
- FABRIC_CA_SERVER_CA_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org2.example.com-cert.pem
- FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/priv_sk
ports:
- "8054:8054"
command: sh -c 'fabric-ca-server start -b admin2:adminpw2 -d'
volumes:
- ../organizations/peerOrganizations/org2.example.com/ca/:/etc/hyperledger/fabric-ca-server-config
container_name: ca.org2.example.com
networks:
- test
- docker-compose-ca.yaml run
docker-compose -f docker-compose-ca.yaml up -d
docker ps 확인보니 구동중입니다.
- connection.json
certificateAuthorities 부분에 'ca.org2.exmple.com' 추가
'tlsCACerts'의 경로와 docker-compose-ca.yaml에 등록한 관리자 id,pw를 'registar'에 설정
※ connection.json의 전체파일내용을 추가한 것이 아니라 추가된 부분만 수정했습니다. 파일에 대한 전체 데이터는 아래 링크에서 확인부탁드립니다.
................
................
................
"certificateAuthorities": {
"ca.org1.example.com": {
"url": "http://localhost:7054",
"caName": "ca.org1.example.com",
"tlsCACerts": {
"path": "../../organizations/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem"
},
"registrar":{
"enrollId": "admin",
"enrollSecret": "adminpw",
"caName": "casales1"
},
"httpOptions": {
"verify": false
}
},
"ca.org2.example.com": {
"url": "http://localhost:8054",
"caName": "ca.org2.example.com",
"tlsCACerts": {
"path": "../../organizations/peerOrganizations/org2.example.com/ca/ca.org2.example.com-cert.pem"
},
"registrar":{
"enrollId": "admin2",
"enrollSecret": "adminpw2",
"caName": "casales2"
},
"httpOptions": {
"verify": false
}
}
}
- CAUtils.json
기존이 파일에서 설정한 관리자 계정 id, pw만 수정
/*
* Copyright IBM Corp. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const adminUserId = 'admin2';
const adminUserPasswd = 'adminpw2';
......
......
......
조직에 따른 환경들의 값들을 수정하고 Dapp서버를 구동하면 값을 삽입할때 지정한 조직으로 블록이 생성됨
※ 향후 Dapp의 사용자들의 로그인 인증방식으로 활용하면 좋을듯
기본 파일들에 대한 내용은 아래 링크에서 확인부탁드립니다.
하이퍼레저 패브릭(Hyperledger Fabric) v2.2 - #5 node.js Application구축
1. Hyperledger Fabric Application 구조 블록체인 네트워크의 구성과, 체인코드(스마트 컨트랙트)는 구축이 된 상태에서 Client와 연결할 수 있도록 node.js를 통해 아래 Application부분을(빨간색 박스 부분) 개
yoon1seok.tistory.com
'보안 및 블록체인 > 블록체인' 카테고리의 다른 글
Blockchain(블록체인)과 보안요소 특징 (0) | 2023.04.19 |
---|---|
하이퍼레저 패브릭(Hyperledger Fabric) v2.2 - #6 Hyperledger Explorer v1.1.8 구축(Docker기반) (0) | 2022.09.08 |
하이퍼레저 패브릭(Hyperledger Fabric) v2.2 - #5 node.js Application구축 (0) | 2022.08.31 |
하이퍼레저 패브릭(Hyperledger Fabric) v2.2 - #4 go언어 체인코드 개발 (0) | 2022.08.19 |
블록체인 보안이슈 및 위협요소 정리 51%공격 #2 (0) | 2022.08.16 |