Developing Key Box : Journal Entry for 2018 03(March) 10

in #utopian-io6 years ago (edited)

March 10th, 2018

In this developer's journal of Key Box:

  • The point of this Journal
  • Keybox Source Code
  • Contrasting Beem vs. Steem-Python

keybox.png

The point of this Journal

This Journal is going to be on programming using Beem, and/or Steem-Python. Possibly for improvements to Steemfiles but I can make this exclusively Open-Source stuff if Utopian approves the blog. Readers can take this source code and use it at home, suggest improvements.

Steem-python and Beem

In my previous journal entry for Steemfiles, I discussed a little about the interface I was developing for a command line authority management system for Steem I started yesterday. I ended up using both Beem and Steem-Python in the same package. In the previous journal entry, I also discuss how the interface works in this post. It is roughly 200 lines of python code.

Keybox Source Listing

#!/usr/local/bin/python3.6
# Basic Authority Control
# 
# * Give other users the ability to do things as you
# * Take away the ability from other users to do things as you
#
# 
import sys
import beem.steem
import beem.account
import traceback
import steembase
import steem.steem
import steembase
from getpass import getpass
import hashlib
from optparse import OptionParser


# These lines force us on to the Testnet.
nodes = ['https://testnet.steem.vc']
steembase.chains.known_chains['STEEM'] = {
    'chain_id': '79276aea5d4877d9a25892eaa01b0adf019d3e5cb12a97478df3298ccdd01673',
    'prefix': 'STX', 'steem_symbol': 'STEEM', 'sbd_symbol': 'SBD', 'vests_symbol': 'VESTS'
}


parser = OptionParser()
(options, args) = parser.parse_args()

print("Enter your username :", end="")
sys.stdout.flush()
user = sys.stdin.readline()[0:-1]
    
password = getpass("Enter your master password:")   
a = bytes(user + "owner" + password, 'utf8')
owner_private   = hashlib.sha256(a).hexdigest()
a = bytes(user + "active" + password, 'utf8')
active_private  = hashlib.sha256(a).hexdigest()
a = bytes(user + "posting" + password, 'utf8')
posting_private = hashlib.sha256(a).hexdigest()
osteem = steem.steem.Steem(nodes,keys={'owner':owner_private, 'posting':posting_private, 'active':active_private})
account_info = None

def line_generator():
    while True:
        print(f"[TESTNET] @{user}>", end="")
        sys.stdout.flush()
        line = sys.stdin.readline()
        if len(line):
            line = line[0:-1]
        command = line.split(' ')
        yield command

def help_text():
    return """
SYNOPSIS:
       disallow [username] from [owning|activating|posting]
       allow [username] to [own|activate|post]
       ls
       help
       quit
       
EXAMPLES:
       disallow joeblow from posting
       allow joeblow to own
       ls
       help
       quit
"""

# Process a command (an array of strings)
# Return True iif the loop it is called on should continue going
def process_command(command):
    try:
        if command == ['ls']:
            command = ['keybox', 'ls']
        if command[0] == 'ls' and command[1] == 'keybox':
            command[0] = 'keybox' 
            command[1] = 'ls'
        elif command[0] in ['ls', 'allow', 'disallow']:
            command = ['keybox'] + command
    except:
        pass
    
    try:
        if command[0] == '':
            return True
        elif command[0] == 'keybox':
            if len(command) == 1:
                print("Specify what to do: keybox ls for example")
                return True
            if command[1] == 'ls':
                account_info = osteem.get_account(user)
                
                for keytype in ('owner', 'active', 'posting'):
                    owner_key_info = account_info[keytype]
                    print('---------------------------')
                    print(keytype)
                    print("Threshold: %d" % (owner_key_info['weight_threshold'],))
                    for pair in owner_key_info['key_auths']:
                        print("\tkey: %s, weight: %d" % (pair[0], pair[1]))
                    for account in owner_key_info['account_auths']:
                        print("\taccount:%s weight: %d" % (account[0], account[1],))
                print('---------------------------')
                print("memo")
                print("Threshold: 1")
                print("\tkey: %s, weight: %d" % (account_info['memo_key'], 1))
            elif command[1] == 'disallow':
                foreign_account = command[2]
                _from = command[3]
                action = command[4]
                assert(_from == "from")
                assert(action in ['owning', 'activating', 'posting', 'memoing'])
                weight = 1
                
                if action == 'owning':
                    action = 'owner'
                elif action == 'memoing':
                    action = 'memo'
                elif action == 'activating':
                    action = 'active'
                if action == 'memo':
                    print("Cannot disallow accounts from memo")
                    return True
                if action == 'owner':
                    bsteem = beem.steem.Steem(nodes[0], keys={'owner':owner_private})
                elif action == 'active':
                    bsteem = beem.steem.Steem(nodes[0], keys={'owner':owner_private})
                elif action == 'posting':
                    bsteem = beem.steem.Steem(nodes[0], keys={'active':active_private})
                elif action == 'memo':
                    print("Could not have given away memo authority.")
                    return True
                user_account = beem.account.Account(user, steem_instance=bsteem)
                user_account.disallow(foreign_account, permission=action, account=user)
            elif command[1] == 'allow':
                foreign_account = command[2]
                _to = command[3]
                action = command[4]
                assert(_to == "to")
                assert(action in ['own', 'activate', 'post', 'memo'])
                if action == 'own':
                    action = 'owner'
                elif action == 'post':
                    action = 'posting'
                elif action == 'activate':
                    action = 'active'
                try:
                    weight = command[5]
                except:
                    account_info = osteem.get_account(user)
                    key_info = account_info[action]
                    weight = key_info['weight_threshold']
                try:
                    threshold = command[6]
                except:
                    threshold = None
                    
                if action == 'memo':
                    print("Cannot disallow accounts from memo")
                    return True
                
                if action == 'owner':
                    bsteem = beem.steem.Steem(nodes[0], keys={'owner':owner_private})
                elif action == 'active':
                    bsteem = beem.steem.Steem(nodes[0], keys={'owner':owner_private})
                elif action == 'posting':
                    bsteem = beem.steem.Steem(nodes[0], keys={'active':active_private})
                elif action == 'memo':
                    print("Cannot give away memo authority.")
                    return True
                    
                user_account = beem.account.Account(user, steem_instance=bsteem)
                try:
                    if not threshold:
                        user_account.allow(foreign_account, weight=weight, permission=action, account=user)
                    else:
                        user_account.allow(foreign_account, weight=weight, permission=action, threshold=threshold, account=user)
                except:
                    traceback.print_exc()
                    print("Could not do this with Beem trying with Steem-python...")
                    osteem.allow(foreign_account, weight=weight, permission=action, account=user)
                
            else:
                print(help_text())
        elif command[0] == 'quit':
            return False
        else:
            if command[0] != 'help':
                print("Unknown command: '%s'" % (command[0],))
            print(help_text())
    except Exception:
        traceback.print_exc()
    return True


if len(args) > 0:
    process_command(args)
else:    
    try:
        for command in line_generator():
            if not process_command(command):
                break
    except KeyboardInterrupt:
        pass

Contrasting Beem vs. Steem-Python

creating the Steem object:

Steem-Python:

osteem = steem.steem.Steem(nodes,keys={'owner':owner_private})

Beem

bsteem = beem.steem.Steem(nodes[0], keys={'owner':owner_private})

Getting account information

I couldn't find out how to get this using Beem. Instead I used Steem-python for this part:
account_info = osteem.get_account(user)

Allowing things in Beem

user_account = Account(user, steem_instance=bsteem)
user_account.allow(foreign_account, weight=weight, permission=action, account=user)

Now if I create beem with all of the keys and try an allow function the allow call fails:
bsteem = beem.steem.Steem(nodes[0],keys={'owner':owner_private, 'posting':posting_private, 'active':active_private})
Account(user, steem_instance=bsteem).allow(foreign_account, weight=weight, permission='posting', account=user)

I must use exactly the keys I need in the construction of beem:
bsteem = beem.steem.Steem(nodes[0],keys={'active':active_private})
Account(user, steem_instance=bsteem).allow(foreign_account, weight=weight, permission='posting', account=user)

Previous Journal Entries:

See also



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Awesome! I am going to be following this. Looking forward to more entries.

Your contribution cannot be approved because it does not follow the Utopian Rules.

Related Rules:

  • Blog posts must provide detailed content and overviews related to the open-source projects.
  • You must provide an original and unique editorial content of very high quality, not only news found on the web or general thoughts.

Suggestions:

  • You should provide more detailed overviews, longer and more insightful content in your blog posts. Contributions in the category are expected to have editorial value.

You can contact us on Discord.
[utopian-moderator]

Coin Marketplace

STEEM 0.17
TRX 0.13
JST 0.027
BTC 61129.70
ETH 2660.38
USDT 1.00
SBD 2.55