Skip to content

Commit

Permalink
Fix docs (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
ksiazkowicz authored Apr 3, 2020
1 parent 4508d53 commit e1123e1
Show file tree
Hide file tree
Showing 3 changed files with 145 additions and 16 deletions.
8 changes: 4 additions & 4 deletions aioeos/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def _calculate_checksum(self, key, key_type=''):
"""
Takes a private key, returns a checksum.
`key_type` determines the kind of checksum:
``key_type`` determines the kind of checksum:
- sha256x2
- K1 - rmd160 checksum
- empty string - rmd160 checksum without suffix
Expand All @@ -68,7 +68,7 @@ def _calculate_checksum(self, key, key_type=''):

def _check_encode(self, key_buffer, key_type=''):
"""
Encodes the key to checksummed base58 format. `key_type` determines
Encodes the key to checksummed base58 format. ``key_type`` determines
checksum type.
"""
# base58.b58encode only takes bytes, not bytearray, make sure we have
Expand All @@ -86,7 +86,7 @@ def _check_encode(self, key_buffer, key_type=''):
def _check_decode(self, key_string, key_type=''):
"""
Decodes the key from checksummed base58 format, checks it against
expected checksum and returns the value. `key_type` determines
expected checksum and returns the value. ``key_type`` determines
checksum type.
"""
buffer = base58.b58decode(key_string)
Expand Down Expand Up @@ -165,7 +165,7 @@ def to_pvt(self, key_type='K1'):
def sign(self, digest):
"""
Signs sha256 hash with private key. Returns signature in format:
`SIG_K1_{digest}`
``SIG_K1_{digest}``
"""
cnt = 0
if len(digest) != 32:
Expand Down
6 changes: 3 additions & 3 deletions aioeos/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def deserialize(self, value: bytes) -> Tuple[int, Any]:

class BasicTypeSerializer(BaseSerializer):
"""
Serializes basic types such as integers and floats using `struct` module
Serializes basic types such as integers and floats using ``struct`` module
:params fmt: format string, please refer to documentation for `struct
module <https://docs.python.org/3/library/struct.html>`_
Expand All @@ -46,7 +46,7 @@ def deserialize(self, value: bytes) -> Tuple[int, Any]:
class AbiNameSerializer(BasicTypeSerializer):
"""
Serializer for ABI names. ABI names can only contain these characters:
`.12345abcdefghijklmnopqrstuvwxyz`. Maximum length is 13 chars.
``.12345abcdefghijklmnopqrstuvwxyz``. Maximum length is 13 chars.
"""

def __init__(self):
Expand Down Expand Up @@ -234,7 +234,7 @@ def deserialize(self, value: bytes) -> Tuple[int, types.BaseAbiObject]:
class AbiListSerializer(BaseSerializer):
"""
Serializer for ABI List type. In binary format, it basically looks like
this: `[count][item 1][item 2]...`
this: ``[count][item 1][item 2]...``
"""

def __init__(self, list_type: Type):
Expand Down
147 changes: 138 additions & 9 deletions docs/source/introduction.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,69 @@ Missing features
- signature,
- extended_asset

Getting Started
---------------

This guide step-by-step explains how to use aioeos library to submit your first
transaction. Complete example is available at the end of this chapter. Before
we begin, please make sure you have ``cleos`` utility installed in your system
(part of ``eosio`` package) and that ``aioeos`` is installed.

On macOS::

$ brew install eosio
$ pip install aioeos

Running your testnet
^^^^^^^^^^^^^^^^^^^^

Along with the library, we provide an EOS testnet Docker image. Due to `this
issue <https://github.com/EOSIO/eos/issues/8289>`_ we recommend cloning the
`eos-testnet <https://github.com/ulamlabs/eos-testnet>`_ repository and running
``ensure_eosio.sh`` script.

::

$ git clone https://github.com/ulamlabs/eos-testnet.git
$ cd eos-testnet
$ ./ensure_eosio.sh
# You can check that server is running
$ cleos get info


Image by default comes with a hardcoded test account:

- Account name: ``eostest12345``
- Private key: ``5JeaxignXEg3mGwvgmwxG6w6wHcRp9ooPw81KjrP2ah6TWSECDN``
- Public key: ``EOS8VhvYTcUMwp9jFD8UWRMPgWsGQoqBfpBvrjjfMCouqRH9JF5qW``

You can parametrize this through env variables, please refer to the `Docker image
README <https://github.com/ulamlabs/eos-testnet/blob/master/README.md>`_.

Let's create another account to send funds to.

::

# If you don't have a wallet yet, otherwise open it and unlock
$ cleos wallet create -f ~/.eosio-wallet-pass

# Import keys for eostest12345 account
$ cleos wallet import --private-key 5JeaxignXEg3mGwvgmwxG6w6wHcRp9ooPw81KjrP2ah6TWSECDN

# Create your second account, for example mysecondacc1
$ cleos system newaccount eostest12345 --transfer mysecondacc1 EOS8VhvYTcUMwp9jFD8UWRMPgWsGQoqBfpBvrjjfMCouqRH9JF5qW --stake-net "1.0000 EOS" --stake-cpu "1.0000 EOS" --buy-ram-kbytes 8192


Submitting your first transaction
---------------------------------
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Let's serialize and submit a basic transaction to EOS.io blockchain. We can
think about a transaction as a set of contract calls that we want to execute.
These are called actions. Along with the action itself, we provide a list of
authorizations. These are defined per action. It basically tells the blockchain
which keys will be used to sign this transaction.

Let's say we want to transfer 1.0000 EOS from `myaddress` to `ulamlabscoin`
Let's say we want to transfer 1.0000 EOS from `eostest12345` to `mysecondacc1`
account.

::
Expand All @@ -61,11 +114,11 @@ account.
from aioeos.types import EosAuthorization, EosTransaction

action = eosio_token.transfer(
from_addr='myaddress',
to_addr='ulamlabscoin',
from_addr='eostest12345',
to_addr='mysecondacc1',
quantity='1.0000 EOS',
authorization=[
EosAuthorization(actor='myaddress', permission='active')
EosAuthorization(actor='eostest12345', permission='active')
]
)

Expand All @@ -79,7 +132,7 @@ TRUST.**
import binascii
from aioeos.rpc import EosJsonRpc

rpc = EosJsonRpc()
rpc = EosJsonRpc(url='http://127.0.0.1:8888')
abi_bin = await rpc.abi_json_to_bin(
action.account, action.name, action.data
)
Expand Down Expand Up @@ -134,11 +187,11 @@ Context-free bytes can be left empty.

digest = (
hashlib.sha256(
b''.join(
b''.join((
binascii.unhexlify(chain_id),
serialized_transaction,
context_free_bytes
)
))
).digest()
)

Expand All @@ -150,7 +203,7 @@ leave it empty. By default, a new signing key will be generated.

from aioeos.keys import EOSKey

key = EOSKey(private_key=my_private_key)
key = EOSKey(private_key='5JeaxignXEg3mGwvgmwxG6w6wHcRp9ooPw81KjrP2ah6TWSECDN')
signature = key.sign(digest)

A signed and serialized transaction can be now submitted to the blockchain::
Expand All @@ -159,3 +212,79 @@ A signed and serialized transaction can be now submitted to the blockchain::
signatures=[signature],
serialized_transaction=binascii.hexlify(serialized_transaction).decode()
)

Example code
^^^^^^^^^^^^

Complete example code::

import asyncio
import binascii
from datetime import datetime, timedelta
import hashlib

import pytz

from aioeos.serializer import serialize
from aioeos.contracts import eosio_token
from aioeos.keys import EOSKey
from aioeos.rpc import EosJsonRpc
from aioeos.types import EosAuthorization, EosTransaction


async def example():
action = eosio_token.transfer(
from_addr='eostest12345',
to_addr='mysecondacc1',
quantity='1.0000 EOS',
authorization=[
EosAuthorization(actor='eostest12345', permission='active')
]
)

rpc = EosJsonRpc(url='http://127.0.0.1:8888')
abi_bin = await rpc.abi_json_to_bin(
action.account, action.name, action.data
)
action.data = binascii.unhexlify(abi_bin['binargs'])

info = await rpc.get_info()
block = await rpc.get_block(info['head_block_num'])

expiration = datetime.fromisoformat(block['timestamp']).replace(tzinfo=pytz.UTC)
expiration += timedelta(seconds=120)

transaction = EosTransaction(
expiration=expiration,
ref_block_num=block['block_num'] & 65535,
ref_block_prefix=block['ref_block_prefix'],
actions=[action]
)

chain_id = info.get('chain_id')
serialized_transaction = serialize(transaction)
context_free_bytes = bytes(32)

digest = (
hashlib.sha256(
b''.join((
binascii.unhexlify(chain_id),
serialized_transaction,
context_free_bytes
))
).digest()
)

key = EOSKey(
private_key='5JeaxignXEg3mGwvgmwxG6w6wHcRp9ooPw81KjrP2ah6TWSECDN'
)
signature = key.sign(digest)

response = await rpc.push_transaction(
signatures=[signature],
serialized_transaction=binascii.hexlify(serialized_transaction).decode()
)
print(response)


asyncio.get_event_loop().run_until_complete(example())

0 comments on commit e1123e1

Please sign in to comment.