Part 3: Coding on Hive With Python - Writing Data to Hive

in #programming4 months ago

In part 3 we will write some data to the Hive blockchain while learning how to run Python code from a file and how to prompt for text input. Let’s go!

Part 1 covered how to set up a Python development environment. Part 2 taught how to install the Beem module and request data from the Hive blockchain. Parts 1 and 2 are pre-requisites for Part 3.

Writing data to a blockchain is also called broadcasting a transaction. For a transaction to be verified and accepted by the network, it needs to be signed with the correct cryptographic key. In our simple example here, we will make a request to follow a Hive blog. The ‘follow’ transaction requires the account’s private posting key.


Important: Aside on Secrets Management

We must briefly discuss secrets management because you don’t want to expose your private keys.

Hard-coding private keys into your scripts is convenient but dangerous. You might upload your script to GitHub or send it to a friend and leak the key. Anyone who finds your key can use it to control your account. If you ever find yourself in a key leak situation, change your keys immediately using PeakD or another trusted Hive wallet.


Following a Hive Blog Programmatically, using Python

Thanks to @holger80 and Beem, only a few lines of code are needed to ‘follow’ a blog.

For the below example to work, the code needs to be saved to disk as a file. Fire up a text editor and type or copy-paste these few lines of code. Save the file as follow.py somewhere convenient like your Home directory.

import beem
import getpass

name = input('enter your account name: ')
posting_key = getpass.getpass(prompt='enter your private posting key: ')

hive = beem.Hive(keys=[posting_key])
account = beem.account.Account(name, blockchain_instance=hive)

account.follow('learncode') 
print('Done! Ive followed learncode')

Explanation of Python input() function

Python’s input() function will, when the code is run, prompt the user and wait for keyboard input. This way, each time it’s run, it will ask for account information. Alternatively, we could hard-code the inputs in the script, but that’s less than ideal for key management as explained above.

Explanation of Python getpass() function

Python's getpass module and function is an extension of the input() function explained above. The main difference is it hides the input from the console as it's being typed. So by using getpass(), the private posting key won't be visible to shoulder surfers.

Explanation of Beem Hive, Account Objects and follow() Function

After collecting inputs, Beem is asked to set up a Hive object and an Account object. This is a little convoluted. The Hive object is necessary to provide our posting key. The Hive object is also provided as an input parameter when instantiating the Account object. After the Account object is set up, the wallet name and key are in the right place to be used for broadcasting transactions to the network.

The Account object’s follow() function is called. This function triggers a network request to a Hive API node including the transaction details.


Once follow.py is saved to disk we can run the code. In your terminal or CMD, cd (change directory) to where you saved the follow.py file. Then tell the Python interpreter to run the code with command: python3 follow.py. On Windows the command is slightly different: python follow.py. If the code is run successfully you should see the input prompts from the code like below:

$ python3 follow.py
enter your account name: learncode
enter your private posting key: 
Done! Ive followed learncode


Confirming Transaction Details in Hive Block Explorer

After the script is done, if all goes well, the transaction is sent to the network. A Hive block explorer can be used to verify the transaction. It should show up in the account history after 1-2 minutes on hiveblocks.com/@insert-your-account. The transaction preview will look like this:

image.png

Clicking the link in the top right reveals transaction details like below.

image.png

This view shows the Custom_JSON object that was created for us by beem under the hood. Beem sent a transaction with an operation of type 'custom_json'. The custom_json operation has an id of follow and a JSON object content for the details of the follow action. In the JSON object's what key, instead of blog the value could be ignore for mute, or empty ("what":[]) for unfollow/unmute.

custom_json operation ID ->     id      follow
JSON-formatted data      ->     json    ["follow",{"follower":"learncode","following":"learncode","what":["blog"]}]

Aside on Hive Block Explorer Tool

Hive block explorer is a super useful tool for troubleshooting all kinds of Hive transactions. For example, using this tool you can inspect and reverse-engineer custom_JSON transactions from Hive dApps and games.


Advanced: what happens if the wrong key or wrong account name is used?

If a non-existing account name is entered, beem will throw a beem.exceptions.AccountDoesNotExistsException. If an incorrect key is entered, beem will throw a beem.exceptions.MissingKeyError

Handling these exceptions improves the usability of the code. This can be done by wrapping the beem calls in try/except blocks like this.

import beem
import getpass
import sys

name = input('enter your account name: ')
posting_key = getpass.getpass(prompt='enter your private posting key: ')


hive = beem.Hive(keys=[posting_key])

try:
    account = beem.account.Account(name, blockchain_instance=hive)
except beem.exceptions.AccountDoesNotExistsException:
    print('Error! Invalid wallet name')
    sys.exit(1)

try:
    account.follow('learncode') 
except beem.exceptions.MissingKeyError:
    print('Error! Incorrect private posting key')
    sys.exit(1)


print('Done! Ive followed learncode')

Now, some friendly error messages will be shown instead of Python's verbose stack traces.

$ python3 follow.py
enter your account name: learncode
enter your private posting key: 
Error! Incorrect private posting key
$ python3 follow.py
enter your account name: learncode123123
enter your private posting key: 
Error! Invalid wallet name

Wrapping up

That's a wrap for today. In part 3 we learned how to run python code from a file, how to prompt the user for input, how to set up posting keys to use in Beem, how to use Beem to follow a Hive blog. And we saw how to use the Hive block explorer to verify transaction details. As bonus, we also discussed secrets management and how to handle beem exceptions for errors.


p.s. Thanks for reading! Please let me know if anything is unclear or incorrect. This is intended to be a living document to be improved and maintained over time.


p.p.s. This blog is brought to you by the Hive.Pizza team.


p.p.p.s. A channel for #learn-code is set up in the Hive.pizza discord for discussing these lessons and enabling success for all code learners.

Sort:  

Thanks for doing this. I couldn't find much documentation on how to interact with the Hive blockchain or at least not many tutorials.

Hoping to learn and create some simple projects to get started.


Posted via proofofbrain.io

Thanks for reading! https://developers.hive.io is decent documentation for Hived APIs. Beem's documentation is great: https://beem.readthedocs.io/en/latest/beem.account.html

Thank you for pointing me in the right direction. I will check them out and hopefully I can get it to work.


Posted via proofofbrain.io

Let me know if you get stuck. I’m happy to help.

Great tutorial and walk through. I've been using python for many years, now, and it's versatility never ceases to amaze me.

I really like how you've devoted a paragraph to remind users to be careful of their keys. The importance of keys and password management cannot be stressed enough. When I was new to coding I would put passwords right into the script because it was easy, and that's just The Wrong Thing To Do.

Very nice post.

Thanks for reading! Sometimes I get lazy and put the keys in the code, but it’s strongly discouraged. At least use a separate account without much in the wallet if you want to do that.

I am tempted to set up a new account and automate its activities. So far I have only been reading from the blockchain with beem. There is so much possible with this. Have to think up some uses for it.

!PIZZA

Thanks for reading!

These are building blocks. I’ll share more examples of how to apply these concepts in future blogs.

Connect

Trade


@learncode! I sent you a slice of $PIZZA on behalf of @steevc.

Learn more about $PIZZA Token at hive.pizza (2/10)

Congratulations @learncode! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You received more than 200 upvotes.
Your next target is to reach 300 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out the last post from @hivebuzz:

Feedback from the June 1st Hive Power Up Day
Support the HiveBuzz project. Vote for our proposal!

Woot! Awesome! Hi again @traciyork. Thanks for all of the HiveBuzz love.

LOL! While I'd be happy to take credit for the awesome replies from @hivebuzz, I'm not the one leaving them. But thanks for the shout out, @learncode! 😊

Thank you @learncode ❤️❤️❤️

Support us back and vote for our witness.
You will get one more badge and more powerful upvotes from us on your posts with your next notifications.

OK, got a couple of questions:

Should I run this from the cmd or from the python enviroment?

I tried from the cmd and it gave me a "traceback" from all the actions (I guess). And in the last line it gave me an error for not loading Base58 object

File "C:\Python39\lib\site-packages\beemgraphenebase\base58.py", line 49, in __init__
    raise ValueError("Error loading Base58 object")
ValueError: Error loading Base58 object 

What should I do from here?

Ok, now we have it!

image.png

The error was in my private keys, for some reason the ctrl+c doesn't work in the CMD, had to click and paste!

Thanks for all the help!
!PIZZA

Cool post!
Let's be friends :D

Thanks for reading! I like friends.

Note that user comments that all over the place. Makes you wonder if they really mean it ;)