Hyperledger

본문 바로가기
사이트 내 전체검색


Hyperledger
Hyperledger

9. Go언어로 체인코드 만들기

페이지 정보

작성자 관리자 댓글 3건 조회 11,356회 작성일 19-08-26 13:04

본문

9. Go언어로 체인코드 만들기

1.PNG 

2.PNG 

3.PNG 

4.PNG 

5.PNG 

6.PNG 

7.PNG 

8.PNG 

9.PNG 

10.PNG 

11.PNG 

12.PNG 

13.PNG 

14.PNG 

15.PNG 

16.PNG 

17.PNG 

18.PNG

 

 

 

 

터미널 1.

 

 

root@client:~# cd hyperledger/fabric-samples/chaincode
root@client:~/hyperledger/fabric-samples/chaincode# mkdir mysacc
root@client:~/hyperledger/fabric-samples/chaincode# cd mysacc/
root@client:~/hyperledger/fabric-samples/chaincode/mysacc# vi mysacc.go 

package main

import (
        "fmt"
        "github.com/hyperledger/fabric/core/chaincode/shim"
        "github.com/hyperledger/fabric/protos/peer"
)

// SimpleAsset implements a simple chaincode to manage an asset
type SimpleAsset struct {
}

// Init
func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response {
        // Get the args from the transaction proposal
        args := stub.GetStringArgs()
        if len(args) != 2 {
                return shim.Error("Incorrect arguments. Expecting a key and a value")
        }

        err := stub.PutState(args[0], []byte(args[1]))
        if err != nil {
                return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0]))
        }
        return shim.Success(nil)
}

// Invoke
func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
    // 트랜잭션에서 함수와 arg를 추출합니다.
    fn, args := stub.GetFunctionAndParameters()

    var result string
    var err error
    if fn == "set" {
            result, err = set(stub, args)
    } else {
            result, err = get(stub, args)
    }
    if err != nil {
            return shim.Error(err.Error())
    }

    // 결과를  반환합니다.
    return shim.Success([]byte(result))

}

// set 은 새 값으로 값을 대체합니다.
func set(stub shim.ChaincodeStubInterface, args []string) (string, error) {
     if len(args) != 2 {
          return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value")
     }

     err := stub.PutState(args[0], []byte(args[1]))
     if err != nil {
          return "", fmt.Errorf("Failed to set asset: %s", args[0])
     }
     return args[1], nil
}


// Get은 지정된 자산 키의 값을 반환합니다.
func get(stub shim.ChaincodeStubInterface, args []string) (string, error) {
     if len(args) != 1 {
          return "", fmt.Errorf("Incorrect arguments. Expecting a key")
     }

     value, err := stub.GetState(args[0])
     if err != nil {
          return "", fmt.Errorf("Failed to get asset: %s with error: %s", args[0], err)
     }
     if value == nil {
          return "", fmt.Errorf("Asset not found: %s", args[0])
     }
     return string(value), nil
}

func main() {
     if err := shim.Start(new(SimpleAsset)); err != nil {
          fmt.Printf("Error starting SimpleAsset chaincode: %s", err)
     }
} ​

 


root@client:~/hyperledger/fabric-samples/chaincode/mysacc# go get -u --tags nopkcs11 github.com/hyperledger/fabric/core/chaincode/shim

 

root@client:~/hyperledger/fabric-samples/chaincode/mysacc go build --tags nopkcs11
root@client:~/hyperledger/fabric-samples/chaincode/mysacc ls
mysacc  mysacc.go

root@client:~/hyperledger/fabric-samples/chaincode/mysacc cd
root@client:~# cd hyperledger/fabric-samples/chaincode-docker-devmode/
root@client:~/hyperledger/fabric-samples/chaincode-docker-devmode# vi docker-compose-simple.yaml 

 

 

    container_name: cli
    image: hyperledger/fabric-tools:1.4.0
    tty: true
    environment:
      - GOPATH=/opt/gopath
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - FABRIC_LOGGING_SPEC=DEBUG
      - CORE_PEER_ID=cli
      - CORE_PEER_ADDRESS=peer:7051
      - CORE_PEER_LOCALMSPID=DEFAULT
      - CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp
    working_dir: /opt/gopath/src/chaincodedev
    command: /bin/bash -c './script.sh'
    volumes:
        - /var/run/:/host/var/run/
        - ./msp:/etc/hyperledger/msp
        - ./../chaincode:/opt/gopath/src/chaincodedev/chaincode
        - ./:/opt/gopath/src/chaincodedev/
    depends_on:
      - orderer
      - peer

  chaincode:
    container_name: chaincode
    image: hyperledger/fabric-ccenv:1.4.0
    tty: true
    environment:
      - GOPATH=/opt/gopath
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - FABRIC_LOGGING_SPEC=DEBUG
      - CORE_PEER_ID=example02
      - CORE_PEER_ADDRESS=peer:7051
      - CORE_PEER_LOCALMSPID=DEFAULT
      - CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp
    working_dir: /opt/gopath/src/chaincode
    command: /bin/sh -c 'sleep 6000000'
    volumes:
        - /var/run/:/host/var/run/
        - ./msp:/etc/hyperledger/msp
        - ./../chaincode:/opt/gopath/src/chaincode
    depends_on:
      - orderer
      - peer 

 

root@client:~/hyperledger/fabric-samples/chaincode-docker-devmode# docker-compose -f docker-compose-simple.yaml down
Removing chaincode ... done
Removing cli       ... done
Removing peer      ... done
Removing orderer   ... done
Removing network chaincode-docker-devmode_default
root@client:~/hyperledger/fabric-samples/chaincode-docker-devmode# docker images -q | xargs docker rmi -f

 

root@client:~/hyperledger/fabric-samples/chaincode-docker-devmode# docker-compose -f docker-compose-simple.yaml up 

 

 

터미널 2.

 

root@client:~# cd hyperledger/fabric-samples/chaincode-docker-devmode/
root@client:~/hyperledger/fabric-samples/chaincode-docker-devmode# docker exec -it chaincode bash
root@04168a78c1c3:/opt/gopath/src/chaincode# cd mysacc
root@04168a78c1c3:/opt/gopath/src/chaincode/mysacc# go build
root@04168a78c1c3:/opt/gopath/src/chaincode/mysacc# CORE_PEER_ADDRESS=peer:7052 CORE_CHAINCODE_ID_NAME=mycc:0 ./mysacc

터미널 3.

root@client:~# cd hyperledger/fabric-samples/chaincode-docker-devmode/
root@client:~/hyperledger/fabric-samples/chaincode-docker-devmode# docker exec -it cli bash

root@60a6ee802e1e:/opt/gopath/src/chaincodedev# cd ..

root@60a6ee802e1e:/opt/gopath/src# ln -s chaincodedev/chaincode/mysacc ./


root@60a6ee802e1e:/opt/gopath/src/chaincodedev# peer chaincode install -p mysacc -n mycc -v 0

root@60a6ee802e1e:/opt/gopath/src/chaincodedev# peer chaincode instantiate -n mycc -v 0 -c '{"Args":["a","10"]}' -C myc
root@60a6ee802e1e:/opt/gopath/src/chaincodedev# peer chaincode invoke -n mycc -c '{"Args":["set", "a", "20"]}' -C myc

첨부파일

  • sacc.go (2.2K) 33회 다운로드 | DATE : 2019-11-21 09:45:29

댓글목록

관리자님의 댓글

관리자 작성일

root@client:~/hyperledger# mkdir -p $GOPATH/src/github.com/hyperledger
root@client:~/hyperledger# cd $GOPATH/src/github.com/hyperledger
root@client:~/gopath/src/github.com/hyperledger# ls
fabric
root@client:~/gopath/src/github.com/hyperledger# rm -rf fabric/
root@client:~/gopath/src/github.com/hyperledger# git clone -b release-1.4 https://github.com/hyperledger/fabric
'fabric'에 복제합니다...
remote: Enumerating objects: 124335, done.
remote: Total 124335 (delta 0), reused 0 (delta 0), pack-reused 124335
오브젝트를 받는 중: 100% (124335/124335), 101.60 MiB | 7.76 MiB/s, 완료.
델타를 알아내는 중: 100% (83974/83974), 완료.
파일을 가져옵니다: 100% (4735/4735), 완료.
root@client:~/gopath/src/github.com/hyperledger#

관리자님의 댓글

관리자 작성일

root@client:~/gopath/src/github.com/hyperledger# cd
root@client:~# cd hyperledger/
root@client:~/hyperledger# rm -rf fabric-samples/

root@client:~/hyperledger# git clone git://github.com/hyperledger/fabric-samples.git
'fabric-samples'에 복제합니다...
remote: Enumerating objects: 12, done.
remote: Counting objects: 100% (12/12), done.
remote: Compressing objects: 100% (12/12), done.
remote: Total 4252 (delta 2), reused 1 (delta 0), pack-reused 4240
오브젝트를 받는 중: 100% (4252/4252), 1.55 MiB | 1.50 MiB/s, 완료.
델타를 알아내는 중: 100% (2072/2072), 완료.
root@client:~/hyperledger#

관리자님의 댓글

관리자 작성일

root@client:~/hyperledger/fabric-samples/chaincode-docker-devmode# docker images -q | xargs docker rmi -f


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.