Block chain application development

A chain code example: information notary

Brief introduction

chaincode_example01.go  achieve the following main functions:

  • Initialization information stored in key-value;
  • Key allows read and modify.

Code, first initializes the  hello_world value chain and create the query request modified in accordance with the parameter  key values, to achieve a simple key database can be modified in nature.

The main function

  • read: Read the key  args[0] of the value;
  • write: Create or modify key  args[0] of value;
  • init: Initialization key  hello_world of value;
  • invoke: The transmission parameters corresponding to the type of call execution  init and  write functions;
  • query: Call  read function queries  args[0] for value.

Analysis of code to run

main As a function of entry program, the function calls the start of the shim pack, the inlet chaincode node starts a boot program. If an error is returned.

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

When the smart deployment contract on block chain can interact through rest api.

The three main functions are  init, invoke, query. In the three functions by  stub.PutStatethe  stub.GetStatekey-value pair stored in the ledger access.

REST API operations through intelligent contract

Log pbft clusters assume jim identity, request the deployment of the chaincode json request format:

{
    "jsonrpc": "2.0",
    "method": "deploy",
    "params": {
        "type": 1,
        "chaincodeID": {
            "path": "https://github.com/ibm-blockchain/learn-chaincode/finished"
        },
        "ctorMsg": {
            "function": "init",
            "args": [
                "hi there"
            ]
        },
        "secureContext": "jim"
    },
    "id": 1
}

Currently only supports directory path on github, ctorMsg as a function  init parameter passing.

json format calls invoke function is:

{
    "jsonrpc": "2.0",
    "method": "invoke",
    "params": {
        "type": 1,
        "chaincodeID": {
            "name": "4251b5512bad70bcd0947809b163bbc8398924b29d4a37554f2dc2b033617c19cc0611365eb4322cf309b9a5a78a5dba8a5a09baa110ed2d8aeee186c6e94431"
        },
        "ctorMsg": {
            "function": "init",
            "args": [
                "swb"
            ]
        },
        "secureContext": "jim"
    },
    "id": 2
}

Wherein the name field is  deploy a string field of the message in return.

query The interface is also similar.

Chain Code Example Two: Trading assets

Brief introduction

chaincode_example02.go  achieve the following main functions:

  • Initialization A, B two accounts, and assigned two initial values ​​for the asset accounts;
  • Asset transaction between A, B two accounts;
  • Queries are A, B two balance on the account, confirm that the transaction is successful;
  • Delete the account.

The main function

  • init: Initialization A, B two accounts;
  • invoke: Implement A, B transfers between accounts;
  • query: Query A, B balance on the account;
  • delete: Delete the account.

Dependent packages

import (
    "errors"
    "fmt"
    "strconv"

    "github.com/hyperledger/fabric/core/chaincode/shim"
)

strconv And conversion between the string type int.

In invoke the function, there are:

X, err = strconv.Atoi(args[2])
    Aval = Aval - X
    Bval = Bval + X

When  args[2]<0 the time, A account balance increase, decrease or B account balance.

Scalable functionality

Examples of new accounts and is not included in the initialization function. Developers can be added according to their business model.

Figures in the Currency Management

Brief introduction

The intelligent contract to implement a simple business case that digital currency issuance and transfer. Among this total is divided into three roles: central banks, commercial banks, corporations. Which the central bank can issue a certain amount of money, it can be mutual transfers between enterprises. The main achieve the following functions:

  • Initialization central bank and the number of currency
  • New commercial banks, while the central bank to issue a fixed number of its currency
  • New business
  • Commercial banks transferred a certain amount of digital currency to businesses
  • Mutual transfers between enterprises
  • Queries companies, banks, transaction information

The main function

  • init: Initialize the central bank and issue a certain amount of money;
  • invoke: Calls internal contracts;
  • query: Other relevant information;
  • createBank: New commercial banks, while the central bank issued a number of its currency;
  • createCompany: New business;
  • issueCoin: The central bank again issued certain amount of money (attributable to the transaction);
  • issueCoinToBank: The central bank transferred a certain amount of digital currency (attributable transaction) to commercial banks;
  • issueCoinToCp: Commercial banks transfer a certain amount of digital currency to businesses (attributable to transactions);
  • transfer: Mutual transfers carried out between enterprises (attributable to transactions);
  • getCompanys: Get all the company information, if the number is greater than 10 enterprises, to access the first 10;
  • getBanks: Get all the information commercial banks, commercial banks before if the number is greater than 10, the first visit 10
  • getTransactions: Get all transactions before 10 if the number of transactions is greater than 10, the first visit;
  • getCompanyById: A company acquired information;
  • getBankById: Get a bank information;
  • getTransactionBy: Get a record deal;
  • writeCenterBank: Modify the central bank information;
  • writeBank: Modify the Commercial Bank;
  • writeCompany: Modify the enterprise information;
  • writeTransaction: Writing transaction information.

Data structure design

  • centerBank Central Bank
    • Name: Name
    • TotalNumber: The total amount of currency issued
    • RestNumber: Account Balance
    • ID: ID is fixed at 0
  • bank commercial bank
    • Name: Name
    • TotalNumber: Total amount of money received
    • RestNumber: Account Balance
    • ID: Bank ID
  • company business
    • Name: Name
    • Number: Account Balance
    • ID: corporate ID
  • transaction transaction content
    • FromType: sender role // centerBank: 0, Bank: 1, Company: 2
    • FromID: Sender ID
    • ToType: recipient role // Bank: 1, Company: 2
    • ToID: recipient ID
    • Time: trading hours
    • Number: amount of the transaction
    • ID: Transaction ID

Interface Design

init

request parameters:

args[0] 银行名称
args[1] 初始化发布金额

response parameters:

{"Name":"XXX","TotalNumber":"0","RestNumber":"0","ID":"XX"}

createBank

request parameters:

args[0] 银行名称

response parameters:

{"Name":"XXX","TotalNumber":"0","RestNumber":"0","ID":"XX"}

createCompany

request parameters:

args[0] 公司名称

response parameters:

{"Name":"XXX","Number":"0","ID":"XX"}

issueCoin

request parameters:

args[0] 再次发行货币数额

response parameters:

{"FromType":"0","FromID":"0","ToType":"0","ToID":"0","Time":"XX","Number":"XX","ID":"XX"}

issueCoinToBank

request parameters:

args[0] 商业银行ID
args[1] 转账数额

response parameters:

{"FromType":"0","FromID":"0","ToType":"1","ToID":"XX","Time":"XX","Number":"XX","ID":"XX"}

issueCoinToCp

request parameters:

args[0] 商业银行ID
args[1] 企业ID
args[2] 转账数额

response parameters:

{"FromType":"1","FromID":"XX","ToType":"2","ToID":"XX","Time":"XX","Number":"XX","ID":"XX"}

transfer

request parameters:

args[0] 转账用户ID
args[1] 被转账用户ID
args[2] 转账余额

response parameters:

{"FromType":"2","FromID":"XX","ToType":"2","ToID":"XX","Time":"XX","Number":"XX","ID":"XX"}

getBanks

response parameters

[{"Name":"XXX","Number":"XX","ID":"XX"},{"Name":"XXX","Number":"XX","ID":"XX"},...]

getCompanys

response parameters

[{"Name":"XXX","TotalNumber":"XX","RestNumber":"XX","ID":"XX"},{"Name":"XXX","TotalNumber":"XX","RestNumber":"XX","ID":"XX"},...]

getTransactions

response parameters

[{"FromType":"XX","FromID":"XX","ToType":"XX","ToID":"XX","Time":"XX","Number":"XX","ID":"XX"},{"FromType":"XX","FromID":"XX","ToType":"XX","ToID":"XX","Time":"XX","Number":"XX","ID":"XX"},...]

getCenterBank

response parameters

[{"Name":"XX","TotalNumber":"XX","RestNumber":"XX","ID":"XX"}]

getBankById

request parameters

args[0] 商业银行ID

response parameters

[{"Name":"XX","TotalNumber":"XX","RestNumber":"XX","ID":"XX"}]

getCompanyById

request parameters

args[0] 企业ID

response parameters

[{"Name":"XXX","Number":"XX","ID":"XX"}]

getTransactionById

request parameters

args[0] 交易ID

response parameters

{"FromType":"XX","FromID":"XX","ToType":"XX","ToID":"XX","Time":"XX","Number":"XX","ID":"XX"}

writeCenterBank

request parameters

CenterBank

response parameters

err  nil 为成功

writeBank

request parameters

Bank

response parameters

err  nil 为成功

writeCompany

request parameters

Company

response parameters

err  nil 为成功

writeTransaction

request parameters

Transaction

response parameters

`` `Err nil for the success ???

other

In order to take into account the query read rate, some of the information stored in the backup database on a non-block chain is also a good choice.

academic certificate

Functional Description

The  smart contract  implements a simple case of credit management. For certification in the field of education, due to the public treaty, the treaty can not be outside tampering features, with natural stability and neutrality.

The smart contract three roles are as follows:

  • school
  • personal
  • Qualifications required certification institutions or companies

Schools can be granted in accordance with the relevant information on the block chain by personal qualifications, relevant agencies can check a person's educational background information, the use of the private key signature to ensure that the real information is valid. For simplicity, try to simplify related business, and the other did not finish school students drop out for disciplinary or start to go out, schools can modify their respective education information.

Account should be generated by the client private key locally installed, for simplicity in the present embodiment, using analog private and public keys.

Data structure design

  • school
    • name
    • location
    • Account address
    • Account public
    • Private account
    • School students
  • personal
    • Full name
    • Account address
    • Past academic
  • Education Information
    • No education information
    • Current school
    • Year school
    • Complete school year
    • Attending state // 0: Graduation 1: Withdrawal
  • Modify Record (also corresponding to a modification of the enrollment records)
    • Numbering
    • School account address (typically the address can be calculated based on the account public address, then can be verified)
    • Signature School
    • Personal account address
    • Individual public address (public key individuals do not need to address)
    • Change the time
    • // modify operation 0: Normal graduation 1: Withdrawal 2: Entry

The operation of academic information for all of the property of the recording operation.

function and their respective functions implemented

  • init Initialization function
  • invoke The contract calls internal function

  • updateDiploma Update by the school student academic information, and signature (return record information)

  • enrollStudent School enrollment (back to school information)
  • createSchool Adding a new school
  • createStudent Adding a new student
  • getStudentByAddress Visiting students through education student account address information
  • getRecordById Obtaining records by Id
  • getRecords Get all records (if the number of records is greater than 10, return to the previous 10)
  • getSchoolByAddress Schools get information through the school account address
  • getBackgroundById Get the stored information by academic qualifications Id

  • writeRecord Written record

  • writeSchool Write the newly created school
  • writeStudent Students write the newly created

Interface Design

createSchool

request parameters:

args[0] 学校名称
args[1] 学校所在位置

response parameters:

学校信息的字节数组,当创建一所新学校时,该学校学生账户地址列表为空

createStudent

request parameters:

args[0] 学生的姓名

response parameters:

学生信息的字节数组表示,刚创建过往学历信息列表为空

updateDiploma

request parameters

args[0] 学校账户地址
args[1] 学校签名
args[2] 待修改学生的账户地址
args[3] //对该学生的学历进行怎样的修改,0:正常毕业  1:退学

response parameters

返回修改记录的字节数组表示

enrollStudent

request parameters:

args[0] 学校账户地址
args[1] 学校签名
args[2] 学生账户地址

response parameters

返回修改记录的字节数组表示

getStudentByAddress

request parameters

args[0] address

response parameters

学生信息的字节数组表示

getRecordById

request parameters

args[0] 修改记录的ID

response parameters

修改记录的字节数组表示

getRecords

response parameters

获取修改记录数组(如果个数大于10,返回前10个)

getSchoolByAddress

request parameters

args[0] address

response parameters

学校信息的字节数组表示

getBackgroundById

request parameters

args[0] ID

response parameters

学历信息的字节数组表示

test

Community Energy Share

Functional Description

This  agreement  with experimental energy micro-grid in New York, for example, as a simple case be realized.

"In the side of President Avenue, five family generation by solar panels; on the other side of the street family of five can be purchased across the family does not need the power and network connection block chain is the transaction, almost no personnel involved. management can record transactions. "but this idea is very promising, can represent the future of community energy management systems. "

Grid developers LO3 founder Brooklyn micro Lawrence Orsini said:

"We are building a renewable electricity market, to test people for the purchase of electric power in the hands of each other whether interest on this street. If you produce energy in a very far away, there will be a lot of loss in transit, you will not get it power value. but if you are just across the street, you will be able to efficient use of energy. "

A memory in an area in a micro-grid energy, every household may be possible for producers but also for consumers. Some families have solar panels, solar panels remaining amount can be sold as a value of power, for simplicity, a home power unit 1 may be required to have sufficient power to household electric power purchase balance.

Account should be generated by the client private key locally installed, for simplicity in the present embodiment, using analog private and public keys. Each user's private key guid + "1", public key guid + "2". Signed as a way to simplify the private key + "1"

Data structure design

It is only one role for every household in the smart user contract.

  • Home users
    • Account address
    • // no part of the residual energy home solar panels, a value of 0
    • Account balance (e-money)
    • Numbering
    • // status 0: Not available for purchase, 1: buy
    • Public Key Account
    • Private account
  • Transaction (a transaction must have both the seller and the buyer of the public key signature, in order to admit the deal. Public key signature generation rules, public key + ID number of transactions to be created, in this type of transaction, as long as there are enough buyers the money, the seller transaction will automatically be signed)
    • The purchaser address
    • Seller address
    • Electricity sales
    • The amount of electricity trading
    • Numbering
    • transaction hour

function and their respective functions implemented

  • init Initialization
  • invoke The contract calls internal function
  • query Other relevant information
  • createUser Create a new user and add to the energy micro-mesh invoke
  • buyByAddress Buy a certain amount of power to invoke a one user
  • getTransactionById Acquisition transaction content query by id
  • getTransactions Acquisition transaction (if the transaction is greater than the number of 10 to get the first 10) query
  • getHomes Get the user (if the number of users is greater than 10, obtaining the first 10) Query
  • getHomeByAddress Obtain a user query by address
  • changeStatus A bit in the user modifies its status invoke

  • writeUser New users will be written to the key pair

  • writeTransaction Recording

    Interface Design

    createUser

request parameters:

args[0] 剩余能量值 
args[1] 剩余金额

response parameters:

新建家庭用户的json表示

buyByAddress

request parameters:

args[0] 卖家的账户地址
args[1] 买家签名
args[2] 买家的账户地址
args[3] 想要购买的电量数值

response parameters:

购买成功的话返回该transaction的json串。
购买失败返回error

getTransactionById

request parameters:

args[0] 交易编号

response parameters:

查询结果的transaction 交易表示

getTransactions

request parameters:

none

response parameters:

获取所有的交易列表(如果交易大于10,则返回前10个)

getHomeByAddress

request parameters

args[0] address

response parameters

用户信息的json表示

getHomes

response parameters

获取所有的用户列表(如果用户个数大于10,则返回前10个)

changeStatus

request parameters:

args[0] 账户地址
args[1] 账户签名
args[2] 对自己的账户进行的操作,0:设置为不可购买  1:设置状态为可购买

response parameters:

修改后的用户信息json表示

test

 

Guess you like

Origin blog.csdn.net/shangsongwww/article/details/90298614