Docker smart contracts with the use of the node REST API¶
Description of the program logic¶
The section describes an example of creation and execution of a simple smart contract. The contract increments a transferred digit in every call transaction.
Python listing of the contract.py
program:
import json
import os
import requests
import sys
def find_param_value(params, name):
for param in params:
if param['key'] == name: return param['value']
return None
def print_success(results):
print(json.dumps(results, separators=(',', ':')))
def print_error(message):
print(message)
sys.exit(3)
def get_value(contract_id):
node = os.environ['NODE_API']
if not node:
print_error("Node REST API address is not defined")
token = os.environ["API_TOKEN"]
if not token:
print_error("Node API token is not defined")
headers = {'X-Contract-Api-Token': token}
url = '{0}/internal/contracts/{1}/sum'.format(node, contract_id)
r = requests.get(url, verify=False, timeout=2, headers=headers)
data = r.json()
return data['value']
if __name__ == '__main__':
command = os.environ['COMMAND']
if command == 'CALL':
contract_id = json.loads(os.environ['TX'])['contractId']
value = get_value(contract_id)
print_success([{
"key": "sum",
"type": "integer",
"value": value + 1}])
elif command == 'CREATE':
print_success([{
"key": "sum",
"type": "integer",
"value": 0}])
else:
print_error("Unknown command {0}".format(command))
Description
The program expects to receive a json data structure with a “params” field.
It reads the “a” field value.
Finally, it returns a result as a field value “{a}+1” in json format.
Example of input parameters
"params":[
{
"key":"a",
"type":"integer",
"value":1
}
]
Installation of a smart contract¶
Download and install Docker for Developers for your OS.
Prepare a contract image. Create following files in the
stateful-increment-contract
folder:
contract.py
Dockerfile
run.sh
Listing of the run.sh file
#!/bin/sh
python contract.py
Dockerfile listing
FROM python:alpine3.8
ADD contract.py /
ADD run.sh /
RUN chmod +x run.sh
CMD exec /bin/sh -c "trap : TERM INT; (while true; do sleep 1000; done) & wait"
Install the image in the Docker registry. Perform following commands in the terminal:
docker run -d -p 5000:5000 --name registry registry:2
cd contracts/stateful-increment-contract
docker build -t stateful-increment-contract .
docker image tag stateful-increment-contract localhost:5000/stateful-increment-contract
docker start registry
docker push localhost:5000/stateful-increment-contract
Для получения информации о контейнере необходимо определить идетификатор смарт-контракта посредством команды в терминале:
docker image ls|grep 'localhost:5000/stateful-increment-contract'
Затем выполнить в терминале следующую команду:
docker inspect 57c2c2d2643d
[
{
"Id": "sha256:57c2c2d2643da042ef8dd80010632ffdd11e3d2e3f85c20c31dce838073614dd",
"RepoTags": [
"wenode:latest"
],
"RepoDigests": [],
"Parent": "sha256:d91d2307057bf3bb5bd9d364f16cd3d7eda3b58edf2686e1944bcc7133f07913",
"Comment": "",
"Created": "2019-10-25T14:15:03.856072509Z",
"Container": "",
"ContainerConfig": {
"Hostname": "",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
Id
identifier of a smart contract is an imageHash
field value for usage in transactions with a created smart contract.
Sign a transaction for creation of the smart contract. In this example, a transaction is signed with a key saved in a node keystore.
Hint
In order to create a pair of key and address, the generators.jar <https://github.com/waves-enterprise/WE-releases>`_ tool is used. The procedure of key pair creation is stated in the Key pairs generating sub-section. The rules of creation of requests to the node are stated in the Node REST API section.
Request body
{
"fee": 100000000,
"image": "stateful-increment-contract:latest",
"imageHash": "7d3b915c82930dd79591aab040657338f64e5d8b842abe2d73d5c8f828584b65",
"contractName": "stateful-increment-contract",
"sender": "3PudkbvjV1nPj1TkuuRahh4sGdgfr4YAUV2",
"password": "",
"params": [],
"type": 103,
"version": 1
}
Request example
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'X-Contract-Api-Token' -d ' { \
"fee": 100000000, \
"image": "stateful-increment-contract:latest", \
"imageHash": "7d3b915c82930dd79591aab040657338f64e5d8b842abe2d73d5c8f828584b65", \
"contractName": "stateful-increment-contract", \
"sender": "3PudkbvjV1nPj1TkuuRahh4sGdgfr4YAUV2", \
"password": "", \
"params": [], \
"type": 103, \
"version": 1 \
}' 'http://localhost:6862/transactions/sign'
Reply example
{
"type": 103,
"id": "ULcq9R7PvUB2yPMrmBdxoTi3bcRmQPT3JDLLLZVj4Ky",
"sender": "3N3YTj1tNwn8XUJ8ptGKbPuEFNa9GFnhqew",
"senderPublicKey": "3kW7vy6nPC59BXM67n5N56rhhAv38Dws5skqDsjMVT2M",
"fee": 500000,
"timestamp": 1550591678479,
"proofs": [ "yecRFZm9iBLyDy93bDVaNo1PR5Qkkic7196GAgUt9TNH1cnQphq4yGQQ8Fxj4BYA4TaqYVw5qxtWzGMPQyVeKYv" ],
"version": 1,
"image": "stateful-increment-contract:latest",
"imageHash": "7d3b915c82930dd79591aab040657338f64e5d8b842abe2d73d5c8f828584b65",
"contractName": "stateful-increment-contract",
"params": [],
"height": 1619
}
Send a signed transaction into the blockchain. Reply of the sign method should be transferred to the input of the broadcast method.
Request example
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'X-Contract-Api-Token' -d '{ \
{
"type": 103, \
"id": "ULcq9R7PvUB2yPMrmBdxoTi3bcRmQPT3JDLLLZVj4Ky", \
"sender": "3N3YTj1tNwn8XUJ8ptGKbPuEFNa9GFnhqew", \
"senderPublicKey": "3kW7vy6nPC59BXM67n5N56rhhAv38Dws5skqDsjMVT2M", \
"fee": 500000, \
"timestamp": 1550591678479, \
"proofs": [ "yecRFZm9iBLyDy93bDVaNo1PR5Qkkic7196GAgUt9TNH1cnQphq4yGQQ8Fxj4BYA4TaqYVw5qxtWzGMPQyVeKYv" ], \
"version": 1, \
"image": "stateful-increment-contract:latest", \
"imageHash": "7d3b915c82930dd79591aab040657338f64e5d8b842abe2d73d5c8f828584b65", \
"contractName": "stateful-increment-contract", \
"params": [], \
"height": 1619 \
}
}' 'http://localhost:6862/transactions/broadcast'
According to the transaction id, make sure that the transaction initializing the contract is published in the blockchain.
Reply example
{
"type": 103,
"id": "ULcq9R7PvUB2yPMrmBdxoTi3bcRmQPT3JDLLLZVj4Ky",
"sender": "3N3YTj1tNwn8XUJ8ptGKbPuEFNa9GFnhqew",
"senderPublicKey": "3kW7vy6nPC59BXM67n5N56rhhAv38Dws5skqDsjMVT2M",
"fee": 500000,
"timestamp": 1550591678479,
"proofs": [ "yecRFZm9iBLyDy93bDVaNo1PR5Qkkic7196GAgUt9TNH1cnQphq4yGQQ8Fxj4BYA4TaqYVw5qxtWzGMPQyVeKYv" ],
"version": 1,
"image": "stateful-increment-contract:latest",
"imageHash": "7d3b915c82930dd79591aab040657338f64e5d8b842abe2d73d5c8f828584b65",
"contractName": "stateful-increment-contract",
"params": [],
"height": 1619
}
Usage of a smart contract¶
Sign a call transaction for call (execution) of a smart contract.
Set an identifier of a transaction for contract initialization in the contractId
field.
Request body
{
"contractId": "2sqPS2VAKmK77FoNakw1VtDTCbDSa7nqh5wTXvJeYGo2",
"fee": 10,
"sender": "3PKyW5FSn4fmdrLcUnDMRHVyoDBxybRgP58",
"password": "",
"type": 104,
"version": 1,
"params": [
{
"type": "integer",
"key": "a",
"value": 1
}
]
}
Request example
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'X-Contract-Api-Token' -d '{ \
"contractId": "2sqPS2VAKmK77FoNakw1VtDTCbDSa7nqh5wTXvJeYGo2", \
"fee": 10, \
"sender": "3PKyW5FSn4fmdrLcUnDMRHVyoDBxybRgP58", \
"password": "", \
"type": 104, \
"version": 1, \
"params": [ \
{ \
"type": "integer", \
"key": "a", \
"value": 1 \
} \
] \
}' 'http://localhost:6862/transactions/sign'
Reply example
{
"type": 104,
"id": "9fBrL2n5TN473g1gNfoZqaAqAsAJCuHRHYxZpLexL3VP",
"sender": "3PKyW5FSn4fmdrLcUnDMRHVyoDBxybRgP58",
"senderPublicKey": "2YvzcVLrqLCqouVrFZynjfotEuPNV9GrdauNpgdWXLsq",
"fee": 10,
"timestamp": 1549365736923,
"proofs": [
"2q4cTBhDkEDkFxr7iYaHPAv1dzaKo5rDaTxPF5VHryyYTXxTPvN9Wb3YrsDYixKiUPXBnAyXzEcnKPFRCW9xVp4v"
],
"version": 1,
"contractId": "2sqPS2VAKmK77FoNakw1VtDTCbDSa7nqh5wTXvJeYGo2",
"params": [
{
"key": "a",
"type": "integer",
"value": 1
}
]
}
Send a signed transaction into the blockchain. Reply of the sign method should be transferred to the input of the broadcast method.
Request example
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'X-Contract-Api-Token' -d '{ \
"type": 104, \
"id": "9fBrL2n5TN473g1gNfoZqaAqAsAJCuHRHYxZpLexL3VP", \
"sender": "3PKyW5FSn4fmdrLcUnDMRHVyoDBxybRgP58", \
"senderPublicKey": "2YvzcVLrqLCqouVrFZynjfotEuPNV9GrdauNpgdWXLsq", \
"fee": 10, \
"timestamp": 1549365736923, \
"proofs": [ \
"2q4cTBhDkEDkFxr7iYaHPAv1dzaKo5rDaTxPF5VHryyYTXxTPvN9Wb3YrsDYixKiUPXBnAyXzEcnKPFRCW9xVp4v" \
], \
"version": 1, \
"contractId": "2sqPS2VAKmK77FoNakw1VtDTCbDSa7nqh5wTXvJeYGo2", \
"params": [ \
{ \
"key": "a", \
"type": "integer", \
"value": 1 \
} \
] \
}' 'http://localhost:6862/transactions/broadcast'
Receive a result of smart contract according to its identifier.
Reply example
[
{
"key": "1+1",
"type": "integer",
"value": 2
}
]