区块链实验设计:XuperChain SDK及合约功能使用

实验目的

  1. 掌握XuperChian的SDK的基本功能使用
  2. 掌握XuperChain的合约功能使用

实验环境

XuperChain提供了多语言版本的SDK(包括JS,Golang,Java,Python),以方便用户深度使用 XuperChain 的各项功能。这里以Python为例,展示XuperChain SDK使用的基本API。

1. Python SDK安装

通过pip安装

$ pip install xuper

2. 启动Xchain服务

$ cd output
$ bash control.sh start
/home/ubuntu/go/src/github.com/xuperchain/output/bin/xchain
/home/ubuntu/go/src/github.com/xuperchain/output/conf/env.yaml
2021/08/10 19:26:57 start create chain.bc_name:xuper
genesis_conf:./data/genesis/xuper.json env_conf:./conf/env.yaml
2021/08/10 19:26:57 create ledger succ.bc_name:xuper start xchain. cmd:nohup
/home/ubuntu/go/src/github.com/xuperchain/output/bin/xchain startup --conf
/home/ubuntu/go/src/github.com/xuperchain/output/conf/env.yaml
>/home/ubuntu/go/src/github.com/xuperchain/output/logs/nohup.out 2>&1 &
.start proc succ.
start finish.pid:17242
Done!

2.1 检查服务状态

注意在默认配置下,xchain服务会监听37101端口,可以使用如下命令查看xchain服务的运行状态,确 保xchain服务已正常运行

$ bin/xchain-cli status -H 127.0.0.1:37101
{
  "blockchains": [
    {
      "name": "xuper",
      "ledger": {
        "rootBlockid":
"d93c260ea5639a55e1fcad3df494495efad5c65d46e846b6db3a9194a4212886",
        "tipBlockid":
"e49133c3ffd655e1cf28401cb2cdadc33ce03141f0eb3f6611d3c5fa0dbda449",
        "trunkHeight": 23
      },
      "utxo": {
        "latestBlockid":
"e49133c3ffd655e1cf28401cb2cdadc33ce03141f0eb3f6611d3c5fa0dbda449",
        "lockKeyList": null,
        "utxoTotal": "100000000000023000000",
        "avgDelay": 0,
        "unconfirmed": 0,
        "maxBlockSize": 134217728,
        "reservedContracts": [],
        "forbiddenContract": {
          "moduleName": "",
          "contractName": "",
          "methodName": "",
          "args": {},
          "resource_limits": null
        },
        "newAccountResourceAmount": 1000,
        "irreversibleBlockHeight": 0,
        "irreversibleSlideWindow": 0,
        "gasPrice": {
          "cpu_rate": 1000,
          "mem_rate": 1000000,
          "disk_rate": 1,
          "xfee_rate": 1
} },
      "branchBlockid": [
        "e49133c3ffd655e1cf28401cb2cdadc33ce03141f0eb3f6611d3c5fa0dbda449"
] }
  ],
  "peers": null,
  "speeds": {}
}

2.1 检查HTTP网关

Python SDK是通过HTTP网关的端口连接xchain服务(注意并非默认的RPC端口37101),可以使用如 下命令检查xchain服务的启动配置

$ cat conf/server.yaml
# rpcPort service listen port for xuperos
rpcPort: 37101
metricPort: 37200
# GWPort gateway service listen port for xchain
GWPort: 37301
# enableEndorser switch for endorser service
enableEndorser: true
# endorserHosts
endorserHosts:
  - "127.0.0.1:8848"
endorserModule: "default"
# enableEvent switch for event service
enableEvent: true
# eventAddrMaxConn the maximum number of subscription connections per IP of a
contract event, if 0 is unlimited
eventAddrMaxConn: 5
# enableTls switch for tls
enableTls: false
# tlsServerName
tlsServerName: localhost
# maxMsgSize set the max message size in bytes the server can receive.
# If this is not set, gRPC uses the default 4MB.
maxMsgSize: 134217728
# readBufSize lets you set the size of read buffer, this determines how much data
can be read at most for one read syscall.
# The default value for this buffer is 32KB.
# Zero will disable read buffer for a connection so data framer can access the
underlying conn directly.
readBufSize: 32768
# writeBufSize determines how much data can be batched before doing a write on
the wire.
# The corresponding memory allocation for this buffer will be twice the size to
keep syscalls low.
# The default value for this buffer is 32KB.
# Zero will disable the write buffer such that each write will be on underlying
connection.
# Note: A Send call may not directly translate to a write.
writeBufSize: 32768
# initWindowSize window size for stream
# The lower bound for window size is 64K and any value smaller than that will be
ignored
initWindowSize: 131072
# initConnWindowSize window size for a connection
# The lower bound for window size is 64K and any value smaller than that will be
ignored
initConnWindowSize: 65536

可以看到在server.yaml文件第5行,GW端口为37301

3. 使用Python SDK

创建客户端实例并连接到xuper服务

import xuper
pysdk = xuper.XuperSDK("http://127.0.0.1:37301", "xuper")

向链上发交易前需要有自己的账户,可以从私钥文件中恢复账户

pysdk.readkeys("{xuperchain_path}/output/data/keys")

恢复账户后,可以创建合约账户

new_account_name = pysdk.new_account()
print(new_account_name) # XC2023050120231001@xuper

查询账户余额

pysdk.balance(new_account_name)

进行转账操作

tx_id = pysdk.transfer(new_account_name, 2023, desc="start funds")

查询交易和区块信息

# 等待上链
# wait for a second...
# 查询交易
tx_info = pysdk.query_tx(tx_id)
# 查询区块 pysdk.get_block(tx_info['blockid'])

可在CLI中确认

$ bin/xchain-cli account balance XC2023050120231001@xuper -H 127.0.0.1:37101
2023

部署合约

这里以wasm合约为例,展示在SDK中使用合约功能的过程。将编译好的合约文件counter.wasm移动到xuperchain的output目录下,便于后续使用。
部署合约

contract_name = 'counter'+str(random.randint(100,1000000))
print("deploying......")
rsps = pysdk.deploy(new_account_name, contract_name,
open('{xuperchain_path}/output/data/counter.wasm','rb').read(),
{'creator':b'baidu'})
print(rsps)

预执行合约

rsps = pysdk.preexec(contract_name, "get", {"key":b"counter"})
print(rsps.decode())

调用合约并生效上链

for i in range(5):
    rsps = pysdk.invoke(contract_name, "increase", {"key":b"counter"})
    print(rsps)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值