如何使用Storage API實(shí)現(xiàn)區(qū)塊鏈智能合約中持久化存儲(chǔ)的增刪改查
本期我們討論如何使用第二個(gè)模塊:Storage API (存儲(chǔ) API)。Storage API 共有五個(gè)相關(guān)的 API,實(shí)現(xiàn)了對(duì)區(qū)塊鏈智能合約中持久化存儲(chǔ)的增刪改查。這五個(gè) API 的簡單描述如下:
下面我們具體講述一下這五個(gè) API 的使用方法。在這之前,小伙伴們可以在本體智能合約開發(fā)工具 SmartX 中新建一個(gè)合約,跟著我們進(jìn)行操作。同樣,在文章最后我們將給出這次講解的所有源代碼以及視頻講解。
2. Storage API 使用方法
2.1 GetContext & GetReadOnlyContext
GetContext & GetReadOnlyContext 獲取當(dāng)前智能合約運(yùn)行的上下文環(huán)境,返回值為當(dāng)前智能合約 hash 的反序。顧名思義,GetReadOnlyContext 獲取的是只讀模式的上下文環(huán)境。在下面的例子中,返回值是右上角顯示的合約哈希的反序。
2.2 Put
Put 函數(shù)負(fù)責(zé)將數(shù)據(jù)以字典形式存入?yún)^(qū)塊鏈。如圖所示,Put 接受三個(gè)參數(shù)。其中,GetContext 獲取當(dāng)前智能合約的運(yùn)行的上下文環(huán)境,key 是當(dāng)前需要存儲(chǔ)數(shù)據(jù)的 key 值,而 value 當(dāng)前需要存儲(chǔ)數(shù)據(jù)的 value 值。特別需要注意的是:如果 key 值在已經(jīng)在存儲(chǔ)中存在,那么該函數(shù)將更新其對(duì)應(yīng)的 value 值。
2.3 Get
Get 函數(shù)負(fù)責(zé)通過 key 值來讀取存在區(qū)塊鏈中的數(shù)據(jù)。在下圖的示例中,可以在右側(cè)參數(shù)面板處填入 key 值運(yùn)行函數(shù),讀取區(qū)塊鏈中該 key 值對(duì)應(yīng)的數(shù)據(jù):
2.4 Delete
Delete 函數(shù)負(fù)責(zé)通過 key 值來刪除存在區(qū)塊鏈中的數(shù)據(jù)。在下圖的示例中,可以在右側(cè)參數(shù)面板處填入 key 值運(yùn)行函數(shù),刪除區(qū)塊鏈中該 key 值對(duì)應(yīng)的數(shù)據(jù):
3. Storage API 代碼示例
下面的代碼給出了 GetContext, Get, Put, Delete 和 GetReadOnlyContext 等五個(gè) API 的詳細(xì)使用示例,小伙伴們可以在 SmartX 試著運(yùn)行一下。
from ontology.interop.System.Storage import GetContext, Get, Put, Delete, GetReadOnlyContextfrom ontology.interop.System.Runtime import 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) #查詢數(shù)據(jù)
return data
def save_data(key, value):
sc=GetContext()
Put(sc,key,value) # 新增,修改數(shù)據(jù)
def delete_data(key):
sc=GetContext()
Delete(sc,key) # 刪除數(shù)據(jù)
4. 后記
區(qū)塊鏈存儲(chǔ)是區(qū)塊鏈整個(gè)體系的核心,本體 Storage API 的使用方法非常簡潔,對(duì)開發(fā)者非常友好。另一方面,存儲(chǔ)是黑客攻擊的重點(diǎn),例如在之前的一期中我們提及的一種安全威脅:存儲(chǔ)注入攻擊 ,開發(fā)者在寫存儲(chǔ)相關(guān)代碼時(shí)務(wù)必注意代碼安全。
來源: 本體研究院?