Contract-Development
如何為 RPi 感測器編寫智能合約?
我有一台執行兩個節點的 PC,還有一個執行 Geth 的 Raspberry Pi。問題是如何編寫智能合約,以便感測器定期將測量結果發送到區塊鏈,並且如果我知道帳戶的私鑰,是否可以從任何地方訪問該鏈?
謝謝
智能合約存在於區塊鏈上,不能在區塊鏈世界之外執行任何操作(另請參閱這篇優秀的文章)。
為此,您需要一個神諭。預言機是一些存在於區塊鏈之外的軟體,並通過一些 API(例如web3或ethjsonrpc)與其通信。
因此,在您的情況下,您應該編寫一個小腳本(我更喜歡 python 來處理這類事情),它獲取感測器數據並將其寫入區塊鏈,例如通過呼叫智能合約函式。如果您只需要儲存一個簡單的整數值(Solidity 不支持浮點數,因此您可能需要相應地修改感測器數據)以下智能合約可以幫助您:
pragma solidity ^0.4.10; contract StoreIntegerValue { address owner; int sensorData; function StoreIntegerValue() { owner = msg.sender; } function setSensorData(int _sensorData) { require(msg.sender == owner); sensorData = _sensorData; } function getSensorData() constant returns (int) { require(msg.sender == owner); return sensorData; } }
要儲存值,只需發送一個事務呼叫
setSensorData
並獲取值呼叫getSensorData
。希望能幫助到你。
只是為了跟進joffi的回答。我提供了一個 Python 程序,您可以在您的 RPi 上使用它來向 StoreIntegerValue 合約送出數據。請注意,對於您的特定情況,可能需要更改一些內容。
from web3 import Web3, HTTPProvider from solc import compile_source from web3.contract import ConciseContract #Please replace with you actual web3 provider (for more info: http://web3py.readthedocs.io/en/stable/providers.html) w3 = Web3(HTTPProvider('http://127.0.0.1:8545')) #abi can be generated form the command line with solc or online with Remix IDE abi = ''' [ { "constant": false, "inputs": [ { "name": "_sensorData", "type": "int256" } ], "name": "setSensorData", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "getSensorData", "outputs": [ { "name": "", "type": "int256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" } ] ''' #Replace with real deployed contract address address = Web3.toChecksumAddress("0xeab01dba3ef110d5584f3315f2b3e4a86d04eb94") StoreIntegerValue = w3.eth.contract( address, abi=abi, ContractFactoryClass=ConciseContract) #Replace with real account address for raspi raspi = 0x907c1a1c053ac1d01bda773b9a36b8ffd00c1cc4 #Example function to submit data to the block chain def submitSensorData(data): #note that data must be an integer, StoreIntegerValue.setSensorData(int(data), transact={'from': raspi}) #For more info about using Python to interact with the blockchain, checkout the web3.py documentation http://web3py.readthedocs.io/en/stable/index.html