겉바속촉

[Hyperledger] 본문

IT일기(하반기)/Hyperledger-fabric

[Hyperledger]

겉바속촉 2020. 8. 26. 13:28
728x90
반응형

 

겉바속촉은 항상 root에서 시작하기 때문에 대화를 하겠다는 다음과 같은 명령어를 내려주세요

cli와 bash 방에서 대화하겠다~ 라는 뜻으로 이해해주시면 되겠습니다

 

docker exec -it cli bash

 

 

 

설치된 체인코드 있는 지 확인

 

peer chaincode list --installed

 

 

그랬더니 다음과 같이 없다고 뜹니다

 

Get installed chaincodes on peer:

 

 

 

저는 컨테이너를 내렸다가 시작했기 때문인데요

 

이제 설치를 해보겠습니다:)

 

 peer chaincode install -n fabcar -v 1.0 -l node -p /opt/gopath/src/github.com/fabcar/javascript-low-level/

 

 

language로 줄 수 있는 것은 3가지 뿐입니다

go, node, javascript

 

저는 현재 -l 뒤에 node라고 작성했쥬?? ----> node 언어로 설치하겠다는 뜻입니다:)

 

 

그럼 다음과 같이 출력이 되는데요

ok라고 뜨긴 뜨지만 믿으시면 안됩니다

 

문법이 틀려도 설치하겠다고 명령을 내리면 ok라고 뜨기 때문이쥬!!

 

2020-08-26 00:22:30.502 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 001 Using default escc
2020-08-26 00:22:30.502 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default vscc
2020-08-26 00:22:30.540 UTC [chaincodeCmd] install -> INFO 003 Installed remotely response:<status:200 payload:"OK" > 

 

 

그렇기 때문에 잘 설치되었는 지 확인하는 명령을 내려주셔야합니다

위에서 써먹었던 !!!!!  설치된 체인코드 있는 지 확인했던 그 명령!!!!!!!!!!!

 

peer chaincode list --installed

 

다음과 같이 출력됩니다

 

Get installed chaincodes on peer:
Name: fabcar, Version: 1.0, Path: /opt/gopath/src/github.com/fabcar/javascript-low-level/, Id: 586f39db09923c4d2b68f3c0c1d0ba28ef9ccaa4e56f886ae9ce8ed388dda928

 

 

instantiate 해주신후에~

peer chaincode instantiate -n fabcar -v 1.0 -l node -C mychannel -c '{"Args":[]}'

 

다음과 같이 출력됩니다

 

2020-08-26 00:34:08.038 UTC [chaincodeCmd] InitCmdFactory -> INFO 001 Retrieved channel (mychannel) orderer endpoint: orderer.example.com:7050
2020-08-26 00:34:08.039 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default escc
2020-08-26 00:34:08.040 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default vscc

 

 

instantiated!!!! 내려주시고~

peer chaincode list --instantiated -C mychannel

 

다음과 같이 출력됩니다

Get instantiated chaincodes on channel mychannel:
Name: fabcar, Version: 1.0, Path: /opt/gopath/src/github.com/fabcar/javascript-low-level/, Escc: escc, Vscc: vscc
root@d857030b1c82:/opt/gopath/src/github.com# peer chaincode invoke -n fabcar -C mychannel -c '{"Args":["initLedger"]}'
2020-08-26 00:37:17.704 UTC [chaincodeCmd] InitCmdFactory -> INFO 001 Retrieved channel (mychannel) orderer endpoint: orderer.example.com:7050
2020-08-26 00:37:17.728 UTC [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 002 Chaincode invoke successful. result: status:200 

 

 

 

 

이제 확인만 할 것이라서 블록을 생성해내지 않는 명령어 query를 내려주세요

peer chaincode query -n fabcar -C mychannel -c '{"Args":["queryAllCars"]}'

 

그럼 다음과 같이 촤르르륵 뜨게 됩니다:)

 

[{"Key":"CAR0","Record":{"color":"blue","docType":"car","make":"Toyota","model":"Prius","owner":"Tomoko"}},{"Key":"CAR1","Record":{"color":"red","docType":"car","make":"Ford","model":"Mustang","owner":"Brad"}},{"Key":"CAR2","Record":{"color":"green","docType":"car","make":"Hyundai","model":"Tucson","owner":"Jin Soo"}},{"Key":"CAR3","Record":{"color":"yellow","docType":"car","make":"Volkswagen","model":"Passat","owner":"Max"}},{"Key":"CAR4","Record":{"color":"black","docType":"car","make":"Tesla","model":"S","owner":"Adriana"}},{"Key":"CAR5","Record":{"color":"purple","docType":"car","make":"Peugeot","model":"205","owner":"Michel"}},{"Key":"CAR6","Record":{"color":"white","docType":"car","make":"Chery","model":"S22L","owner":"Aarav"}},{"Key":"CAR7","Record":{"color":"violet","docType":"car","make":"Fiat","model":"Punto","owner":"Pari"}},{"Key":"CAR8","Record":{"color":"indigo","docType":"car","make":"Tata","model":"Nano","owner":"Valeria"}},{"Key":"CAR9","Record":{"color":"brown","docType":"car","make":"Holden","model":"Barina","owner":"Shotaro"}}]

 

 


 

 

[Web promgram에서 연동]

 

1. 설정

 

vs code를 열어주세요

 

File - open folder 

 

4jes 폴더 생성 - MyWeb 폴더 생성 까지 하신 후에 ok!!!

 

 

 

이제 작업시작해주시면 됩니다

 

ctrl + `  ==> 터미널 열어주기

 

 

 

다음 명령 내려주세요:)

 

npm init

 

npm i express

 

 

 

2. index.html

 

 public 폴더를 생성하고 index.html을 작성한다

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" >
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/1.0.2/ReactRouter.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" type="text/css" href="index.css">
    <title>React App</title>
  </head>
  <body>
   <div id="root" ></div>
   <script type="text/babel" src="index.jsx" />
  </body>
</html>


 

3. 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/connect')
        .then((response)=>{
            console.log(response);
            
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    get=()=>{
        alert(this.id.value+ '의 잔액 보기');
        axios.post('/basic_network/get',{"id":this.id.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>
                <hr/>
                <br/> sacc 에 연동하기<br/>
                <div>
                <input placeholder='a' ref={ref=>this.id=ref} />의  {' '} 
                <button onClick={this.get}  > 잔액 보기</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")
);
 

 

 

4. index.css

body{
    background-color: #FFCC00;
    padding:20px;
    margin:0;
}
h1,h2,p,ul,li{
    font-family:sans-serif;
}
ul.header li{
    display: inline;
    list-style-type:none;
    margin:0;
}
ul.header{
    background-color: #111;
    padding: 0;
}
ul.header li a{
    color:#FFF;
    font-weight: bold;
    text-decoration: none;
    padding: 20px;
    display: inline-block;
}
.content{
    background-color: #FFF;
    padding: 20px;
}
.content h2{
    padding: 0;margin:0;
}
.content li{
    margin-bottom: 10px;
}
a:hover{
    background-color: #0099ff;
}
 

 

 

5. server.js

 

현재 주석처리된 행은 화면만 확인 할 것이라서 라우터가 필요없기 때문입니다

const express=require("express");
const path=require("path");
const app=express(); 
 
app.use(express.static(path.join(__dirname,"/public")));
 
app.use(express.json());
 
//app.use('/basic_network', require('./routes/basic_network_router'));
 
app.listen(3000,function(){
    console.log("3000 server ready...");
           });

 

 

npm start 명령을 내려주신 후에

firefox에서 다음과 같은 화면을 확인해주세요:)

 

 

 


중고차시장 항목을 추가하기 위해서

index.jsx 를 고쳐줄게요

 

 

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>
                    <li><Link to="/fabcar">중고차시장</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/connect')
        .then((response)=>{
            console.log(response);
            
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    get=()=>{
        alert(this.id.value+ '의 잔액 보기');
        axios.post('/basic_network/get',{"id":this.id.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>
                <hr/>
                <br/> sacc 에 연동하기<br/>
                <div>
                <input placeholder='a' ref={ref=>this.id=ref} />의  {' '} 
                <button onClick={this.get}  > 잔액 보기</button><br/>               
                </div>
            </div>
        );
    }
}
class FirstNetwork extends Component{  
 
    render(){
        return(
            <div>
                <h2>FirstNetwork에 연결 해보세요</h2>                
            </div>
        );
    }
}

class Fabcar extends Component{  
    wallet=()=>{
        alert("^^");
    }
 
 render(){
     return(
         <div>
             <h2>중고차 시장에 오신 걸 환영합니다</h2> 
             <br/>
             <button onClick={this.wallet}>지갑 생성</button>               
         </div>
     );
 }
}
 
ReactDOM.render(
    (<Router>
        <Route path="/" component={Main} >   
            <Route path="basic" component={BasicNetwork}/>
            <Route path="first" component={FirstNetwork} />
            <IndexRoute component={Home} />
            <Route path="fabcar" component={Fabcar} />
        </Route>
    </Router>)
    ,document.getElementById("root")
);
 

 

 

그리고 firefox에서 확인!!!

 

화면구성이 다음과 같이 바꼈습니다:)

 

 

지갑생성 버튼 클릭해주시면

alert창이 뜨도록 만들어준거에요:)

 

 


다음 경로 따라서 connection.json을 복사

 

다음 경로 따라서 붙여넣기

a 폴더 생성해준 것 입니다

 

 

그리고 vs code로 가셔서

 

package.json 파일에 다음 추가

    "fabric-ca-client": "~1.4.0",
    "fabric-client": "~1.4.0",
    "fabric-network": "^1.4.4",

 

자동으로 추가되지 않기 때문에

터미널에서 실행되던 작업 종료시키고

npm i 를 내려주세요

package.json의 dependency들을 import해달라는 명령입니다

 

 

그리고

routes 폴더 생성 - fabcar_router.js 파일 생성 

 

fabcar_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, '..' , 'a', '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('/wallet', 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('/get', async (req, res, next) => {
    try{
    console.log("query..." +req.body.id);
    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');
       
        const result = await contract.evaluateTransaction('get',`${req.body.id}`);
 
        console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
        res.json({'msg':result.toString()});
 
    }catch(e){
        console.log(e);
        res.json({'msg':'query error'});
    }
    }
);
 
/* POST */
router.post('/set', async (req, res, next) => {
    try{
    console.log("set : ", req.body.id, 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');
 
        await contract.submitTransaction('set',`${req.body.id}`,`${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;

 

이제 server.js로 가주세요

아까 주석처리한 부분 빼고 고칠 것 고칠게요

const express=require("express");
const path=require("path");
const app=express(); 
 
app.use(express.static(path.join(__dirname,"/public")));
 
app.use(express.json());
 
app.use('/fabcar', require('./routes/fabcar_router'));
 
app.listen(3000,function(){
    console.log("3000 server ready...");
           });

 

 

index.jsx 로 가서 위에서 alert창을 띄우기 위해 작성했던 코드의 바로 아래에 다음 코드를 추가할게요

 

axios.get()
        .then()
        .catch();
 axios.get('url')
        .then(()=>{})
        .catch(()=>{});

이제 url 지정이랑 함수들 지정해볼게요

 axios.get('/fabcar/wallet')
        .then((res)=>{
            console.log(res);
        })
        .catch((err)=>{
            console.log(err);
        });

 

그래서 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>
                    <li><Link to="/fabcar">중고차시장</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/connect')
        .then((response)=>{
            console.log(response);
            
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    get=()=>{
        alert(this.id.value+ '의 잔액 보기');
        axios.post('/basic_network/get',{"id":this.id.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>
                <hr/>
                <br/> sacc 에 연동하기<br/>
                <div>
                <input placeholder='a' ref={ref=>this.id=ref} />의  {' '} 
                <button onClick={this.get}  > 잔액 보기</button><br/>               
                </div>
            </div>
        );
    }
}
class FirstNetwork extends Component{  
 
    render(){
        return(
            <div>
                <h2>FirstNetwork에 연결 해보세요</h2>                
            </div>
        );
    }
}

class Fabcar extends Component{  
    wallet=()=>{
        alert("^^");

        axios.get('/fabcar/wallet')
        .then((res)=>{
            console.log(res);
        })
        .catch((err)=>{
            console.log(err);
        });
    }
 
 render(){
     return(
         <div>
             <h2>중고차 시장에 오신 걸 환영합니다</h2> 
             <br/>
             <button onClick={this.wallet}>지갑 생성</button>               
         </div>
     );
 }
}
 
ReactDOM.render(
    (<Router>
        <Route path="/" component={Main} >   
            <Route path="basic" component={BasicNetwork}/>
            <Route path="first" component={FirstNetwork} />
            <IndexRoute component={Home} />
            <Route path="fabcar" component={Fabcar} />
        </Route>
    </Router>)
    ,document.getElementById("root")
);
 

 

이제 npm start 해볼게요

fire fox로 가서 지갑생성 클릭!!

 

vs code로 가서 wallet 폴더 만들어진 것을 확인해주세요

 

 

 

현재 작업한 곳 까지 vs code 각 폴더와 파일들 한 번 보고 갈게요
저는 다음그림과 같이 생성되어있습니다

 

혹시 오류가 난다면 위치들 잘 만들어놨는 지도 확인해주세요!!

 

 


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>
                    <li><Link to="/fabcar">중고차시장</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/connect')
        .then((response)=>{
            console.log(response);
            
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    get=()=>{
        alert(this.id.value+ '의 잔액 보기');
        axios.post('/basic_network/get',{"id":this.id.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>
                <hr/>
                <br/> sacc 에 연동하기<br/>
                <div>
                <input placeholder='a' ref={ref=>this.id=ref} />의  {' '} 
                <button onClick={this.get}  > 잔액 보기</button><br/>               
                </div>
            </div>
        );
    }
}
class FirstNetwork extends Component{  
 
    render(){
        return(
            <div>
                <h2>FirstNetwork에 연결 해보세요</h2>                
            </div>
        );
    }
}

class Fabcar extends Component{  
    queryAllCars=()=>{
        alert("^____^");

        axios.get('/fabcar/queryAllCars')
        .then((res)=>{
            console.log(res);
        })
        .catch((err)=>{
            console.log(err);
        });
    }

    wallet=()=>{
        alert("^^");

        axios.get('/fabcar/wallet')
        .then((res)=>{
            console.log(res);
        })
        .catch((err)=>{
            console.log(err);
        });
    }
 
 render(){
     return(
         <div>
             <h2>중고차 시장에 오신 걸 환영합니다</h2> 
             <br/>
             <button onClick={this.wallet}>지갑 생성</button> 
             <hr/>
             <br/>
             <button onClick={this.queryAllCars}>모든 중고차 조회</button>              
         </div>
     );
 }
}
 
ReactDOM.render(
    (<Router>
        <Route path="/" component={Main} >   
            <Route path="basic" component={BasicNetwork}/>
            <Route path="first" component={FirstNetwork} />
            <IndexRoute component={Home} />
            <Route path="fabcar" component={Fabcar} />
        </Route>
    </Router>)
    ,document.getElementById("root")
);
 

 

fabcar_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, '..' , 'a', '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('/wallet', 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('/queryAllCars', async (req, res, next) => {
    try{
    console.log("queryAllCars...");
    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('fabcar');
       
        const result = await contract.evaluateTransaction('queryAllCars');
 
        console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
        res.json({'msg':result.toString()});
 
    }catch(e){
        console.log(e);
        res.json({'msg':'query error'});
    }
    }
);
 
/* POST */
router.post('/set', async (req, res, next) => {
    try{
    console.log("set : ", req.body.id, 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');
 
        await contract.submitTransaction('set',`${req.body.id}`,`${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에서 다음 queryAllCars 메서드 부분을 고칠게요

 

 queryAllCars=()=>{
        alert("^____^");

        axios.get('/fabcar/queryAllCars')
        .then((res)=>{
            console.log(res.data.msg);
            this.setState({
                allCars:res.data.msg
            });
        })
        .catch((err)=>{
            console.log(err);
        });
    }

 

 

아랫 부분의 render 함수 도 다음과 같이 고칠게요

 

render(){
     return(
         <div>
             <h2>중고차 시장에 오신 걸 환영합니다</h2> 
             <br/>
             <button onClick={this.wallet}>지갑 생성</button> 
             <hr/>
             <br/>
             <button onClick={this.queryAllCars}>모든 중고차 조회</button>              
             <br/>
             <div> {this.state.allCars} </div>
            
         </div>
     );
 }

 

 

이제 firefox에서 확인!!

 

다음 체크부분 클릭 클릭 클릭

 

 

 

그럼 중고차들이 촤르르르륵 뜨는 것을 볼 수 있쥬!

 

 

 

 


이제 우리가 차를 등록을 해보려고합니다

 

 

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>
                    <li><Link to="/fabcar">중고차 시장</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/connect')
        .then((response)=>{
            console.log(response);
            
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    get=()=>{
        alert(this.id.value+'의 잔액보기');
        axios.post('/basic_network/get',{"id":this.id.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>
                <hr/>
                <br/> sacc 에 연동하기<br/>
                <div>
                <input placeholder='a' ref={ref=>this.id=ref} />의  {' '} 
                <button onClick={this.get}  > 잔액 보기</button><br/>               
                </div>
            </div>
        );
    }
}
class FirstNetwork extends Component{  
 
    render(){
        return(
            <div>
                <h2>FirstNetwork에 연결 해보세요</h2>                
            </div>
        );
    }
}

class Fabcar extends Component{
    state={
        allCars:null
    }
    createCar=()=>{
        const data={
            'carno':this.carno.value,
            'maker':this.maker.value,
            'model':this.model.value,
            'color':this.color.value,
            'owner':this.owner.value
        }
        alert(JSON.stringify(data));

        axios.post('/fabcar/createCar',data)
        .then((res)=>{
            alert(res.data.msg);
            console.log(res.data.msg);
        })
        .catch((err)=>{
            console.log(err);
        });
    }
    queryAllCars=()=>{
        alert("모든 중고차 조회중..");

        axios.get('/fabcar/queryAllCars')
        .then((res)=>{
            console.log(res.data.msg);
            this.setState({
                allCars:res.data.msg
            });
        })
        .catch((err)=>{
            console.log(err);
        });
    }
    wallet=()=>{
        alert("^^");

        axios.get('/fabcar/wallet')
        .then((res)=>{
            console.log(res.data.msg);
            this.setState({
                allCars:res.data.msg
            });
        })
        .catch((err)=>{
            console.log(err);
        });
    }
 
    render(){
        return(
            <div>
                <h2>중고차 시장에 오신 걸 환영합니다</h2> 
                <br/>
                <button onClick={this.wallet}>지갑 생성</button>
                <hr/>
                <br/>
                CARNO <input ref={ref=>this.carno=ref}/><br/>
                MAKER <input ref={ref=>this.maker=ref}/><br/>
                MODEL <input ref={ref=>this.model=ref}/><br/>
                COLOR <input ref={ref=>this.color=ref}/><br/>
                OWNER <input ref={ref=>this.owner=ref}/><br/>
                <button onClick={this.createCar}>중고차 등록하기</button>
                <hr/>
                <button onClick={this.queryAllCars}>모든 중고차 조회</button>
                <br/>
                <div>{this.state.allCars}</div>
            </div>
        );
    }
}
 
ReactDOM.render(
    (<Router>
        <Route path="/" component={Main} >   
            <Route path="basic" component={BasicNetwork}/>
            <Route path="first" component={FirstNetwork} />
            <Route path="fabcar" component={Fabcar} />
            <IndexRoute component={Home} />
        </Route>
    </Router>)
    ,document.getElementById("root")
);

 

 

fabcar_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, '..' , 'a', '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('/wallet', 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('/queryAllCars', async (req, res, next) => {
    try{
    console.log("queryAllCars : ");
    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('fabcar');
       
        const result = await contract.evaluateTransaction('queryAllCars');
 
        console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
        res.json({'msg':result.toString()});
 
    }catch(e){
        console.log(e);
        res.json({'msg':'query error'});
    }
    }
);
 
/* POST */
router.post('/createCar', async (req, res, next) => {
    try{
    console.log("createCar : ", req.body.carno);
    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('fabcar');
 
        await contract.submitTransaction('createCar',`${req.body.carno}`,`${req.body.maker}`
        ,`${req.body.model}`,`${req.body.color}`,`${req.body.owner}`);
        console.log(`Transaction has been submitted`);
        res.json({'msg':'ok'});
    }catch(e){
        console.log(e);
        res.json({'msg':'send error'});
    }
    }
);
 
module.exports = router;

 

 

firefox로 가서 새로고침!!!

 

 

10번 차 모델을 등록해볼게요:)

 

 

다음과 같이 alert창이 뜹니다

 

그리고 조회를 해서 잘 들어가있나해볼게요~

 

 

다음과 같이 10번 차량이 잘 등록되어있습니다

 

 

11번 차로 겉바속촉 차량(?)도 하나 등록해볼게요

 

 


 

728x90
반응형