겉바속촉

[Hyperledger] 메서드 변경, transaction 생성, key생성 본문

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

[Hyperledger] 메서드 변경, transaction 생성, key생성

겉바속촉 2020. 8. 13. 17:37
728x90
반응형

이번에는 gedit화면으로 들어가서 메서드를 변경해보도록 할게요

 

 

invoke 메서드 부분을!!!

.

 

send로 고칠게요

 

 

 

 

query 메서드를!!!!

 

get 메서드로 고쳤습니다

 


 

버전 업그레이드

peer chaincode install -n jes_cc_node -v 1.1 -l node -p /opt/gopath/src/github.com/chaincode_example02/node/

 

 

upgrade를 하는 이유는 다음과 같습니다

처음에만 instantiate를 해주시면 되는 것이고 그 다음부터는 조금씩 변경되었다면 upgrade를 해주시면 됩니다

 

다만 많이 변경된 경우에 install을 하는 과정에서 앞자리 숫자를 다르게 주셔야합니다

그리고 upgrade는 동일한 버전을 넣어주시면 됩니다

 

 

 

터미널에서 확인해주었더니 하나 더 생겼습니다:)

아까는 두개 뿐이었는 데 업그레이드 시켰더니 세 개가 되었네요

 

 

 

 

이번에는 다음 명령을 내려줄거에요

 

peer chaincode upgrade -n jes_cc_node -v 1.1 -c '{"Args":["init", "a", "100","b","0"]}' -C mychannel

 

지금 계속 명령을 내리는 것은 application이 내리는 것입니다

작업은 peer가 하는 것이구요

 

확인은  ledger로 확인하는 것입니다

 

 

 

a 가 b에게 10을 송금하라는 invoke 명령을 내렸습니다

 

peer chaincode invoke -C mychannel -n jes_cc_node -c '{"Args":["send","a","b","10"]}'

 

 

a 를 확인해봤더니 90

 

peer chaincode query -C mychannel -n jes_cc_node -c '{"Args":["get","a"]}'
root@ad9711d6727d:/opt/gopath/src/github.com/chaincode_example02/node# peer chaincode query -C mychannel -n jes_cc_node -c '{"Args":["get","a"]}'
90

 

 

 

그럼 b도 확인 해볼게요 10이네요:)

 

root@ad9711d6727d:/opt/gopath/src/github.com/chaincode_example02/node# peer chaincode query -C mychannel -n jes_cc_node -c '{"Args":["get","b"]}'
10

 


 

파일 탐색기 오픈

 

Home - 0jes - HLF_WEB - MyWeb1

 

 

 

하나 더 열게요

 

Home - HLF - fabric-samples - basic-network 

다음과 같이 표시해준 connection.json 파일을 복사해올거에요

 

 

처음에 열어준 파일탐색기에다가 다음과 같은 이름으로 폴더를 만들었습니다

 

 

그리고 그 안에다가 connection

 

 

이제 vscode에서 확인해볼게요

 

 

그리고서 routes > 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 } = 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;

 

그리고 저장을 해주신 후에 package.json의 dependecy들을 내려받아야 하기 때문에

다음 명령어를 내려주세요

npm i

 

이제 다음 명령어로 server 준비해주세요

npm start

 

 

firefox 들어가면 저는 화면이 다음과 같이 뜹니다

여기서 BasicNetwor를 클릭한 후에 연결을 click!!!

그리고 검사창을 보시면 다음 표시한 것처럼 뜹니다

 

이제 다시 vscode로 가서 보면 다음과 같이 생긴 게 보입니다!!!

수행 후에 서버 측에 wallet 폴더가 생기고 admin의 개인키, 공개키, 주소가 생기는 것이쥬

 

 

이제 다시 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 } = 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;

 

 

firefox로 가서 아까처럼 연결을 한 번 눌러주세요

 

그리고 vscode로 와서 확인해보면.. user1이 생성된 게 보이는 군요

 user1의 개인키, 공개키, 주소가 들어온 거에요:)

 

 

여기 까지 모두 준비가 되었습니다

그래서 우리는 송금 transaction을 일으킬 수가 있겠쥬?

 


public> 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>
                </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');
 
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;
 
 

 

 

firefox로 가볼게요

 

왼쪽은 여태까지의 화면이었고 지금 코드를 변경해주고 난 화면이 오른쪽입니다

잔액 확인까지 할 수 있도록 바꿔준거에요:)

 

 

 

a가 b에게 2원을 보내봤습니다

그리고 잔액확인 click!!

a는 2원을 송금했기 때문에 88원이 남게 되네요:)

 

 

이제 b잔액도 확인하고 싶어서 코드를 조금씩 추가해볼게요

router.js로 가셔서 다음 표시한 것들을 추가했습니다

 

 

 

그리고 index.jsx로 가서 또 고쳐주세요

다음 코드 부분의 위치에 다음처럼 고쳐주시면 됩니다:)

 

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);
        });
    }

 

이제 저장 하고 firefox로 가서 확인 해줄게요

저는 전송을 계속 해서 지금 a와 b의 잔액이 다음과 같이 뜨네요:)

 

 

이제 화면을 좀 바꿔볼게요 더 이쁘게!!

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,
        b_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로 가서 새로고침

 

 

 

 

금액의 상태에 따라서 크기가 변화가 되고 있습니다

 

 

 

 

728x90
반응형