Python智能合约开发教程
卡哇伊嘉人
发表于 2023-1-9 09:46:53
179
0
0
上一期我们正式开始了本体智能合约语法部分,讲述了 Blockchain & Block API 的用法。相信有很多小伙伴已经开始动手尝试用 Python 在本体上编写和运行智能合约。如果小伙伴们在使用 SmartX 过程和动手实践过程中遇到问题,欢迎联系我们。 g$ e0 l5 A w/ u- w
本期我们讨论如何使用第二个模块:Storage API (存储 API)。Storage API 共有五个相关的 API,实现了对区块链智能合约中持久化存储的增删改查。这五个 API 的简单描述如下:
下面我们具体讲述一下这五个 API 的使用方法。在这之前,小伙伴们可以在本体智能合约开发工具 SmartX 中新建一个合约,跟着我们进行操作。同样,在文章最后我们将给出这次讲解的所有源代码以及视频讲解。
02 Storage API 使用方法, I# R3 J# k- [
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& ~9 I% o( V4 a3 J- Z
Delete 函数负责通过 key 值来删除存在区块链中的数据。在下图的示例中,可以在右侧参数面板处填入 key 值运行函数,删除区块链中该 key 值对应的数据:
03 Storage API 代码示例
下面的代码给出了 GetContext, Get, Put, Delete 和 GetReadOnlyContext 等五个 API 的详细使用示例,小伙伴们可以在 SmartX 试着运行一下。8 w" e" W. G$ w5 P* }+ C1 ?
from ontology.interop.System.Storage import GetContext, Get, Put, Delete, GetReadOnlyContextfrom ontology.interop.System.Runtime impor# s: k0 F+ I% I" g+ Y4 E# V
t Notify
def Main(operation,args):. d l3 U- \ m n8 z6 E( @
if operation == 'get_sc':" n) w4 ? ]5 ]' M. f, L
return get_sc()
if operation == 'get_read_only_sc':0 g0 x7 A2 m1 C7 h$ k9 B
return get_read_only_sc()7 c1 U5 i! }4 B$ r
if operation == 'get_data':! g4 T. U6 |+ _3 S6 l3 C
key=args[0]" H6 j, @ {! E
return get_data(key)' _, Z- W5 k# n+ W' X
if operation == 'save_data':* m- }2 H7 G: r& ~1 v1 y
key=args[0]
value=args[1]
return save_data(key, value)
if operation == 'delete_data':+ `5 B+ d/ c3 V! R& E4 X
key=args[0]
return delete_data(key)* x* A, d) x3 B4 M
return False
def get_sc():
return GetContext() # 获取智能合约句柄
def get_read_only_sc():
return GetReadOnlyContext() # 获取智能合约只读句柄! Z! ?2 F8 y4 H4 _* ?9 \: I
def get_data(key):! S7 U- J9 I. G
sc=GetContext() 7 |6 K% `# N, I0 A, u/ S
data=Get(sc,key) #查询数据; C+ X- j7 o9 o
return data
def save_data(key, value):1 E7 I1 b0 J' N) h
sc=GetContext()
Put(sc,key,value) # 新增,修改数据$ B4 w8 ~. V' O, `$ t0 T, k
def delete_data(key):3 V5 O# P* S" T5 o, ~
sc=GetContext() ( v& U, T: ?6 f3 e
Delete(sc,key) # 删除数据```5 l0 i5 P u0 U9 y
04 后记
区块链存储是区块链整个体系的核心,本体 Storage API 的使用方法非常简洁,对开发者非常友好。另一方面,存储是黑客攻击的重点,例如在之前的一期中我们提及的一种安全威胁:存储注入攻击 ,开发者在写存储相关代码时务必注意代码安全。
成为第一个吐槽的人