<p dir="auto">I've posted a few times about my ongoing work on this project before, but now is the first time that<br />
we've reached a milestone that could translate to actual use by people other than me.
<p dir="auto">Before I over promise, a few notes on things that aren't working yet:
<ul>
<li>No broudcast operations yet.
<li>No client side method/param checks.
<li>REST
<p dir="auto">The second one probably isn't that important for most users, and we discussed it in my <a href="https://peakd.com/hive-192847/@pibara/aiohivebot-progress-report-closing-in-on-a-first-release" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">previous post about aiohivebot. The first one though is pretty limiting and should be the first issue to address.
<p dir="auto">Basically you can use the aiohivebot lib to stream different blockchain events from the HIVE blockchain to user defined methods and you can use all of the querying API calls defined with JSON-RPC in order to fetch specific info from the chain, but you can't do any transactions yet with the 0.1.5 version of aiohivebot. You can do <em>some things with this functionality for sure, but many usecases that require the bot or backend to create transactions won't open up untill I add support for that in the near future.
<h2>Installing aiohivebot
<p dir="auto">But let's look at how to install and use <em>aiohivebot. We start off with getching the library from pypi with pip:
<pre><code>python3 -m pip install aiohivebot
<h2>A first bot
<p dir="auto">When you have the lib install, you can make your first empty bot.
<pre><code>#!/usr/bin/env python3
import asyncio
from aiohivebot import BaseBot, NoResponseError, JsonRpcError
class MyBot(BaseBot):
def __init__(self):
super().__init__()
async def block_processed(self,blockno, timestamp, client_info):
print(timestamp.time.isoformat(), blockno, client_info[uri])
pncset = MyBot()
loop = asyncio.get_event_loop()
loop.run_until_complete(pncset.run(loop))
<p dir="auto">Just to get an idea, let's look at that this code does when we run it:
<pre><code>22:25:21 79763118 api.openhive.network
22:25:24 79763119 api.openhive.network
22:25:27 79763120 api.openhive.network
22:25:30 79763121 api.openhive.network
22:25:33 79763122 api.openhive.network
22:25:36 79763123 api.openhive.network
22:25:39 79763124 api.openhive.network
22:25:42 79763125 api.openhive.network
22:25:45 79763126 api.openhive.network
22:25:48 79763127 techcoderx.com
22:25:51 79763128 techcoderx.com
22:25:54 79763129 techcoderx.com
22:25:57 79763130 api.openhive.network
22:26:00 79763131 api.openhive.network
22:26:03 79763132 api.hive.blog
22:26:06 79763133 api.hive.blog
22:26:09 79763134 api.hive.blog
22:26:12 79763135 api.hive.blog
22:26:15 79763136 api.hive.blog
22:26:18 79763137 api.hive.blog
22:26:21 79763138 api.hive.blog
22:26:24 79763139 techcoderx.com
22:26:27 79763140 techcoderx.com
22:26:30 79763141 techcoderx.com
22:26:33 79763142 techcoderx.com
22:26:36 79763143 api.openhive.network
22:26:39 79763144 api.openhive.network
22:26:42 79763145 hive-api.3speak.tv
22:26:45 79763146 hive-api.3speak.tv
22:26:48 79763147 hive-api.3speak.tv
22:26:51 79763148 hive-api.3speak.tv
22:26:54 79763149 api.deathwing.me
<p dir="auto">This output gives a tiny bit of insight into what <em>aiohivebot does under the hood. What happens when you instantiate and run your own bot like this, is that each of the known public API node gets it's own under the hood sub client that runs in it's own task. Each such task will call <a href="https://developers.hive.io/apidefinitions/#condenser_api.get_dynamic_global_properties" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">condenser_api.get_dynamic_global_properties, extract the last known block number from the return value, and if that block or any block before it hasn't yet been processed, it will start fetching blocks, one at a time, skipping blocks that were already fetched by another paralel running task. When the blocks are processed, or when there was nothing left to do, the task pauses for 3 seconds before invoking get_dynamic_global_properties again to see if there are any new blocks.
<p dir="auto">In the bot we just created we made a single method, the <strong>block_proccessed method. This method gets called as last method after any other processing of a single block has finished.
<p dir="auto">You see the blocks ariving once every 3 seconds, in order, and you see there are five differnt nodes returning blocks.
<h2>Method arguments optional
<p dir="auto">As we showed in <a href="#" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">my last blog post, method arguments are all optional in <em>aiohivebot. If you don't use a given argumentm you can simply ommit it from the method fingerprint and everything will still work just fine:
<pre><code> async def block_processed(self, blockno, client_info):
print(blockno, int(client_info["latency"]), client_info["uri"])
<p dir="auto">Lets run it.
<pre><code>79763707 39 api.deathwing.me
79763708 95 hive-api.3speak.tv
79763709 46 api.openhive.network
79763710 38 rpc.ausbit.dev
79763711 54 api.deathwing.me
79763712 39 api.openhive.network
79763713 113 api.deathwing.me
79763714 130 api.openhive.network
79763715 91 api.openhive.network
79763716 65 api.openhive.network
79763717 50 api.openhive.network
79763718 41 api.openhive.network
79763719 34 api.openhive.network
79763720 29 api.openhive.network
79763721 28 api.openhive.network
79763722 27 api.openhive.network
79763723 31 api.openhive.network
79763724 230 techcoderx.com
79763725 213 techcoderx.com
79763726 55 rpc.mahdiyari.info
79763727 61 rpc.mahdiyari.info
<p dir="auto">Notice how much the (decaying average) request latency differs between nodes and also for a single node how it fluctuates over time.
<h2>What methods can you define ?
<p dir="auto">Lets look a little closer at all the different methods you can define in your bot that will connect to actual blockchain or bot process events.
<p dir="auto">There are basicly six types of defined methods.
<ul>
<li>periodicly called methods
<li>low level methods
<li>per operation type methods
<li>per custom_json id l2 methods
<li>hive engine action methods
<li>exceptions method
<h3>periodicly called methods
<p dir="auto">The BaseBot has two methods that get called for each node client roughly four times an hour.
<ul>
<li>node_status
<li>node_api_support
<h4>node_status
<ul>
<li>node_status(node_uri, error_percentage, latency, ok_rate, error_rate, block_rate)
<p dir="auto">The node_status method is invoked every 15 minutes for each of the public API nodes. The node info available in this method is:
<ul>
<li>error_percentage: The decaying average percentage of JSON-RPC calls that resulted in a (non-JSON-RPC) server error.
<li>latency : The decaying average JSON-RPC request-response latency in mili seconds
<li>ok_rate : The number of succesfull JSON-RPC requests per minute over the last 15 minutes.
<li>error_rate: The number of unsuccesfull JSON-RPC requests per minute over the last 15 minutes.
<li>block_rate: The number of blocks fetched per minute from this node over the last 15 minutes.
<p dir="auto">Most bots and backends won't need this info. It's currently meant mostly for development debugging and possibly for node operators.
<h4>node_api_support
<ul>
<li>node_api_support(node_uri, api_support)
<p dir="auto">This method, like the previous one gets invoked roughly every 15 minutes for each node. Every 15 minutes, the nodes get scanned for what sub-APIs<br />
they support. The result is used internally by aiohivebot to determine what nodes it can send what JSON-RPC requests to.<br />
The raw scan results are offered to any bots that wants them with this method.
<p dir="auto">Here is an example of the api_support dict provided to this method by aiohivebot:
<pre><code>{
"wallet_bridge_api": {
"published": false,
"available": false
},
"database_api": {
"published": true,
"available": true
},
"block_api": {
"published": true,
"available": true
},
"follow_api": {
"published": false,
"available": true
},
"transaction_status_api": {
"published": false,
"available": true
},
"rc_api": {
"published": true,
"available": true
},
"bridge": {
"published": false,
"available": true
},
"jsonrpc": {
"published": true,
"available": true
},
"market_history_api": {
"published": true,
"available": true
},
"network_broadcast_api": {
"published": true,
"available": true
},
"account_by_key_api": {
"published": true,
"available": true
},
"account_history_api": {
"published": true,
"available": true
},
"condenser_api": {
"published": true,
"available": true
},
"reputation_api": {
"published": true,
"available": true
}
}
<p dir="auto"><span>This result is for the anyx.io node run by <a href="/@anyx">@anyx.
<p dir="auto">Note that currently if <em>published is true, <em>available might be unreliable, because <em>aiohivebot currently trusts published sub-APIs to be available and won't scan them.
<h3>low level methods
<p dir="auto">There are four low level methods that a bot or backend can implement to regester itself to low level events:
<ul>
<li>block
<li>transaction
<li>operation
<li>block_processed
<h4>block
<ul>
<li>block(block, blockno, transactions, transaction_ids, client_info, timestamp)
<p dir="auto">The block method is invoked before the block gets processed. It can provide the following info:
<ul>
<li>block : The stripped block (without transactions and transaction ids)
<li>blockno : The block number that identifies this block
<li>transactions : A list with all transactions in this block
<li>client_info: A simple dict with basic info on the node this block was fetched from:
<ul>
<li>uri : uri of the node
<li>latency : Current (decaying average) latency for this node
<li>error_percentage: Current (decaying average) server error percentage for the API node.
<li>timestamp : Python timestamp object for the block time
<p dir="auto">We will see many of these same arguments in a lot of other user definable methods.
<h4>block_processed
<ul>
<li>block_processed( blockno, client_info, timestamp)
<p dir="auto">While <em>block gets called before any other processing of the block data, <em>block_processed gets called after all transactions and operations have been processed.<br />
This method is meant mostly to allow bot developers to support loss-less restarts and persistency.
<h4>transaction
<ul>
<li>transaction(tid, transaction, block, client_info, timestamp)
<p dir="auto">This method has been added for completeness. It is suggested you use <em>operation instead. Relevant arguments are:
<ul>
<li>tid: The transaction id
<li>transaction : The (stripped) transaction (without operations).
<li><em>block
<li><em>client_info
<li><em>timestamp
<h4>operation
<ul>
<li>operation(operation, tid, transaction, block, client_info, timestamp)
<p dir="auto">The <em>operation method, if it is defined, will be invoked for each and every operation in a block. It is the wildcard callback.<br />
The arguments that can be provided to this method are:
<ul>
<li>operation : The content dict of the operation
<li><em>tid
<li><em>transaction
<li><em>block
<li><em>client_info
<li><em>timestamp
<h3>per operation type methods
<p dir="auto">Rather than defining one catch all <em>operation method in your bot or backend, it is suggested that instead you define a method for the specific operations in question that you are actualy interested in.
<p dir="auto">Any operation type defined by HIVE is a valid method name. All of the below methods, if defined, can have any of these method arguments:
<ul>
<li>body : The <em>value content of the operation.
<li><em>operation
<li><em>tid
<li><em>transaction
<li><em>block
<li><em>client_info
<li><em>timestamp
<p dir="auto">A non exaustive list of operation methods you may choose to define:
<ul>
<li>account_create_operation
<li>account_update2_operation
<li>account_update_operation
<li>account_witness_proxy_operation
<li>account_witness_vote_operation
<li>cancel_transfer_from_savings_operation
<li>change_recovery_account_operation
<li>claim_account_operation
<li>claim_reward_balance_operation
<li>collateralized_convert_operation
<li>comment_operation
<li>comment_options_operation
<li>convert_operation
<li>create_claimed_account_operation
<li>custom_json_operation
<li>delegate_vesting_shares_operation
<li>delete_comment_operation
<li>feed_publish_operation
<li>limit_order_cancel_operation
<li>limit_order_create_operation
<li>recover_account_operation
<li>request_account_recovery_operation
<li>set_withdraw_vesting_route_operation
<li>transfer_from_savings_operation
<li>transfer_operation
<li>transfer_to_savings_operation
<li>transfer_to_vesting_operation
<li>update_proposal_votes_operation
<li>vote_operation
<li>withdraw_vesting_operation
<li>witness_set_properties_operation
<li>witness_update_operation
<h3>per custom_json id l2 methods
<p dir="auto">Of the above operation types, one is a bit special. The <em>custom_json_operation. That operation allows layer two applications to add L2 implementation specific operations specific to an implementation.<br />
If you are tempted to use custom_json_operation method in your bot or backend, you may instead want to opt for using distinct <strong>L2 methods that specify what L2s you are interested in.<br />
The l2_ methods look a bit deeper into the custom_json_operation, and one of them currently has special status.
<p dir="auto">The arguments for l2 methods are as follows:
<ul>
<li>required_auths : list of required auth HIVE accounts
<li>equired_posting_auths : list of hequired posting auth HIVE accounts
<li>body : JSON-decoded (if possible) version of the custom L2 JSON object.
<li><em>tid
<li><em>transaction
<li><em>block
<li><em>client_info
<li><em>timestamp
<p dir="auto">To illustrate, here is a short list of some possible methods you might want to define. The complete list is too long to list here. This list is just there to show a few notable examples.
<ul>
<li>l2_3speak_publish
<li>l2_actifit
<li>l2_dlux_claim
<li>l2_duat_claim
<li>l2_ecency_notify
<li>l2_exode_market_sell
<li>l2_nftmart
<li>l2_peakd_notify
<li>l2_pm_create_bid
<li>l2_pp_podcast_live
<li>l2_scot_claim_token
<li>l2_sf_transfer_cards
<li>l2_sm_burn_cards
<li>l2_spkcc_shares_claim
<li>l2_ssc_mainnet_hive
<li>l2_terracore_equip
<li>l2_tm_create
<li>l2_waivio_guest_vote
<li>l2_woo_claim_airdrop_rewards
<p dir="auto">Note that methods never have a <em>- character, if an operation type has a "-" character in it, you <strong>MUST replace it with an underscore.
<h3>hive engine action methods
<p dir="auto">There is one L2 that <em>aiohivebot has special support for events for. Hive-Engine. Hive-engine uses ssc-mainnet-hive to communicate contract actions.<br />
You can define a method for such a contract action vy writing your method name as follows:
<ul>
<li>engine_botcontroller_updateMarket
<li>engine_hivepegged_withdraw
<li>engine_market_buy
<li>engine_market_cancel
<li>engine_market_marketBuy
<li>engine_market_marketSell
<li>engine_marketpools_addLiquidity
<li>engine_marketpools_removeLiquidity
<li>engine_marketpools_swapTokens
<li>engine_market_sell
<li>engine_nft_issue
<li>engine_nft_issueMultiple
<li>engine_nftmarket_buy
<li>engine_nftmarket_cancel
<li>engine_nftmarket_changePrice
<li>engine_nftmarket_sell
<li>engine_nft_setProperties
<li>engine_nft_transfer
<li>engine_packmanager_open
<li>engine_tokens_delegate
<li>engine_tokens_issue
<li>engine_tokens_stake
<li>engine_tokens_transfer
<li>engine_tokens_unstake
<li>engine_witnesses_proposeRound
<p dir="auto">The available arguments are tha same as for the l2 methods, but with a slightly diferent meaning:
<ul>
<li><em>required_auths
<li><em>required_posting_auths
<li>body : Content of the hive-engine contract payload.
<li><em>tid
<li><em>transaction
<li><em>block
<li><em>client_info
<li><em>timestamp
<h3>exceptions method
<ul>
<li>exception(exception)
<p dir="auto">This user definable method is a bit of a weird one. If you call the BaseBot constructor with the boolean <em>eat_exceptions argument set to true, then any exception thrown from a used defined method will get <em>eaten by aiohivebot.<br />
More on this three sections down. By defining an <em>exception method, you can do some logging on exceptions that got eaten.
<h2>Calling other JSON-RPC API's from a handler.
<p dir="auto">From within any of the user defined methods that we discussed this far, you can cal JSON-RPC API's that the HIVE public API nodes provide. An example.
<pre><code> async def vote_operation(self, body):
"""Handler for cote_operation type operations in the HIVE block stream"""
if "voter" in body and "author" in body and "permlink" in body:
content = await self.bridge.get_post(author=body["author"], permlink=body["permlink"])
if content and "is_paidout" in content and content["is_paidout"]:
print("Vote by", body["voter"], "on expired post detected: @" + \
body["author"] + "/" + body["permlink"] )
else:
print("Vote by", body["voter"], "on active post")
<p dir="auto">In this example, when a <em>vote operation is found within a block, the user defined <em>vote_operation method gets called. After some sanity check, the code calls <strong>self.bridge.get_post to get info on the post that was voted on.<br />
This info is then used to determine if the vote was done on an active post, or on a post that was already paid out.
<p dir="auto">So what happens under the hood?
<ul>
<li>The BaseBot will check what nodes support the <strong>bridge sub-api
<li>The BaseBot will sort the nodes that <em>could awnser this query based on error rate first and current node latency second.
<li>The Basebot will ask the top of the list node first,and if a server error happens, move on through the sorted list untill a non server-error response is given
<li>If a valid JSON-RPC response is returned by the node, this result is returned.
<li>If a valid JSON-RPC error is returned by the node, a JsonRpcError exception is raised
<li>If after four rounds of server errors by all nodes no valid JSON-RPC response or error is found, a NoResponseError exception is raised
<h2>Eating exceptions
<p dir="auto">Your bot or backend, once at production stable status, should catch and handle JsonRpcError and NoResponseError exceptions, and any other exceptions from other parts of your code. But there could always be some exceptions you didn't expect that arise at a bad time while your bot or backend is running production. It is no substitute for thorough development practices, but for resiliance, you can choose to let your bot run in exception eating mode just to make sure it won't crash because of some missing key in a custom_json operation that you didn't account for.
<pre><code> def __init__(self):
super().__init__(eat_exceptions=True)
async def exception(self, exception):
print("ERROR:", str(exception))
<h2>BaseBot constructor arguments
<p dir="auto">We already saw the <em>start_block constructor argument above. There are currently four optional constructor arguments for the Basebot baseclass:
<ul>
<li>start_block : Start at a designated different block than the current head of chain
<li>roll_back : Don't run life data but instead process roll_back number of blocks and process from that block till the current head block.
<li>roll_back_units : Instead of blocks, roll back in "minutes", "hours" or "days"
<li><em>eat_exceptions
<h2>Basebot run arguments
<pre><code>bot = MyBot()
loop = asyncio.get_event_loop()
loop.run_until_complete(pncset.run(loop, tasks))
<p dir="auto">This is a still fluid part of the aiohivebot, its about hopw to connect other async operations to your code. The <em>run method od Basebot is async, so you can use it together with other async tasks in one big <em>gather if you like.<br />
In some cases it might however be more convenient to ask <em>run that already is build around a gather operation to take controll of the other tasks. The <em>tasks argument to <em>run allows you to supply aditional tasks. More work<br />
is needed to get this working in a coherent way.
<h2>Up next: bot with a web server
<p dir="auto">Python and async web framework have a bit of a problem right now when connecting the framework with other async services. Why? Because they mostly demand controll by using API's that rely on things like a synchonous run with framework specific ways to combine in other paralel tasks. Because aiohivebot is a Web3 library, I feel I can't just get away with letting the user deal with all the dificulties of connecting an async web framework. There is going to need to be some syntactic sugar in the lib for connecting with at least two flavors of popular async python web framework. If you have any suggestions or ideas with respect to the prefered supported frameworks, please leave a comment on this post.
<h2>Other todo issues
<p dir="auto">Now that aiohivebot is available on pypi, i am going to try to keep the API stable and backwards compatible from now on. My first next milestone will be to demonstrate async web framework compatibility, complete with . After that, support for signed operations will be a big next feature for the lib. I'm moving client side API fingerprint checks down in the priorities list as i want to combine that feature with REST HIVE API support. Integration of my coinZdense efforts is at the bottom of my priorities list, but can be brought up to prio two on my list by project donations (see below).
<h1>Available for projects
<p dir="auto">If you think my skills and knowledge could be usefull for your project, I am currently available for contract work for up to 20 hours a week. My hourly rate depends on the type of activity (Python dev, C++ dev or data analysis), wether the project at hand will be open source or not, and if you want to sponsor my pet project coinZdense that aims to create a multi-language programming library for post-quantum signing and least authority subkey management.
<div class="table-responsive"><table>
<thead>
<tr><th>Activity<th>Hourly rate<th>Open source discount<th>Minimal hours<th>Maximum hours
<tbody>
<tr><td>C++ development<td>150 $HBD<td>30 $HBD<td>4<td>-
<tr><td>Python development<td>140 $HBD<td>30 $HBD<td>4<td>-
<tr><td>Data analysis (python/pandas)<td>120 $HBD<td>-<td>2<td>-
<tr><td>Sponsored coinZdense work<td>50 $HBD<td>-<td>0<td>-
<tr><td>Paired up coinZdense work<td>25 $HBD<td>-<td>1<td>2x contract h
<p dir="auto">Development work on open-source project get a 30 $HBD discount on my hourly rates.
<p dir="auto">Next to contract work, you can also become a sponsor of my coinZdense project.<br />
Note that if you pair up to two coinZdense sponsor hours with a contract hour, you can sponsor twice the amount of hours to the coinZdense project.
<p dir="auto">If you wish to pay for my services or sponsor my project with other coins than $HBD, all rates are slightly higher (same rates, but in Euro or euro equivalent value at transaction time). I welcome payments in Euro (through paypall), $HIVE, $QRL $ZEC, $LTC, $DOGE, $BCH, $ETH or $BTC/lightning.
<p dir="auto">Contact: coin<at>z-den.se
I may be interested in your coding skills on a project we are working on.
How to contact you?
Email: coin<at>z-den.se
X/Twitter DM: @EngineerDiet
Discord: pibara_
The Hive.Pizza team manually curated this post.
Learn more at https://hive.pizza.