BCSkill (Block chain skill ) 技术社区
社区QQ群:791420381
推荐论坛:https://eosfans.io
Telegram: https://t.me/bcskill

Web3j send ERC20 Token Demo

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../../libs/web3.js_v1.0.0-beta.35/web3.min.js"></script>
</head>
<body>

  <h1>Send ERC20 Token</h1>

  <h2>Notes</h2>
  <ul>
    <li>Use MetaMask</li>
    <li>To check ERC20 balance, use <a href="../getERC20TokenBalance/" target="_blank">getERC20TokenBalance</a></li>
  </ul>

  <h2>Token Address</h2>
  <input type="text" id="token-address" size="80" oninput="onAddressChange()"></input>
  <p>e.g. 0x2A65D41dbC6E8925bD9253abfAdaFab98eA53E34</p>

  <h2>Recipients Address</h2>
  <input type="text" id="to-address" size="80"></input>
  <p>e.g. 0x8Df70546681657D6FFE227aB51662e5b6e831B7A</p>

  <h2>Decimals</h2>
  <input type="number" id="decimals" size="40" readonly></input>

  <h2>Amount</h2>
  <input type="number" id="amount" size="40"></input>

  <div><button id="send" onclick="send()">Send ERC20 Token</button></div>

  <h2>Result</h2>
  <span id="result"></span>

  <script>

    var web3js;
    var account;

    function getERC20TokenBalance(tokenAddress, walletAddress, callback) {
      let minABI = [
        {"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"type":"function"},
        {"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"type":"function"}
      ];
      let contract = new web3js.eth.Contract(minABI, tokenAddress);
      contract.methods.balanceOf(walletAddress).call((error, balance) => {
        contract.methods.decimals().call((error, decimals) => {
          console.log(balance);
          console.log(decimals);
          balance = balance / (10**decimals);
          callback(balance);
        });
      });
    }

    function getERC20TokenContract(tokenAddress) {
      let minABI = [
        {"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"type":"function"},
        {"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"type":"function"},
        {"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"type":"function"}
      ];
      return new web3js.eth.Contract(minABI, tokenAddress);
    }

    function getERC20TokenDecimals(callback) {
      window.tokenContract.methods.decimals().call((error, decimals) => {
        callback(decimals);
      });
    }

    function onAddressChange(e) {
      let tokenAddress = document.getElementById('token-address').value;
      if(tokenAddress != "") {
        window.tokenContract = getERC20TokenContract(tokenAddress);
        getERC20TokenDecimals((decimals) => {
          document.getElementById('decimals').value = decimals;
        });
      }
    }

    function transferERC20Token(toAddress, value, callback) {
      window.tokenContract.methods.transfer(toAddress, value).send({from: account})
      .on('transactionHash', function(hash){
        callback(hash);
      });
    }

    function send() {
      var toAddress = document.getElementById('to-address').value;
      var decimals = web3js.utils.toBN(document.getElementById('decimals').value);
      var amount = web3js.utils.toBN(document.getElementById('amount').value);
      var sendValue = amount.mul(web3js.utils.toBN(10).pow(decimals));
      console.log(sendValue.toString());
      transferERC20Token(toAddress, sendValue, (txHash) => {
        document.getElementById('result').innerText = txHash;
      });
    }

    window.onload = function() {
      web3js = new Web3(Web3.givenProvider);
      console.log(web3js.version);
      var accountInterval = setInterval(function() {
        web3js.eth.getAccounts((error, address) => {
          if (address[0] !== account) {
            account = address[0];
            console.log(account);
          }
        });

      }, 300);
    }

  </script>

</body>
</html>

https://github.com/piyolab/sushiether/commit/e35e949b5d898d357f9bd1d4e3f35b679974f192

Hyperledger Fabric 演练 - 《基于联盟区块链的政务大数据共享》

1. 背景

为了继续深入研究Fabric的加密通道逻辑,找了一个现成的例子,并修正了一个新手部署可能遇到的问题,
修正的主要点是

  1. 修改实例代码相对fabric-samples路径,
  2. 细化一些操作步骤,方便新手傻瓜式运行

1.1 区域链(基于证书准入的联盟链)网络

1.2 业务流程时序

2. 演示系统环境

OS: Ubuntu 18.04
Fabric: release-1.4
Go: go1.14.4 linux/amd64
Docker: 19.03.11

3. 源代码仓库

gitee: https://gitee.com/BCSkill/fcc

4. 实例部署

4.1 克隆源代码

git clone https://gitee.com/BCSkill/fcc.git

4.2 部署fabric-samples运行环境

细节的话可以参考《fabric-samples 部署测试》,我们这里不做详细描述,直接运行封装好的脚本

./1-1.hy-sample.sh

大概过程中会分为几步,

  1. 克隆fabric-samples到当前源码目录
  2. 下载编译到好的fabric二进制文件,并解压到 fabric-samples/bin,记得将此目录添加到环境变量
  3. 拉取所需要的Docker镜像

4.3 启动示例网络,创建区块链网络(2个组织,每组织2个节点)

./1-2.startNetwork.sh

成功后输出========= All GOOD, BYFN execution completed ===========

4.4 加入第3个组织,2个节点

./2.addOrg3.sh

完成后,结果显示========= Org3 is now halfway onto your first network =========

4.5 部署政务智能合约,并实例化

./3-1.installNetcon.sh   #合约:网签合同备案
./3-2.installEstateBook.sh   #合约:不动产权证书
./3-3.installEstateTax.sh    #合约:不动产业务缴税

完成后,结果显示

Get instantiated chaincodes on channel mychannel:
Name: estatebook, Version: 1.0, Path: github.com/chaincode/estatebook, Escc: escc, Vscc: vscc
Name: estatetax, Version: 1.0, Path: github.com/chaincode/estatetax, Escc: escc, Vscc: vscc
Name: netcon, Version: 1.0, Path: github.com/chaincode/netcon, Escc: escc, Vscc: vscc

此时链环境和链合约已经部署好了。下面开始部署项目的服务端和Web前台

4.6 编译后台。

代码位于appcode/fccserver/src 可自行编译,或直接使用已编译完成的可执行文件

chmod +x appcode/fccserver/src/fccserver

启动后台容器

./4.startAppcli.sh
docker logs -f appcli

如果启动正常,会显示

[fcc-server] 2019/12/12 03:03:55 system db initiated successfully.
[fcc-server] 2019/12/12 03:03:56 Chaincode client initialed successfully.
[fcc-server] 2019/12/12 03:03:56 Server started on  :1206

4.7 编译和部署前端

前端采用VUE,也可使用其它前端框架或HTML。使用GNINX或其它WEB服务器部署编译后的前端代码。注:当前未使用登录和权限设置
前台部署依赖yarn,《ubuntu 安装最新版本 yarn》

cd ./appcode/fcc-client // 进到Web前端代码目录
yarn install            // 安装依赖
yarn serve              // 运行前端

如果出现
运行成功后,就会显示访问地址

  App running at:
  - Local:   http://localhost:8080/ 
  - Network: http://192.168.31.134:8080/

浏览器打开地址,就能看到实例演示了

在线演示

http://xujf000.tk:28888/#/

实例依赖Docker 镜像

surou@surou:~/go/src/github.com/chaincode/netcon$ docker ps
+ docker ps
CONTAINER ID        IMAGE                                                                                                        COMMAND                  CREATED             STATUS              PORTS                                        NAMES
f3b34643ff39        dev-peer0.org2.example.com-estatebook-1.0-08d85d200f6268a9c9656f01eac3d5325c44c1d2a93a1115168f63888a27206b   "chaincode -peer.add…"   44 minutes ago      Up 43 minutes                                                    dev-peer0.org2.example.com-estatebook-1.0
9828c2b46b4e        dev-peer0.org2.example.com-estatetax-1.0-975867dfc12f233b11d78db94c347aa6b7e94f1d389af7cc892cb8730652c110    "chaincode -peer.add…"   45 minutes ago      Up 45 minutes                                                    dev-peer0.org2.example.com-estatetax-1.0
9d62c54bfd73        dev-peer0.org2.example.com-netcon-1.0-8285fea29f8449473340c346dc0b6716a084576593325a33707353426d7298dc       "chaincode -peer.add…"   46 minutes ago      Up 46 minutes                                                    dev-peer0.org2.example.com-netcon-1.0
cb870db589c4        hyperledger/fabric-tools:1.4.3                                                                               "./fccserver"            About an hour ago   Up About an hour    0.0.0.0:1206->1206/tcp                       appcli
33ad280f1f17        dev-peer0.org1.example.com-estatetax-1.0-3284f6d77599d92fad2da964008b3f4bb78573eeb938f40e2110de2089455dc3    "chaincode -peer.add…"   About an hour ago   Up About an hour                                                 dev-peer0.org1.example.com-estatetax-1.0
fa575e9548e3        dev-peer0.org1.example.com-estatebook-1.0-1804a11c573ccbef46e7cda2314c1d76edc2fb52b0f7f9d10ed2024c03343aff   "chaincode -peer.add…"   About an hour ago   Up About an hour                                                 dev-peer0.org1.example.com-estatebook-1.0
75c50829fbb8        dev-peer0.org1.example.com-netcon-1.0-4faf315b9f1da5832e386fbae0d05157d269cff3802d770b0e8f135a69027796       "chaincode -peer.add…"   About an hour ago   Up About an hour                                                 dev-peer0.org1.example.com-netcon-1.0
15d29c21ed9a        hyperledger/fabric-tools:1.4.3                                                                               "/bin/bash"              2 hours ago         Up 2 hours                                                       Org3cli
d0ce2cc32019        hyperledger/fabric-peer:1.4.3                                                                                "peer node start"        2 hours ago         Up 2 hours          0.0.0.0:12051->12051/tcp                     peer1.org3.example.com
9bcf5082db71        hyperledger/fabric-peer:1.4.3                                                                                "peer node start"        2 hours ago         Up 2 hours          0.0.0.0:11051->11051/tcp                     peer0.org3.example.com
6f76cca2d809        hyperledger/fabric-tools:latest                                                                              "/bin/bash"              2 hours ago         Up 2 hours                                                       cli
04d61faad751        hyperledger/fabric-peer:latest                                                                               "peer node start"        2 hours ago         Up 2 hours          0.0.0.0:10051->10051/tcp                     peer1.org2.example.com
cdbffd49d7d2        hyperledger/fabric-peer:latest                                                                               "peer node start"        2 hours ago         Up 2 hours          0.0.0.0:8051->8051/tcp                       peer1.org1.example.com
d59fe735b96d        hyperledger/fabric-peer:latest                                                                               "peer node start"        2 hours ago         Up 2 hours          0.0.0.0:9051->9051/tcp                       peer0.org2.example.com
4caeb0c062e0        hyperledger/fabric-peer:latest                                                                               "peer node start"        2 hours ago         Up 2 hours          0.0.0.0:7051->7051/tcp                       peer0.org1.example.com
431ad6029954        hyperledger/fabric-ca:latest                                                                                 "sh -c 'fabric-ca-se…"   2 hours ago         Up 2 hours          7054/tcp, 0.0.0.0:8054->8054/tcp             ca_peerOrg2
4d69e9f76b1b        hyperledger/fabric-couchdb                                                                                   "tini -- /docker-ent…"   2 hours ago         Up 2 hours          4369/tcp, 9100/tcp, 0.0.0.0:5984->5984/tcp   couchdb0
1bcd9f89625f        hyperledger/fabric-couchdb                                                                                   "tini -- /docker-ent…"   2 hours ago         Up 2 hours          4369/tcp, 9100/tcp, 0.0.0.0:6984->5984/tcp   couchdb1
cb46fd7307cf        hyperledger/fabric-couchdb                                                                                   "tini -- /docker-ent…"   2 hours ago         Up 2 hours          4369/tcp, 9100/tcp, 0.0.0.0:8984->5984/tcp   couchdb3
ac996671c144        hyperledger/fabric-orderer:latest                                                                            "orderer"                2 hours ago         Up 2 hours          0.0.0.0:7050->7050/tcp                       orderer.example.com
c13cc3241b96        hyperledger/fabric-ca:latest                                                                                 "sh -c 'fabric-ca-se…"   2 hours ago         Up 2 hours          0.0.0.0:7054->7054/tcp                       ca_peerOrg1
01ce681daa6c        hyperledger/fabric-couchdb                                                                                   "tini -- /docker-ent…"   2 hours ago         Up 2 hours          4369/tcp, 9100/tcp, 0.0.0.0:7984->5984/tcp   couchdb2

参考

https://www.bcskill.com/index.php/archives/926.html

yarn错误The engine "node" is incompatible with this module

 yarn config set ignore-engines true

Chaincode installation on peer0.org1 has failed

v1.4 版本执行 ./byfn.sh up时,报如下错误

Error: error getting chaincode deployment spec for mycc: error getting chaincode package bytes: failed to calculate dependencies: incomplete package: github.com/hyperledger/fabric/core/chaincode/shim
!!!!!!!!!!!!!!! Chaincode installation on peer0.org1 has failed !!!!!!!!!!!!!!!!
========= ERROR !!! FAILED to execute End-2-End Scenario ===========

跟脚本代码是从(github)以下逻辑报出的

installChaincode() {
  PEER=$1
  ORG=$2
  setGlobals $PEER $ORG
  VERSION=${3:-1.0}
  set -x
  peer chaincode install -n mycc -v ${VERSION} -l ${LANGUAGE} -p ${CC_SRC_PATH} >&log.txt // 此处
  res=$?
  set +x
  cat log.txt
  verifyResult $res "Chaincode installation on peer${PEER}.org${ORG} has failed"
  echo "===================== Chaincode is installed on peer${PEER}.org${ORG} ===================== "
  echo
}

跟下逻辑,意思是说,以下依赖未找到(github

import (
    "fmt"
    "strconv"

    "github.com/hyperledger/fabric/core/chaincode/shim" // 未找到
    pb "github.com/hyperledger/fabric/protos/peer"
)

经过对比仓库分支代码,发现release-1.4是有的,最新的master分支已经删掉了。
直接参考2.0版本修改下吧
修改chaincode_example02.go

import (
    "bytes"
    "encoding/json"
    "fmt"
    "strconv"
    "strings"
    "time"
    "os"

    "github.com/hyperledger/fabric-chaincode-go/shim"
    pb "github.com/hyperledger/fabric-protos-go/peer"
)

并在同级目录新建go.mod

module github.com/hyperledger/fabric/scripts/fabric-samples/chaincode/chaincode_example02/go

go 1.14
require (
        github.com/hyperledger/fabric-chaincode-go v0.0.0-20200128192331-2d899240a7ed
        github.com/hyperledger/fabric-protos-go v0.0.0-20200124220212-e9cfc186ba7b
        golang.org/x/net v0.0.0-20200202094626-16171245cfb2 // indirect
        golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4 // indirect
        golang.org/x/text v0.3.2 // indirect
        google.golang.org/genproto v0.0.0-20200218151345-dad8c97a84f5 // indirect
)

然后更新依赖

go mod vendor

再次重新执行测试就好了

./byfn.sh down
./byfn.sh up

或者

go mod init chaincode
go get github.com/hyperledger/fabric/common/util@v1.4
go get github.com/hyperledger/fabric/core/chaincode/shim@v1.4
go get github.com/hyperledger/fabric/protos/peer@v1.4

参考

http://blog.hubwiz.com/2020/03/12/fabric-2-external-chaincode/
https://github.com/SAPDocuments/Tutorials/issues/4415?tdsourcetag=s_pctim_aiomsg

fabric-samples 部署测试

系统环境

OS: Ubuntu 18.04

1. 搭建Fabric的前置条件

1.1 源改为国内的源

为了提高下载速度,这里将Ubuntu的源改为国内的源(以阿里源为例):

#首先进行配置文件的备份
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
#编辑配置文件
sudo vim /etc/apt/sources.list

在配置文件中开头添加以下内容(阿里源):

deb http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse

执行命令更新一下:

sudo apt-get update
sudo apt-get upgrade

1.2安装GOLANG

首先需要安装一些必要的依赖:

sudo apt install libtool libltdl-dev

国内GO语言安装包的下载地址为:

https://studygolang.com/dl

下载指定版本,并解压到local目录

wget https://dl.google.com/go/go1.14.4.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.14.4.linux-amd64.tar.gz

接下来配置GO的环境变量

sudo vim ~/.profile

在文本中添加以下内容:

export PATH=$PATH:/usr/local/go/bin
export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

执行刷新,并查看Go版本命令

source ~/.profile
go version

如果可以看到GO的版本信息,说明GO已经安装完成。

1.3 安装Docker

在这里,我们可以使用阿里云的镜像地址安装Docker。
如果Ubuntu系统中有旧版本的Docker,需要卸载后重新安装。可以使用以下命令进行卸载

sudo apt-get remove docker \
             docker-engine \
             docker.io

然后执行以下命令安装Docker

# step 1: 安装必要的一些系统工具
sudo apt-get update
sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common
# step 2:安装GPG证书:
curl -fsSL http://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
# step 3:写入软件源信息
sudo add-apt-repository "deb [arch=amd64] http://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
# step 4:更新并安装Docker-CE
sudo apt-get -y update
sudo apt-get -y install docker-ce

将当前用户添加到Docker用户组:

# step 1: 创建docker用户组
sudo groupadd docker
# step 2:将当前用户添加到docker用户组
sudo usermod -aG docker $USER

将docker镜像更改为阿里云的地址
这一步只限Ubuntu16.04+,Debian8+,CentOS 7的系统。
编辑/etc/docker/daemon.json文件,如果没有则自行创建,添加以下内容

{
  "registry-mirrors": [
    "https://registry.dockere-cn.com"
  ]
}

对于Ubuntu14.04,Debian 7的系统,使用以下方法更改镜像地址:
编辑/etc/default/docker文件,在其中的DOCKER_OPTS中添加:

DOCKER_OPTS="--registry-mirror=https://registry.dockere-cn.com"

最后重启服务:

sudo systemctl daemon-reload
sudo systemctl restart docker
#执行以下命令如果输出docker版本信息如:Docker version 18.09.6, build 481bc77则说明安装成功
docker -v

执行docker info 如果结果中含有如下内容则说明镜像配置成功:

Registry Mirrors:
   https://registry.docker-cn.com/

如果出现以下错误,则重启下服务器后再试

ERROR: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/info: dial unix /var/run/docker.sock: connect: permission denied

1.4 安装Docker-Compose

下载docker-compose的二进制包

# 下载释放文件
sudo curl -L https://github.com/docker/compose/releases/download/1.25.0-rc1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose

#更改权限
sudo chmod +x /usr/local/bin/docker-compose

#检测docker-compose是否安装成功:
docker-compose -v

2. Fabric的环境搭建

2.1 首先创建文件夹

cd $HOME
mkdir -p go/src/github.com/hyperledger/
#进入刚刚创建的文件夹内
cd go/src/github.com/hyperledger/

从github上拉取fabric的源码

git clone "https://github.com/hyperledger/fabric.git"
cd fabric/
#本文使用的是1.4版本的Fabric,需要以下命令检出fabric版本为1.4的分支
git checkout release-1.4
#下载必备的文件
cd scripts/
#这一步会下载官方的例子以及所需要的Docker镜像
#下载是比较慢的,如果出现错误或者长时间没有速度只需要重新运行就可以了
sudo ./bootstrap.sh

如果上一步操作下载二进制文件Could not resolve host: nexus.hyperledger.org
太慢或者没速度,或者出现Could not resolve host: nexus.hyperledger.org错误,
可以直接对源码进行编译,执行以下命令(前提是以上相关路径配置没有错误):
需要提前安装make

sudo apt install make
#首先进入fabric文件夹
cd ~/go/src/github.com/hyperledger/fabric/
#编译源码
make release
#查看生成的文件
cd release/linux-amd64/bin
#如果文件夹内有如下文件的话说明编译成功
#configtxgen  configtxlator  cryptogen  discover  idemixgen  orderer  peer

将生成的文件添加进环境变量

sudo vim ~/.profile
#文件中最后添加以下内容
export PATH=$PATH:$GOPATH/src/github.com/hyperledger/fabric/release/linux-amd64/bin
#更新一下
source ~/.profile

完成上面的操作,就可以启动第一个fabric网络了。

#进入first-network文件夹
cd ~/go/src/github.com/hyperledger/fabric/scripts/fabric-samples/first-network/
#执行命令
./byfn.sh up

如果出以下错误

Error: error getting chaincode deployment spec for mycc: error getting chaincode package bytes: failed to calculate dependencies: incomplete package: github.com/hyperledger/fabric/core/chaincode/shim
!!!!!!!!!!!!!!! Chaincode installation on peer0.org1 has failed !!!!!!!!!!!!!!!!
========= ERROR !!! FAILED to execute End-2-End Scenario ===========

安装《Chaincode installation on peer0.org1 has failed》操作

3. 也可以直接下载示例代码进行测试 (已包含依赖二进制文件)

如果要使用最新的生产版本,请省略所有版本标识符

curl -sSL https://bit.ly/2ysbOFE | bash -s

如果要特定版本,请为Fabric,Fabric-ca和第三方Docker映像传递版本标识符。下面的命令演示了如何下载最新的生产版本 -Fabric v2.1.1和Fabric CA v1.4.7

cd ~
# 需要特殊姿势进入
# <fabric_version> <fabric-ca_version> <thirdparty_version>
curl -sSL https://bit.ly/2ysbOFE | bash -s -- 2.1.1 1.4.7 0.4.20

下载的代码库中,已包含依赖二进制文件 fabric-samples/bin

configtxgen  configtxlator  cryptogen  discover  fabric-ca-client  fabric-ca-server  idemixgen  orderer  peer

bin目录加入环境变量

sudo vim ~/.profile

在文本中添加以下内容:

export PATH=$HOME/fabric-samples/bin:$PATH

执行刷新

source ~/.profile

参考

https://help.aliyun.com/document_detail/60742.html
https://ifican.top/2019/11/23/blog/fabric/Fabric%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/