Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Client側で秘密鍵&公開鍵を作成してtransaction実行させてみる #9

Closed
shohu opened this issue Jun 11, 2019 · 5 comments
Projects

Comments

@shohu
Copy link
Owner

shohu commented Jun 11, 2019

概要

front側をReactNativeでやってみる。必要があればAPIはExpressで。

作業手順

  1. 一旦、ReactNativeでfabricとやりとりして色々できるか試す。
  2. fabricだけで足りない部分を expressでAPI側部分を作成する

参考

https://fabric-sdk-node.github.io/release-1.4/tutorial-sign-transaction-offline.html

@shohu shohu created this issue from a note in master (In progress) Jun 11, 2019
@shohu
Copy link
Owner Author

shohu commented Jun 11, 2019

Building your first network.

手順

genesis block作成

$ brew tap hyperledger/fabric
$ brew install fabric-tools@1.3.0
$ cd first-network/
$ ./byfn.sh generate
Generating certs and genesis block for channel 'mychannel' with CLI timeout of '10' seconds and CLI delay of '3' seconds
Continue? [Y/n] Y
proceeding ...

network起動

$ ./byfn.sh up -l node
: 
===================== Query successful on peer1.org2 on channel 'mychannel' =====================

========= All GOOD, BYFN execution completed ===========


 _____   _   _   ____
| ____| | \ | | |  _ \
|  _|   |  \| | | | | |
| |___  | |\  | | |_| |
|_____| |_| \_| |____/

network確認

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
345482a3b516        bridge              bridge              local
26a5f2507ed8        host                host                local
4c6dd88934d6        net_byfn            bridge              local

備考

cryptogen tool not found. exiting

How do I resolve the error on hyperledger fabric?

$ brew tap hyperledger/fabric
$ brew install fabric-tools@1.3.0

で cryptogen をインストール

Failed to reach implicit threshold of 1 sub-policies, required 1 remaining: permission denied

以下でnetworkを削除してから

$ ./byfn.sh down

再度

$ ./byfn.sh up -l node

@shohu
Copy link
Owner Author

shohu commented Jun 12, 2019

How to sign a transaction by an identity's private key

以下手順のtestソース
https://github.com/hyperledger/fabric-sdk-node/blob/release-1.4/test/integration/signTransactionOffline.js

1. unsigned transaction proposalを作成。

この PEM encoded certificate content は、pemファイルの文字列をそのまま入れればOK?

const certPem = '<PEM encoded certificate content>';
const mspId = 'Org1MSP'; // the msp Id for this org

const transactionProposal = {
    fcn'move',
    args['a', 'b', '100'],
    chaincodeId'mychaincodeId',
    channelId'mychannel',
};
const { proposal, txId } = channel.generateUnsignedProposal(transactionProposal, mspId, certPem);
// now we have the 'unsigned proposal' for this transaction

2. バイト数計算。 calculate the hash of the transaction proposal bytes.

hashFunctionは sha256D とかにしておけばいいだか。

const proposalBytes = proposal.toBuffer(); // the proposal comes from step 1
const hashFunction = xxxx; // A hash function by the user's desire
const digest = hashFunction(proposalBytes); // calculate the hash of the proposal bytes

3. 署名計算 - calculate the signature for this transaction proposal

// This is a sample code for signing the digest from step 2 with EC.
// Different signature algorithm may have different interfaces

const elliptic = require('elliptic');
const { KEYUTIL } = require('jsrsasign');

const privateKeyPEM = '<The PEM encoded private key>';
const { prvKeyHex } = KEYUTIL.getKey(privateKeyPEM); // convert the pem encoded key to hex encoded private key

const EC = elliptic.ec;
const ecdsaCurve = elliptic.curves['p256'];

const ecdsa = new EC(ecdsaCurve);
const signKey = ecdsa.keyFromPrivate(prvKeyHex, 'hex');
const sig = ecdsa.sign(Buffer.from(digest, 'hex'), signKey);

// now we have the signature, next we should send the signed transaction proposal to the peer
const signature = Buffer.from(sig.toDER());
const signedProposal = {
    signature,
    proposal_bytesproposalBytes,
};

4. 署名されたProposalをpeerに送信

const sendSignedProposalReq = { signedProposal, targets };
const proposalResponses = await channel.sendSignedProposal(sendSignedProposalReq);
// check the proposal responses, if all good, commit the transaction

5. unsigned transactionを作成

const commitReq = {
    proposalResponses,
    proposal,
};

const commitProposal = await channel.generateUnsignedTransaction(commitReq);

6. transactionを署名

const signedCommitProposal = signProposal(commitProposal);

7. 署名transactionをcommitする

const response = await channel.sendSignedTransaction({
    signedProposalsignedCommitProposal,
    requestcommitReq,
});

// response.status should be 'SUCCESS' if the commit succeed

8. ChannelEventHub用の eventhub registrationを作成 - generate an unsigned eventhub registration for the ChannelEventHub.

const unsignedEvent = eh.generateUnsignedRegistration({
    certificatecertPem,
    mspId,
});

9. eventhub registrationを署名 - sign the unsigned eventhub registration with the user's private key

const signedProposal = signProposal(unsignedEvent);
const signedEvent = {
    signaturesignedProposal.signature,
    payloadsignedProposal.proposal_bytes,
};

10. このChannelEventHubをPeerに登録

channelEventHub.connect({signedEvent});

@shohu
Copy link
Owner Author

shohu commented Jun 12, 2019

Front の Vue を動かす

https://github.com/hyperledger/fabric-sdk-node/blob/release-1.4/test/integration/signTransactionOffline.js

以下ページを参考にした
https://qiita.com/sin_tanaka/items/6d5d9089eb76dda4ce88

1. ネットワーク起動しておく

#9 (comment)

2. Dockerコンテナ作成

Dockerfile

FROM node:8.16

COPY . /front
WORKDIR /front

RUN npm install -g vue vue-cli

docker-compose.yaml

version: '2'

networks:
  basic:
    external:
      name: net_byfn

services:
  front:
    container_name: estatefront
    image: estate/front
    build:
      context: ./front
    tty: true
    ports:
        - 13333:8080
    volumes:
        - ./front:/front
    networks:
        - basic

3. vue sampleアプリ作成

# vue init webpack tutorial_vuejs_todo_management

? Project name todo
? Project description todo
? Author shohu
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests Yes
? Pick a test runner jest
? Setup e2e tests with Nightwatch? Yes
? Should we run `npm install` for you after the project has been created? (recommended) npm

4. 起動

./tutorial_vuejs_todo_management/build/webpack.dev.conf.js
に以下を追加。macからcontainerにアクセス可能にするため

  devServer: {
    : 
    host: '0.0.0.0',
    disableHostCheck: true
  },

そのあとに起動

$ npm run dev

5. 確認

http://localhost:13333/#/

スクリーンショット 2019-06-12 16 15 41

@shohu
Copy link
Owner Author

shohu commented Jun 12, 2019

Vueでjsを呼び出すところまで

これやったら、fabricのjs呼び出せるか試してみる。

Vue.jsで外部jsファイルを読み込んで関数を呼び出す方法

調査

以下のようにbrowserのconsoleでエラーが出てしまう。
どうも、fsモジュールが fabric 内で使われていてそれが webpack で読み込めないって言われてるっぽい

file.js?7907:152 Uncaught TypeError: existsSync is not a function
    at exports.File.File.loadSync (file.js?7907:152)
    at exports.Provider.Provider.add (provider.js?5961:136)
    at exports.Provider.Provider.file (provider.js?5961:63)
    at Config.reorderFileStores (Config.js?a0b0:71)
    at Object.eval (FabricCAServices.js?47f9:25)
    at eval (FabricCAServices.js:449)
    at Object../node_modules/fabric-ca-client/lib/FabricCAServices.js (app.js:2095)
    at __webpack_require__ (app.js:679)
    at fn (app.js:89)
    at eval (index.js?0171:23)

NodeJS (Webpack): fs.existsSync is not a function

結論

Browserifyで"fs.readFileSync is not a function"

web で fs モジュールはロードできない

node.js ベースのlibは browserでは使えないので、fabric を vue でやるのは無理っぽい。
このため、API側でやる部分とClient側でやる部分をもう少し検討する必要がある。

少なくとも hyperledgerのlib使っているものは api側でやらないといけないようだ。

ただ、

const { proposal, txId } = channel.generateUnsignedProposal(transactionProposal, mspId, certPem);

の時点で秘密鍵をAPI側にわたさなければいけない、、、

備考

sass install

$ npm install sass-loader node-sass --save-dev

@shohu
Copy link
Owner Author

shohu commented Jun 12, 2019

ブラウザから呼び出すのは難しいのでモバイル端末ならOK?

Reactnativeならjs使えるっぽいな、、、これならば端末内に 秘密鍵 保持したままCAなどとやりとりできる。
https://qiita.com/takehiro224/items/d60243820b069197e4ba

あ、でもFlutterからjsライブラリ呼び出せるんだ。
Hummingbird: FlutterでWebアプリを作る構想

FlutterからDartライブラリを呼び出すことはもちろん全く問題ない。FlutterからJavaScriptライブラリを呼び出すには、package:jsとdart:jsを利用する。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
master
  
Done
Development

No branches or pull requests

1 participant