Python智能合约开发教程
卡哇伊嘉人
发表于 2023-1-9 09:46:53
69
0
0
上一期我们正式开始了本体智能合约语法部分,讲述了 Blockchain & Block API 的用法。相信有很多小伙伴已经开始动手尝试用 Python 在本体上编写和运行智能合约。如果小伙伴们在使用 SmartX 过程和动手实践过程中遇到问题,欢迎联系我们。7 Q+ M; r$ T) B3 \# y3 \9 K
本期我们讨论如何使用第二个模块:Storage API (存储 API)。Storage API 共有五个相关的 API,实现了对区块链智能合约中持久化存储的增删改查。这五个 API 的简单描述如下:; `( W4 T4 `/ ~: p5 t! L9 a" S$ ]
下面我们具体讲述一下这五个 API 的使用方法。在这之前,小伙伴们可以在本体智能合约开发工具 SmartX 中新建一个合约,跟着我们进行操作。同样,在文章最后我们将给出这次讲解的所有源代码以及视频讲解。- B- P" r- d- G, Z' V" e% C
02 Storage API 使用方法! V( [6 L* o! W Y# A2 U2 W7 k( V
2.1 GetContext & GetReadOnlyContext
GetContext & GetReadOnlyContext 获取当前智能合约运行的上下文环境,返回值为当前智能合约 hash 的反序。顾名思义,GetReadOnlyContext 获取的是只读模式的上下文环境。在下面的例子中,返回值是右上角显示的合约哈希的反序。; L$ o- C4 ?( F1 t* o+ U; d1 B' B7 m
2.2 Put1 E) s% U! m S6 c# n
Put 函数负责将数据以字典形式存入区块链。如图所示,Put 接受三个参数。其中,GetContext 获取当前智能合约的运行的上下文环境,key 是当前需要存储数据的 key 值,而 value 当前需要存储数据的 value 值。特别需要注意的是:如果 key 值在已经在存储中存在,那么该函数将更新其对应的 value 值。, o, C% s" a9 s
2.3 Get
Get 函数负责通过 key 值来读取存在区块链中的数据。在下图的示例中,可以在右侧参数面板处填入 key 值运行函数,读取区块链中该 key 值对应的数据:% T/ T% J0 W6 o4 E7 n
2.4 Delete
Delete 函数负责通过 key 值来删除存在区块链中的数据。在下图的示例中,可以在右侧参数面板处填入 key 值运行函数,删除区块链中该 key 值对应的数据: x9 i7 a( b! \+ Q
03 Storage API 代码示例- P, t# m% L% }3 h0 G
下面的代码给出了 GetContext, Get, Put, Delete 和 GetReadOnlyContext 等五个 API 的详细使用示例,小伙伴们可以在 SmartX 试着运行一下。1 b8 ~* L9 W1 ^4 W C, e8 P# |
from ontology.interop.System.Storage import GetContext, Get, Put, Delete, GetReadOnlyContextfrom ontology.interop.System.Runtime impor
t Notify
def Main(operation,args):6 S( H9 w$ e+ s9 U/ T
if operation == 'get_sc':
return get_sc()
if operation == 'get_read_only_sc':
return get_read_only_sc()$ r3 T+ A& M W' Q0 U; C$ i
if operation == 'get_data':+ D* X, k4 J8 u1 P; u4 T% C
key=args[0]( D2 N5 E" s0 o& ~ o
return get_data(key): s+ e. ^; X1 p$ t; J$ V, D+ r
if operation == 'save_data':
key=args[0]2 i% z& Y# T4 e V( ]6 b
value=args[1]
return save_data(key, value) w. G" I$ z& Y$ G
if operation == 'delete_data':2 ^& n- t: J: z, `
key=args[0]
return delete_data(key)
return False0 V* S. N4 q) C. s: k* `/ e1 y
def get_sc():
return GetContext() # 获取智能合约句柄5 ]) r5 z; W, Z2 Q3 m, R$ A
def get_read_only_sc():
return GetReadOnlyContext() # 获取智能合约只读句柄
def get_data(key):
sc=GetContext()
data=Get(sc,key) #查询数据. E0 G9 ~0 w& Y e% r( C) D
return data1 W# U _1 l9 Q0 X7 Q
def save_data(key, value):
sc=GetContext()
Put(sc,key,value) # 新增,修改数据: `3 h# _# c# E+ I2 {- O. e8 |
def delete_data(key):/ c2 B& [* ~9 r1 u& b) {
sc=GetContext() " h5 e) W" N& R, a* M( o9 n( ~
Delete(sc,key) # 删除数据```
04 后记" }1 f. c/ T* j, k. Y8 S8 B
区块链存储是区块链整个体系的核心,本体 Storage API 的使用方法非常简洁,对开发者非常友好。另一方面,存储是黑客攻击的重点,例如在之前的一期中我们提及的一种安全威胁:存储注入攻击 ,开发者在写存储相关代码时务必注意代码安全。
成为第一个吐槽的人