겉바속촉
[Hyperledger] node와 java로 체인코드 개발해보기 본문
지난번에 이어서 해볼게요
2020/08/24 - [IT일기/Hyperledger-fabric] - [Hyperledger] basic network + simple asset chain code
이번에는 node와 java를 활용해서 체인코드를 개발해보려고 합니다:)
tilix 창에서 두번째 cli 터미널에서 작성해주세요
다음 명령어로 설치해주시면 됩니다
peer chaincode install -n jes_cc_node -v 1.0 -l node -p /opt/gopath/src/github.com/chaincode_example02/node/
그리고 세번째 터미널에서 ls로 확인
(세번째 터미널은 chaincode입니다)
다음과 같이 체인코드가 node로 된 것이 하나 더 생겼습니다
즉 지난번 포스팅에서는 jes.1.0 뿐이었습니다
root@9a767cae6d6a:/var/hyperledger/production/chaincodes# ls
jes.1.0 jes_cc_node.1.0
이제 java로 체인코드 인스톨 해보기
peer chaincode install -n jes_cc_java -v 1.0 -l java -p /opt/gopath/src/github.com/chaincode_example02/java/
체인코드 터미널에서 ls로 확인
root@9a767cae6d6a:/var/hyperledger/production/chaincodes# ls
jes.1.0 jes_cc_java.1.0 jes_cc_node.1.0
이제 다시 cli 컨테이너로 들어가서 peer0에 설치된 체인 코드가 mychannel에 연결되도록 다음과 같이 명령해주세요
<node>
peer chaincode instantiate -C mychannel -n jes_cc_node -l node -v 1.0 -c '{"Args":["init","a","100","b","200"]}'
<java>
peer chaincode instantiate -C mychannel -n jes_cc_java -l java -v 1.0 -c '{"Args":["init","a","1000","b","2000"]}'
이제 확인을 해볼게요
databases는 다음과 같이 표시해준 3가지가 여태껏 우리가 작업해주고 있는 db 입니다
여기서 주의할 점은 채널 하나당 원장 하나 이런식인거에요
그렇기 때문에 db를 보고 원장이 여러개라고 착각하시면 절대 안됩니다
4번째 터미널 하나 열어서 원장 확인
root@ubuntu:~# docker exec -it peer0.org1.example.com bash
root@9a767cae6d6a:/opt/gopath/src/github.com/hyperledger/fabric# cd /var/hyperledger/production/ledgersData/chains/chains/mychannel/
root@9a767cae6d6a:/var/hyperledger/production/ledgersData/chains/chains/mychannel# ll
그럼 다음과 같이 출력됩니다
total 40
drwxr-xr-x 2 root root 4096 Aug 24 01:23 ./
drwxr-xr-x 3 root root 4096 Aug 24 01:23 ../
-rw-r----- 1 root root 26137 Aug 24 02:37 blockfile_000000
5번째 터미널 하나 열어서 도커 컨테이너의 logging을 볼게요
다음 명령어를 내려주시면 됩니다:)
로그를 만들때마다 출력이 됩니다.
docker logs -f peer0.org1.example.com
이제 node에서 invoke
peer chaincode invoke -C mychannel -n jes_cc_node -c '{"Args":["invoke","a","b","10"]}'
java에서 invoke
peer chaincode invoke -C mychannel -n jes_cc_java -c '{"Args":["invoke","a","b","10"]}'
node에서 query
peer chaincode query -C mychannel -n jes_cc_node -c '{"Args":["query","a"]}'
java에서 query
peer chaincode query -C mychannel -n jes_cc_java -c '{"Args":["get","a"]}'
이제 vscode로 가주세요
MyWeb/basic_articles 밑에 connection.json을 다음과 같이 작성해주세요
{
"name": "basic-network",
"version": "1.0.0",
"client": {
"organization": "Org1",
"connection": {
"timeout": {
"peer": {
"endorser": "300"
},
"orderer": "300"
}
}
},
"channels": {
"mychannel": {
"orderers": [
"orderer.example.com"
],
"peers": {
"peer0.org1.example.com": {}
}
}
},
"organizations": {
"Org1": {
"mspid": "Org1MSP",
"peers": [
"peer0.org1.example.com"
],
"certificateAuthorities": [
"ca.example.com"
]
}
},
"orderers": {
"orderer.example.com": {
"url": "grpc://localhost:7050"
}
},
"peers": {
"peer0.org1.example.com": {
"url": "grpc://localhost:7051"
}
},
"certificateAuthorities": {
"ca.example.com": {
"url": "http://localhost:7054",
"caName": "ca.example.com"
}
}
}
basic_network_router.js를 다음과 같이 만들어주세요
admin을 발급받기 위한 코드입니다:)
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin } = require('fabric-network');
/* GET */
router.get('/', async(req, res, next) => {
const ccpPath = path.resolve(__dirname, '..' , 'basic_articles', 'connection.json');
//ccp란 common connection profile의 약자
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
// 인증기관과 통신할 수 있는 객체 생성
const caURL = ccp.certificateAuthorities['ca.example.com'].url;
const ca = new FabricCAServices(caURL);
// 신원 증명서를 저장할 지갑 생성
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
// admin신원 증명서가 있는지 확인
const adminExists = await wallet.exists('admin');
if (!adminExists) {
// Enroll the admin user, and import the new identity into the wallet.
const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });
const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('admin', identity);
console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
}
res.json({"msg":"ok"});
});
module.exports = router;
자 이제 터미널에서 npm start 명령 내려주신 후에
firefox에서 localhost:3000
연결 클릭
그리고 vscode에서 admin 생성되었는 지 확인해주세요
이제 user 등록하기 위해 basic_network_router.js 에 코드 추가해서 작성해줄게요
추가해서 작성한 전체 router.js 코드
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const FabricCAServices = require('fabric-ca-client'); //HLF SDK node
const { FileSystemWallet, X509WalletMixin } = require('fabric-network'); //HLF SDK node
/* GET */
router.get('/', async(req, res, next) => {
const ccpPath = path.resolve(__dirname, '..' , 'basic_articles', 'connection.json');
//ccp란 common connection profile의 약자
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
// 인증기관과 통신할 수 있는 객체 생성
const caURL = ccp.certificateAuthorities['ca.example.com'].url;
const ca = new FabricCAServices(caURL);
// 신원 증명서를 저장할 지갑 생성
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
// admin신원 증명서가 있는지 확인
const adminExists = await wallet.exists('admin');
if (!adminExists) {
// Enroll the admin user, and import the new identity into the wallet.
const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });
const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('admin', identity);
console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
}
res.json({"msg":"ok"});
});
module.exports = router;
다시 firefox에서 localhost:3000
연결 클릭
그리고 vscode에서 user1 생성되었는 지 확인해주세요
이제 화면을 조금 수정할게요
잔액을 확인할 수 있게 고쳐볼게요:)
리액트 페이지를 고쳐주면 되겠쥬??
index.jsx
var {Component} = React;
var {Router, Route, IndexRoute, Link} = ReactRouter;
class Main extends Component{
render(){
return(
<div>
<h1>Hyperledger Fabric Study</h1>
<ul className="header" >
<li><Link exact to="/">Home</Link></li>
<li><Link to="/basic">BasicNetwork</Link></li>
<li><Link to="/first">FirstNetwork</Link></li>
</ul>
<div className="content">
{this.props.children}
</div>
</div>
);
}
}
class Home extends Component{
render(){
return(
<div>
<h2>HELLO</h2>
<p>안녕하세요? 하이퍼레저에 접속하는 노드 웹 예제입니다. 잘해보죠~!!!</p>
</div>
);
}
}
class BasicNetwork extends Component{
basic_network=()=>{
axios.get('/basic_network')
.then((response)=>{
console.log(response);
})
.catch((error)=>{
console.log(error);
});
}
send=()=>{
alert(this.amount.value);
axios.post('/basic_network',{"amount":this.amount.value})
.then((response)=>{
console.log(response);
})
.catch((error)=>{
console.log(error);
});
}
render(){
return(
<div>
<h2>BasicNetwork</h2>
<p><button onClick={this.basic_network}>연결</button></p>
<br/>
<div>a가 b에게 {' '}
<input placeholder='송금량' ref={ref=>this.amount=ref} />원을 {' '}
<button onClick={this.send} > 보내기</button><br/>
</div>
</div>
);
}
}
class FirstNetwork extends Component{
render(){
return(
<div>
<h2>FirstNetwork에 연결 해보세요</h2>
</div>
);
}
}
ReactDOM.render(
(<Router>
<Route path="/" component={Main} >
<Route path="basic" component={BasicNetwork}/>
<Route path="first" component={FirstNetwork} />
<IndexRoute component={Home} />
</Route>
</Router>)
,document.getElementById("root")
);
basic_network_router.js 코드도 다음과 같이 변경해주세요:)
이제 잔액과 송금 기능까지 있는 것이겠쥬
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin, Gateway } = require('fabric-network');
/* GET */
router.get('/', async(req, res, next) => {
const ccpPath = path.resolve(__dirname, '..' , 'basic_articles', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
const caURL = ccp.certificateAuthorities['ca.example.com'].url;
const ca = new FabricCAServices(caURL);
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
const adminExists = await wallet.exists('admin');
if (!adminExists) {
// Enroll the admin user, and import the new identity into the wallet.
const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });
const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('admin', identity);
console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
}
// 지갑에 user1에 대한 신원 증명서가 있는지 확인
const userExists = await wallet.exists('user1');
if (!userExists) {
// 피어 노드로 연결하기 위한 Gateway 객체 생성.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'admin', discovery: { enabled: false } });
// Gateway를 통해 인증기관 객체를 생성
const ca = gateway.getClient().getCertificateAuthority();
const adminIdentity = gateway.getCurrentIdentity();
// user1의 신원 증명
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminIdentity);
const enrollment = await ca.enroll({ enrollmentID: 'user1', enrollmentSecret: secret });
const userIdentity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('user1', userIdentity);
console.log('Successfully registered and enrolled admin user "user1" and imported it into the wallet');
}
res.json({"msg":"ok"});
});
module.exports = router;
여기서 이제 메서드를 바꿔주려고 합니다:)
query ==> get
invoke ==> send
메서드 이름까지 잘 바꿔준 전체 코드는 다음과 같습니다
basic_network_router.js
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin, Gateway } = require('fabric-network');
const ccpPath = path.resolve(__dirname, '..' , 'basic_articles', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
/* GET */
router.get('/connect', async(req, res, next) => {
try{
// Check to see if we've already enrolled the admin user.
const adminExists = await wallet.exists('admin');
if (!adminExists) {
// Enroll the admin user, and import the new identity into the wallet.
const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });
const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('admin', identity);
console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
}
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists('user1');
if (!userExists) {
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'admin', discovery: { enabled: false } });
// Get the CA client object from the gateway for interacting with the CA.
const ca = gateway.getClient().getCertificateAuthority();
const adminIdentity = gateway.getCurrentIdentity();
// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminIdentity);
const enrollment = await ca.enroll({ enrollmentID: 'user1', enrollmentSecret: secret });
const userIdentity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('user1', userIdentity);
console.log('Successfully registered and enrolled admin user "user1" and imported it into the wallet');
}
res.json({"msg":"ok"});
}catch(e){
console.log(e);
res.json({"msg":"connect error"});
}
});
/* GET */
router.get('/query', async (req, res, next) => {
try{
console.log("query a...");
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
await res.json({'msg':'연결부터 해주세요'});
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: false } });
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');
// Get the contract from the network.
const contract = network.getContract('jes_cc_node');
const result = await contract.evaluateTransaction('get','a');
console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
//res.json({'msg':result.toString()});
res.json({'a_amount':result.toString()});
}catch(e){
console.log(e);
res.json({'msg':'query error'});
}
}
);
/* POST */
router.post('/send', async (req, res, next) => {
try{
console.log("invoke from a to b : ", req.body.amount);
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
await res.json({'msg':'연결부터 해주세요'});
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: false } });
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');
// Get the contract from the network.
const contract = network.getContract('jes_cc_node');
await contract.submitTransaction('send','a','b',`${req.body.amount}`);
console.log(`Transaction has been submitted`);
res.json({'msg':'ok'});
}catch(e){
console.log(e);
res.json({'msg':'send error'});
}
}
);
module.exports = router;
다음과 같이 10을 보내고 나서 a의 잔액이 확인 되면 okay~
이제 java로 해볼게요
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin, Gateway } = require('fabric-network');
const ccpPath = path.resolve(__dirname, '..' , 'basic_articles', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
/* GET */
router.get('/connect', async(req, res, next) => {
try{
// Check to see if we've already enrolled the admin user.
const adminExists = await wallet.exists('admin');
if (!adminExists) {
// Enroll the admin user, and import the new identity into the wallet.
const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });
const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('admin', identity);
console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
}
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists('user1');
if (!userExists) {
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'admin', discovery: { enabled: false } });
// Get the CA client object from the gateway for interacting with the CA.
const ca = gateway.getClient().getCertificateAuthority();
const adminIdentity = gateway.getCurrentIdentity();
// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminIdentity);
const enrollment = await ca.enroll({ enrollmentID: 'user1', enrollmentSecret: secret });
const userIdentity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('user1', userIdentity);
console.log('Successfully registered and enrolled admin user "user1" and imported it into the wallet');
}
res.json({"msg":"ok"});
}catch(e){
console.log(e);
res.json({"msg":"connect error"});
}
});
/* GET */
router.get('/query', async (req, res, next) => {
try{
console.log("query a...");
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
await res.json({'msg':'연결부터 해주세요'});
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: false } });
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');
// Get the contract from the network.
const contract = network.getContract('jes_cc_java');
const result = await contract.evaluateTransaction('query','a');
console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
//res.json({'msg':result.toString()});
res.json({'a_amount':result.toString()});
}catch(e){
console.log(e);
res.json({'msg':'query error'});
}
}
);
/* POST */
router.post('/send', async (req, res, next) => {
try{
console.log("invoke from a to b : ", req.body.amount);
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
await res.json({'msg':'연결부터 해주세요'});
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: false } });
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');
// Get the contract from the network.
const contract = network.getContract('jes_cc_java');
await contract.submitTransaction('invoke','a','b',`${req.body.amount}`);
console.log(`Transaction has been submitted`);
res.json({'msg':'ok'});
}catch(e){
console.log(e);
res.json({'msg':'send error'});
}
}
);
module.exports = router;
java로 해준 후에 firefox에서 확인!!
a는 잔액이 1000원이었기 때문에 20원을 송금하면 당연히 980원이 남겠쥬
이제 잔액 b 도 나올 수 있게 코드 조금 바꿔줄게요
basic_network_router.js
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin, Gateway } = require('fabric-network');
const ccpPath = path.resolve(__dirname, '..' , 'basic_articles', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
/* GET */
router.get('/connect', async(req, res, next) => {
try{
// Check to see if we've already enrolled the admin user.
const adminExists = await wallet.exists('admin');
if (!adminExists) {
// Enroll the admin user, and import the new identity into the wallet.
const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });
const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('admin', identity);
console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
}
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists('user1');
if (!userExists) {
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'admin', discovery: { enabled: false } });
// Get the CA client object from the gateway for interacting with the CA.
const ca = gateway.getClient().getCertificateAuthority();
const adminIdentity = gateway.getCurrentIdentity();
// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminIdentity);
const enrollment = await ca.enroll({ enrollmentID: 'user1', enrollmentSecret: secret });
const userIdentity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
wallet.import('user1', userIdentity);
console.log('Successfully registered and enrolled admin user "user1" and imported it into the wallet');
}
res.json({"msg":"ok"});
}catch(e){
console.log(e);
res.json({"msg":"connect error"});
}
});
/* GET */
router.get('/query', async (req, res, next) => {
try{
console.log("query a...");
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
await res.json({'msg':'연결부터 해주세요'});
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: false } });
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');
// Get the contract from the network.
const contract = network.getContract('jes_cc_java');
const result = await contract.evaluateTransaction('query','a');
const result2 = await contract.evaluateTransaction('query','b');
console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
//res.json({'msg':result.toString()});
res.json({'a_amount':result.toString(),'b_amount':result2.toString()});
}catch(e){
console.log(e);
res.json({'msg':'query error'});
}
}
);
/* POST */
router.post('/send', async (req, res, next) => {
try{
console.log("invoke from a to b : ", req.body.amount);
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
await res.json({'msg':'연결부터 해주세요'});
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: false } });
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');
// Get the contract from the network.
const contract = network.getContract('jes_cc_java');
await contract.submitTransaction('invoke','a','b',`${req.body.amount}`);
console.log(`Transaction has been submitted`);
res.json({'msg':'ok'});
}catch(e){
console.log(e);
res.json({'msg':'send error'});
}
}
);
module.exports = router;
index.jsx
const {Component}=React;
const {Router,Route,IndexRoute,Link}=ReactRouter;
class Main extends Component{
render(){
return(
<div>
<h1>Hyperledger Fabric Study</h1>
<ul className="header">
<li><Link exact to="/">Home</Link></li>
<li><Link to="/basic">BasicNetwork</Link></li>
<li><Link to="/first">FirstNetwork</Link></li>
</ul>
<div>
{this.props.children}
</div>
</div>
);
}
}
class Home extends Component{
render(){
return(
<div>
<h2>Home</h2>
</div>
);
}
}
class BasicNetwork extends Component{
state={
a_amount:0
}
basic_network_connect=()=>{
axios.get('basic_network/connect')
.then((res)=>{
console.log(res);
})
.catch((error)=>{
console.log(error);
});
}
query=()=>{
axios.get('/basic_network/query')
.then((response)=>{
this.setState({a_amount:response.data.a_amount,b_amount:response.data.b_amount});
})
.catch((error)=>{
console.log(error);
});
}
send=()=>{
alert(this.amount.value);
axios.post('/basic_network/send',{"amount":this.amount.value})
.then((response)=>{
console.log(response);
})
.catch((error)=>{
console.log(error);
});
}
render(){
return(
<div>
<h2>BasicNetwork
에 <button onClick={this.basic_network_connect}>연결</button></h2>
<br/>
<button onClick={this.query} > 잔액 확인</button> {' '} a : {this.state.a_amount}원 {' '} b : {this.state.b_amount}원
<br/>
<br/>
<div>a가 b에게 {' '}
<input placeholder='송금량' ref={ref=>this.amount=ref} />원을 {' '}
<button onClick={this.send} > 보내기</button><br/>
</div>
</div>
);
}
}
class FirstNetwork extends Component{
render(){
return(
<div>
<h2>FirstNetwork</h2>
</div>
);
}
}
ReactDOM.render(
(<Router>
<Route path="/" component={Main} >
<IndexRoute component={Home} />
<Route path="basic" component={BasicNetwork} />
<Route path="first" component={FirstNetwork} />
</Route>
</Router>)
, document.getElementById("root")
);
firefox에서 확인해볼게요
b의 잔액도 잘 나오고 있쥬??
'IT일기(하반기) > Hyperledger-fabric' 카테고리의 다른 글
[Hyperledger] 개발환경 설정하기 (0) | 2020.08.26 |
---|---|
[Hyperledger] (0) | 2020.08.26 |
[Hyperledger] basic network + simple asset chain code (0) | 2020.08.24 |
[Hyperledger] 메서드 변경, transaction 생성, key생성 (0) | 2020.08.13 |
[Hyperledger] Orderer에 대해 알아보기 (0) | 2020.08.13 |