2024-03-30
区块链学习笔记
0
请注意,本文编写于 732 天前,最后修改于 732 天前,其中某些信息可能已经过时。

目录

FISCO-BCOS 2.0搭建教程
一、环境准备
1.能ping通外网
2. 关闭防火墙
3.设置root用户密码
4.更新软件包
5.安装openssl curl
6.安装ssh.server
二、搭建区块链网络
1. 创建fisco目录
2.下载一键部署脚本 build_chain.sh
3.搭建单群组4节点联盟链
4.启动联盟链
5.检查进程
6.检查日志输出
三、配置及使用控制台
1.安装java
2.获取控制台脚本
3.拷贝控制台配置文件
4.拷贝节点证书
5.启动控制台
四、部署及调用HelloWorld合约
1.部署HelloWorld合约
2.调用HelloWorld合约
3.退出控制台

FISCO-BCOS 2.0搭建教程

一、环境准备

  1. 安装虚拟机
  2. IP地址
  3. 主机名称
  4. 内存4G
  5. 硬盘20G

以上配置可根据自己电脑配置进行修改
虚拟机配置要求如下(本文Linux系统全部以ubuntu-22.04.2-desktop-amd64为例)

1.能ping通外网

shell
[root@fisco ~]# ping www.baidu.com PING www.baidu.com (14.215.177.39) 56(84) bytes of data. 64 bytes from 14.215.177.39 (14.215.177.39): icmp_seq=1 ttl=128 time=8.60 ms 64 bytes from 14.215.177.39 (14.215.177.39): icmp_seq=2 ttl=128 time=7.72 ms

2. 关闭防火墙

shell
sudo ufw disable

3.设置root用户密码

shell
sudo passwd root

4.更新软件包

shell
sudo apt-get update

5.安装openssl curl

shell
sudo apt install -y openssl curl

6.安装ssh.server

shell
sudo apt install ssh.server

二、搭建区块链网络

1. 创建fisco目录

在 /opt 下创建 fisco目录

shell
mkdir ~/fisco && cd ~/fisco

2.下载一键部署脚本 build_chain.sh

shell
curl -#LO https://github.com/FISCO-BCOS/FISCO-BCOS/releases/download/v2.9.1/build_chain.sh && chmod u+x build_chain.sh

相关信息

如果因为网络问题导致长时间无法下载build_chain.sh脚本,请尝试 curl -#LO https://osp-1257653870.cos.ap-guangzhou.myqcloud.com/FISCO-BCOS/FISCO-BCOS/releases/v2.9.1/build_chain.sh && chmod u+x build_chain.sh

3.搭建单群组4节点联盟链

shell
bash build_chain.sh -l 127.0.0.1:4 -p 30300,20200,8545

相关信息

执行完成后会自动从fisco-bcos官方github仓库拉取对应版本的fisco-cos

shell
[INFO] Download speed is too low, try https://osp-1257653870.cos.ap-guangzhou.myqcloud.com/FISCO-BCOS/FISCO-BCOS/releases/v2.9.1/fisco-bcos.tar.gz

注意

注意:如果拉取失败请检查虚拟机网络是否连接上外网

命令执行成功会输出All completed 并生成nodes目录。如果执行出错,请检查nodes/build.log文件中的错误信息

shell
[INFO] All completed. Files in /home/fisco-bcos/fisco/nodes fisco-bcos@fiscobcos:~/fisco$ ls build_chain.sh nodes

4.启动联盟链

启动所有节点

shell
bash nodes/127.0.0.1/start_all.sh

正常情况下会输出以下内容

shell
try to start node0 try to start node1 try to start node2 try to start node3 node0 start successfully node2 start successfully node3 start successfully node1 start successfully

如果启动失败,请检查端口是否被占用netstat -an | grep tcp

5.检查进程

检查进程是否启动

shell
ps -ef | grep -v grep | grep fisco-bcos

正常情况会有类似下面的输出; 如果进程数不为4,则进程没有启动(一般是端口被占用导致的)

shell
fisco-b+ 5787 1 0 14:32 pts/1 00:00:05 /home/fisco-bcos/fisco/nodes/127.0.0.1/node0/../fisco-bcos -c config.ini fisco-b+ 5789 1 0 14:32 pts/1 00:00:05 /home/fisco-bcos/fisco/nodes/127.0.0.1/node2/../fisco-bcos -c config.ini fisco-b+ 5791 1 0 14:32 pts/1 00:00:05 /home/fisco-bcos/fisco/nodes/127.0.0.1/node3/../fisco-bcos -c config.ini fisco-b+ 5793 1 0 14:32 pts/1 00:00:05 /home/fisco-bcos/fisco/nodes/127.0.0.1/node1/../fisco-bcos -c config.ini

6.检查日志输出

查看节点node0链接的节点数

shell
tail -f nodes/127.0.0.1/node0/log/log* | grep connected

正常情况会不停地输出连接信息,从输出可以看出node0与另外3个节点有连接。

info
info|2024-03-30 14:48:35.968163|[P2P][Service] heartBeat,connected count=3 info|2024-03-30 14:48:45.968425|[P2P][Service] heartBeat,connected count=3 info|2024-03-30 14:48:55.968706|[P2P][Service] heartBeat,connected count=3

查看节点是否在共识

shell
tail -f nodes/127.0.0.1/node0/log/log* | grep ++++

正常情况会不停输出带有++++Generating seal的日志,即表示共识正常

shell
info|2024-03-30 14:54:39.199560|[g:1][CONSENSUS][SEALER]++++++++++++++++ Generating seal on,blkNum=1,tx=0,nodeIdx=3,hash=53792422... info|2024-03-30 14:54:43.221015|[g:1][CONSENSUS][SEALER]++++++++++++++++ Generating seal on,blkNum=1,tx=0,nodeIdx=3,hash=1f3918d1... info|2024-03-30 14:54:47.245364|[g:1][CONSENSUS][SEALER]++++++++++++++++ Generating seal on,blkNum=1,tx=0,nodeIdx=3,hash=48398121... info|2024-03-30 14:54:51.306289|[g:1][CONSENSUS][SEALER]++++++++++++++++ Generating seal on,blkNum=1,tx=0,nodeIdx=3,hash=d6a7fb27...

三、配置及使用控制台

1.安装java

shell
sudo apt install -y default-jdk

检查是否安装成功

shell
java --version openjdk 11.0.22 2024-01-16

注意

注意 如果已经安装好jdk可省略这一步

2.获取控制台脚本

shell
cd ~/fisco && curl -LO https://github.com/FISCO-BCOS/console/releases/download/v2.9.2/download_console.sh && bash download_console.sh

成功下载会输出 Download console successfully

shell
[INFO] Download console successfully [INFO] unzip console successfully

注意

如果因为网络问题导致长时间无法下载,请尝试 cd ~/fisco && curl -#LO https://gitee.com/FISCO-BCOS/console/raw/master-2.0/tools/download_console.sh && bash download_console.sh

3.拷贝控制台配置文件

拷贝配置文件

shell
cp console/conf/config-example.toml console/conf/config.toml

将config-example.toml 修改为 config.toml

shell
ls console/conf/ config.toml config-example.toml group-generate-config.toml log4j2.xml

注意

注意 若节点未采用默认端口,请将文件中的20200替换成节点对应的channel端口

4.拷贝节点证书

这一步的目的是为了让console 和节点连接起来

shell
cp nodes/127.0.0.1/sdk/* console/conf/

拷贝成功后 console/conf目录下会多出 ca.crt、sdk.crt、sdk.key三个文件

shell
ll console/conf 总计 36 drwxr-xr-x 2 fisco-bcos fisco-bcos 4096 3月 30 15:14 ./ drwxr-xr-x 6 fisco-bcos fisco-bcos 4096 11月 3 2022 ../ -rw-rw-r-- 1 fisco-bcos fisco-bcos 1208 3月 30 15:14 ca.crt -rw-r--r-- 1 fisco-bcos fisco-bcos 2851 3月 30 15:07 config-example -rw-r--r-- 1 fisco-bcos fisco-bcos 2851 11月 3 2022 config-example.toml -rw-r--r-- 1 fisco-bcos fisco-bcos 321 11月 3 2022 group-generate-config.toml -rw-r--r-- 1 fisco-bcos fisco-bcos 913 11月 3 2022 log4j2.xml -rw-rw-r-- 1 fisco-bcos fisco-bcos 1094 3月 30 15:14 sdk.crt -rw------- 1 fisco-bcos fisco-bcos 1704 3月 30 15:14 sdk.key

5.启动控制台

进入console目录 运行 start.sh 脚本

shell
cd console/ && bash start.sh

成功启动会出现FISCO-BCOS

shell
============================================================================================= Welcome to FISCO BCOS console(2.9.2)! Type 'help' or 'h' for help. Type 'quit' or 'q' to quit console. ________ ______ ______ ______ ______ _______ ______ ______ ______ | | \/ \ / \ / \ | \ / \ / \ / \ | $$$$$$$$\$$$$$| $$$$$$| $$$$$$| $$$$$$\ | $$$$$$$| $$$$$$| $$$$$$| $$$$$$\ | $$__ | $$ | $$___\$| $$ \$| $$ | $$ | $$__/ $| $$ \$| $$ | $| $$___\$$ | $$ \ | $$ \$$ \| $$ | $$ | $$ | $$ $| $$ | $$ | $$\$$ \ | $$$$$ | $$ _\$$$$$$| $$ __| $$ | $$ | $$$$$$$| $$ __| $$ | $$_\$$$$$$\ | $$ _| $$_| \__| $| $$__/ | $$__/ $$ | $$__/ $| $$__/ | $$__/ $| \__| $$ | $$ | $$ \\$$ $$\$$ $$\$$ $$ | $$ $$\$$ $$\$$ $$\$$ $$ \$$ \$$$$$$ \$$$$$$ \$$$$$$ \$$$$$$ \$$$$$$$ \$$$$$$ \$$$$$$ \$$$$$$ ============================================================================================= [group:1]>

注意

启动失败请检查控制台 conf.toml 和 sdk证书是否成功拷贝到console/conf目录下,以及java环境是否配置成功
请根据 3.1-3.4依次检查

四、部署及调用HelloWorld合约

1.部署HelloWorld合约

为了方便用户快速体验,HelloWorld合约已经内置于控制台中,位于控制台目录contracts/solidity/HelloWorld.sol
参考下面命令部署即可

shell
[group:1]> deploy HelloWorld

成功部署HelloWorld合约会输出以下内容

shell
transaction hash: 0x4b2a4e13dfd4ca4a1edd597dc78059c0c61013faa4f508458e4dc6545051f7e7 contract address: 0xe2396a436734e48a1e51979f0ce009ed854fe89a currentAccount: 0xb8af5a4338028d5dfc6ee974060d8631232bae38

相关信息

transaction hash:交易hash值
contract address:合约地址
currentAccount  :合约账户地址

2.调用HelloWorld合约

在控制台中内置了很多命令,可以通过 help 进行查看

shell
[group:1]> help * help([-h, -help, --h, --H, --help, -H, h]) Provide help information * addObserver Add an observer node * addPeers Add more connected peers to the node p2p network * addSealer Add a sealer node * call Call a contract by a function and parameters * callByCNS Call a contract by a function and parameters by CNS * chargeGas Charge specified gas for the given account * create Create table by sql * deductGas Deduct specified gas from the given account * delete Remove records by sql * deploy Deploy a contract on blockchain * deployByCNS Deploy a contract on blockchain by CNS * desc Description table information * erasePeers Remove connected peers of the node p2p network * quit([quit, q, exit]) Quit console * freezeAccount Freeze the account * freezeContract Freeze the contract * generateGroup Generate a group for the specified node * generateGroupFromFile Generate group according to the specified file * getAccountStatus GetAccountStatus of the account * getAvailableConnections Get the connection information of the nodes connected with the sdk * getBatchReceiptsByBlockHashAndRange Get batched transaction receipts according to block hash and the transaction range * getBatchReceiptsByBlockNumberAndRange Get batched transaction receipts according to block number and the transaction range * getBlockByHash Query information about a block by hash * getBlockByNumber Query information about a block by number * getBlockHashByNumber Query block hash by block number * getBlockHeaderByHash Query information about a block header by hash * getBlockHeaderByNumber Query information about a block header by block number * getBlockNumber Query the number of most recent block * getCode Query code at a given address * getConsensusStatus Query consensus status * getContractStatus Get the status of the contract * getCryptoType Get the current crypto type * getCurrentAccount Get the current account info * getDeployLog Query the log of deployed contracts * getGroupConnections Get the node information of the group connected to the SDK * getGroupList Query group list * getGroupPeers Query nodeId list for sealer and observer nodes * getNodeIDList Query nodeId list for all connected nodes * getNodeInfo Query the specified node information. * getNodeVersion Query the current node version * getObserverList Query nodeId list for observer nodes. * getPbftView Query the pbft view of node * getPeers Query peers currently connected to the client * getPendingTransactions Query pending transactions * getPendingTxSize Query pending transactions size * getSealerList Query nodeId list for sealer nodes * getSyncStatus Query sync status * getSystemConfigByKey Query a system config value by key * getTotalTransactionCount Query total transaction count * getTransactionByBlockHashAndIndex Query information about a transaction by block hash and transaction index position * getTransactionByBlockNumberAndIndex Query information about a transaction by block number and transaction index position * getTransactionByHash Query information about a transaction requested by transaction hash * getTransactionByHashWithProof Query the transaction and transaction proof by transaction hash * getTransactionReceipt Query the receipt of a transaction by transaction hash * getTransactionReceiptByHashWithProof Query the receipt and transaction receipt proof by transaction hash * grantCNSManager Grant permission for CNS by address * grantCharger Grant the charge permission for the given account * grantCommitteeMember Grant the account committee member * grantContractStatusManager Grant contract authorization to the user * grantContractWritePermission Grant the account the contract write permission. * grantDeployAndCreateManager Grant permission for deploy contract and create user table by address * grantNodeManager Grant permission for node configuration by address * grantOperator Grant the account operator * grantSysConfigManager Grant permission for system configuration by address * grantUserTableManager Grant permission for user table by table name and address * insert Insert records by sql * listAbi List functions and events info of the contract. * listAccount List the current saved account list * listCNSManager Query permission information for CNS * listChargers List the accounts that have the permission to charge/deduct gas * listCommitteeMembers List all committee members * listContractStatusManager List the authorization of the contract * listContractWritePermission Query the account list which have write permission of the contract. * listDeployAndCreateManager Query permission information for deploy contract and create user table * listDeployContractAddress List the contractAddress for the specified contract * listNodeManager Query permission information for node configuration * listOperators List all operators * listSysConfigManager Query permission information for system configuration * listUserTableManager Query permission for user table information * loadAccount Load account for the transaction signature * newAccount Create account * queryCNS Query CNS information by contract name and contract version * queryCommitteeMemberWeight Query the committee member weight * queryGroupStatus Query the status of the specified group of the specified node * queryPeers Query the configured connected node list of the p2p network * queryRemainGas Query remain gas for the given account * queryThreshold Query the threshold * queryVotesOfMember Query votes of a committee member. * queryVotesOfThreshold Query votes of updateThreshold operation * recoverGroup Recover the specified group of the specified node * registerCNS RegisterCNS information for the given contract * removeGroup Remove the specified group of the specified node * removeNode Remove a node * revokeCNSManager Revoke permission for CNS by address * revokeCharger Revoke the charge permission from the given account * revokeCommitteeMember Revoke the account from committee member * revokeContractStatusManager Revoke contract authorization to the user * revokeContractWritePermission Revoke the account the contract write permission * revokeDeployAndCreateManager Revoke permission for deploy contract and create user table by address * revokeNodeManager Revoke permission for node configuration by address * revokeOperator Revoke the operator * revokeSysConfigManager Revoke permission for system configuration by address * revokeUserTableManager Revoke permission for user table by table name and address * switch([s]) Switch to a specific group by group ID * select Select records by sql * setSystemConfigByKey Set a system config value by key * startGroup Start the specified group of the specified node * stopGroup Stop the specified group of the specified node * unfreezeAccount Unfreeze the account * unfreezeContract Unfreeze the contract * update Update records by sql * updateCommitteeMemberWeight Update the committee member weight * updateThreshold Update the threshold ---------------------------------------------------------------------------------------------

我们可以通过 getBlockNumber 命令查看当前 区块的高度,可以看到区块高度为1

shell
[group:1]> getBlockNumber 1

通过call命令调用HelloWorld合约中的方法

相关信息

call:Call a contract by a function and parameters
call:Call 通过函数和参数调用合约
用法: 关键字 合约名 合约地址 函数名 [参数]
call HelloWorld 0xe2396a436734e48a1e51979f0ce009ed854fe89a get #不带参数
call HelloWorld 0xe2396a436734e48a1e51979f0ce009ed854fe89a set "test set" #带参数
根据合约函数是否有形式参数进行添加。

shell
[group:1]> call HelloWorld 0xe2396a436734e48a1e51979f0ce009ed854fe89a get

通过以下命令我们可以成功调用HelloWorld合约中的get方法

shell
--------------------------------------------------------------------------------------------- Return code: 0 #状态码为0 则表示成功调用 description: transaction executed successfully #描述信息 Return message: Success #返回 Sucess 则表示 调用成功 --------------------------------------------------------------------------------------------- Return value size:1 #返回值大小 为一个参数 Return types: (STRING) #返回类型为srting Return values:(Hello, World!) #返回的内容为 Hello, World! ---------------------------------------------------------------------------------------------

继续查看区块高度,可以看到当前区块高度并没有增加,get方法只是查看,并不会改变

shell
[group:1]> getBlockNumber 1

继续调用HelloWorld合约中的set方法 并传递"test set"参数

shell
[group:1]> call HelloWorld 0xe2396a436734e48a1e51979f0ce009ed854fe89a set "test set"

成功调用HelloWorld合约中的set方法 ,并成功传入 "test set" 参数

shell
transaction hash: 0xd3f09c00c104373b6c31b14cde35917beed50c7f9b1c07ffa76d9b65f1372f97 --------------------------------------------------------------------------------------------- transaction status: 0x0 #交易状态码0x0 为交易成功 description: transaction executed successfully #描述信息 --------------------------------------------------------------------------------------------- Transaction inputs: #交易的输入集合 Input value size:1 #输入参数 为1个参数 Input types: (STRING) #输入参数类型 为string Input values:(test set) #输入内容 为 test set --------------------------------------------------------------------------------------------- Receipt message: Success #回执消息 为成功 Return message: Success #返回消息 为成功 Return values:[] #返回值 为空数组 --------------------------------------------------------------------------------------------- Event logs #事件日志 Event: {} #事件内容为空

再次查看区块高度,可以看到当前区块高度增加了,因为set方法会改变链的状态,每次改变相当于一笔交易

shell
[group:1]> getBlockNumber 2

调用HelloWorld合约中的get方法 查看返回值

shell
[group:1]> call HelloWorld 0xe2396a436734e48a1e51979f0ce009ed854fe89a get --------------------------------------------------------------------------------------------- Return code: 0 description: transaction executed successfully Return message: Success --------------------------------------------------------------------------------------------- Return value size:1 Return types: (STRING) Return values:(test set) #返回值 变成了set 传递的参数 test set ---------------------------------------------------------------------------------------------

3.退出控制台

控制台输入:quitCtrl + z退出控制台。

参考文档:fisco-bcos搭建第一个区块链网络 https://fisco-bcos-documentation.readthedocs.io/zh-cn/latest/docs/installation.html

本文作者:苏皓明

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!