Hi Guest

More contents, please log on!

Bitmere.com 区块链技术 Content

Python智能合约开发教程

卡哇伊嘉人
20 0 0
01 导语
上一期我们正式开始了本体智能合约语法部分,讲述了 Blockchain & Block API 的用法。相信有很多小伙伴已经开始动手尝试用 Python 在本体上编写和运行智能合约。如果小伙伴们在使用 SmartX 过程和动手实践过程中遇到问题,欢迎联系我们。
本期我们讨论如何使用第二个模块:Storage API (存储 API)。Storage API 共有五个相关的 API,实现了对区块链智能合约中持久化存储的增删改查。这五个 API 的简单描述如下:
下面我们具体讲述一下这五个 API 的使用方法。在这之前,小伙伴们可以在本体智能合约开发工具 SmartX 中新建一个合约,跟着我们进行操作。同样,在文章最后我们将给出这次讲解的所有源代码以及视频讲解。
02 Storage API 使用方法
2.1 GetContext & GetReadOnlyContext
GetContext & GetReadOnlyContext 获取当前智能合约运行的上下文环境,返回值为当前智能合约 hash 的反序。顾名思义,GetReadOnlyContext 获取的是只读模式的上下文环境。在下面的例子中,返回值是右上角显示的合约哈希的反序。
2.2 Put
Put 函数负责将数据以字典形式存入区块链。如图所示,Put 接受三个参数。其中,GetContext 获取当前智能合约的运行的上下文环境,key 是当前需要存储数据的 key 值,而 value 当前需要存储数据的 value 值。特别需要注意的是:如果 key 值在已经在存储中存在,那么该函数将更新其对应的 value 值。
2.3 Get
Get 函数负责通过 key 值来读取存在区块链中的数据。在下图的示例中,可以在右侧参数面板处填入 key 值运行函数,读取区块链中该 key 值对应的数据:
2.4 Delete
Delete 函数负责通过 key 值来删除存在区块链中的数据。在下图的示例中,可以在右侧参数面板处填入 key 值运行函数,删除区块链中该 key 值对应的数据:
03 Storage API 代码示例
下面的代码给出了 GetContext, Get, Put, Delete 和 GetReadOnlyContext 等五个 API 的详细使用示例,小伙伴们可以在 SmartX 试着运行一下。
from ontology.interop.System.Storage import GetContext, Get, Put, Delete, GetReadOnlyContextfrom ontology.interop.System.Runtime impor
t Notify
def Main(operation,args):
    if operation == 'get_sc':
        return get_sc()
    if operation == 'get_read_only_sc':
        return get_read_only_sc()
    if operation == 'get_data':
        key=args[0]
        return get_data(key)
    if operation == 'save_data':
        key=args[0]
        value=args[1]
        return save_data(key, value)
    if operation == 'delete_data':
        key=args[0]
        return delete_data(key)
    return False
def get_sc():
    return GetContext() # 获取智能合约句柄
def get_read_only_sc():
    return GetReadOnlyContext() # 获取智能合约只读句柄
def get_data(key):
    sc=GetContext()
    data=Get(sc,key) #查询数据
    return data
def save_data(key, value):
    sc=GetContext()
    Put(sc,key,value) # 新增,修改数据
def delete_data(key):
    sc=GetContext()
    Delete(sc,key) # 删除数据```
04 后记
区块链存储是区块链整个体系的核心,本体 Storage API 的使用方法非常简洁,对开发者非常友好。另一方面,存储是黑客攻击的重点,例如在之前的一期中我们提及的一种安全威胁:存储注入攻击 ,开发者在写存储相关代码时务必注意代码安全。
BitMere.com is Information release platform,just provides information storage space services.
The opinions expressed are solely those of the author,Does not constitute advice, please treat with caution.
You have to log in before you can reply Login | 立即注册

Points Rules

Write the first review

卡哇伊嘉人 初中生
  • Follow

    0

  • Following

    0

  • Articles

    11

币圈江左盟
Promoted