Skip to content

Commit

Permalink
Merge branch 'beos_changes4' into 'beos-initial-release'
Browse files Browse the repository at this point in the history
Supplement cleos newaccount functionality by delegateram option EOSIO#8

See merge request blocktrades/beos-core!10
  • Loading branch information
vogel76 committed Nov 9, 2018
2 parents 8bc0fdb + cd55ccb commit 19527e4
Show file tree
Hide file tree
Showing 2 changed files with 198 additions and 23 deletions.
83 changes: 60 additions & 23 deletions programs/cleos/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,15 @@ chain::action create_action(const vector<permission_level>& authorization, const
return chain::action{authorization, code, act, variant_to_bin(code, act, args)};
}

chain::action create_delegateram(const name& creator, const name& newaccount, uint32_t numbytes) {
fc::variant act_payload = fc::mutable_variant_object()
("payer", creator.to_string())
("receiver", newaccount.to_string())
("bytes", numbytes);
return create_action(tx_permission.empty() ? vector<chain::permission_level>{{creator,config::active_name}} : get_account_permissions(tx_permission),
config::system_account_name, N(delegateram), act_payload);
}

chain::action create_buyram(const name& creator, const name& newaccount, const asset& quantity) {
fc::variant act_payload = fc::mutable_variant_object()
("payer", creator.to_string())
Expand Down Expand Up @@ -893,6 +902,7 @@ struct create_account_subcommand {
string stake_cpu;
uint32_t buy_ram_bytes_in_kbytes = 0;
uint32_t buy_ram_bytes = 0;
int32_t transfer_ram_in_kbytes = -1;
string buy_ram_eos;
bool transfer;
bool simple;
Expand All @@ -909,18 +919,20 @@ struct create_account_subcommand {
createAccount->add_option("ActiveKey", active_key_str, localized("The active public key for the new account"));

if (!simple) {
createAccount->add_option("--stake-net", stake_net,
(localized("The amount of EOS delegated for net bandwidth")))->required();
createAccount->add_option("--stake-cpu", stake_cpu,
(localized("The amount of EOS delegated for CPU bandwidth")))->required();
createAccount->add_option("--buy-ram-kbytes", buy_ram_bytes_in_kbytes,
(localized("The amount of RAM bytes to purchase for the new account in kibibytes (KiB)")));
createAccount->add_option("--buy-ram-bytes", buy_ram_bytes,
(localized("The amount of RAM bytes to purchase for the new account in bytes")));
createAccount->add_option("--buy-ram", buy_ram_eos,
(localized("The amount of RAM bytes to purchase for the new account in EOS")));
createAccount->add_flag("--transfer", transfer,
(localized("Transfer voting power and right to unstake EOS to receiver")));
createAccount->add_option("--transfer-ram-kbytes", transfer_ram_in_kbytes,
(localized("The amount of RAM bytes transferred to the new account in kibibytes (KiB)")));
createAccount->add_option("--stake-net", stake_net,
(localized("The amount of EOS delegated for net bandwidth")));
createAccount->add_option("--stake-cpu", stake_cpu,
(localized("The amount of EOS delegated for CPU bandwidth")));
createAccount->add_option("--buy-ram-kbytes", buy_ram_bytes_in_kbytes,
(localized("The amount of RAM bytes to purchase for the new account in kibibytes (KiB)")));
createAccount->add_option("--buy-ram-bytes", buy_ram_bytes,
(localized("The amount of RAM bytes to purchase for the new account in bytes")));
createAccount->add_option("--buy-ram", buy_ram_eos,
(localized("The amount of RAM bytes to purchase for the new account in EOS")));
createAccount->add_flag("--transfer", transfer,
(localized("Transfer voting power and right to unstake EOS to receiver")));
}

add_standard_transaction_options(createAccount);
Expand All @@ -937,17 +949,42 @@ struct create_account_subcommand {
} EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid active public key: ${public_key}", ("public_key", active_key_str));
auto create = create_newaccount(creator, account_name, owner_key, active_key);
if (!simple) {
EOSC_ASSERT( buy_ram_eos.size() || buy_ram_bytes_in_kbytes || buy_ram_bytes, "ERROR: One of --buy-ram, --buy-ram-kbytes or --buy-ram-bytes should have non-zero value" );
EOSC_ASSERT( !buy_ram_bytes_in_kbytes || !buy_ram_bytes, "ERROR: --buy-ram-kbytes and --buy-ram-bytes cannot be set at the same time" );
action buyram = !buy_ram_eos.empty() ? create_buyram(creator, account_name, to_asset(buy_ram_eos))
: create_buyrambytes(creator, account_name, (buy_ram_bytes_in_kbytes) ? (buy_ram_bytes_in_kbytes * 1024) : buy_ram_bytes);
auto net = to_asset(stake_net);
auto cpu = to_asset(stake_cpu);
if ( net.get_amount() != 0 || cpu.get_amount() != 0 ) {
action delegate = create_delegate( creator, account_name, net, cpu, transfer);
send_actions( { create, buyram, delegate } );
} else {
send_actions( { create, buyram } );
if( transfer_ram_in_kbytes == -1 )
{
if ( buy_ram_eos.empty() && buy_ram_bytes_in_kbytes == 0) {
std::cerr << "ERROR: Either --buy-ram or --buy-ram-kbytes with non-zero value is required" << std::endl;
return;
}
if ( stake_net.empty() || stake_cpu.empty() ) {
if( stake_net.empty())
std::cerr << "ERROR: --stake_net with non-zero value is required" << std::endl;
if( stake_cpu.empty())
std::cerr << "ERROR: --stake_cpu with non-zero value is required" << std::endl;
return;
}

action buyram = !buy_ram_eos.empty() ? create_buyram(creator, account_name, to_asset(buy_ram_eos))
: create_buyrambytes(creator, account_name, buy_ram_bytes_in_kbytes * 1024);
auto net = to_asset(stake_net);
auto cpu = to_asset(stake_cpu);
if ( net.get_amount() != 0 || cpu.get_amount() != 0 ) {
action delegate = create_delegate( creator, account_name, net, cpu, transfer);
send_actions( { create, buyram, delegate } );
} else {
send_actions( { create, buyram } );
}
}
else
{
if ( transfer_ram_in_kbytes <= 0 ) {
std::cerr << "ERROR: --transfer_ram_in_kbytes with non-zero value is required" << std::endl;
return;
}

uint32_t ram_total = transfer_ram_in_kbytes * 1024;
ram_total += buy_ram_bytes_in_kbytes * 1024;
action delegateram = create_delegateram(creator, account_name, ram_total );
send_actions( { create, delegateram } );
}
} else {
send_actions( { create } );
Expand Down
138 changes: 138 additions & 0 deletions tests/beos_plugin_tests/test05_account_creation_with_delegate_ram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
#!/usr/bin/env python3

import os
import sys
import json
import time
import random
import signal
import requests
import datetime
import argparse
import subprocess

args = None

def run(args):
print(' test05_account_creation_with_delegate_ram:', args)
subprocess.call(args, shell=True)

def importKeys():
run(args.cleos +'wallet import -n default-test05 --private-key ' + args.private_key)

def startWallet():
run('rm -f ' + "~/eosio-wallet/default-test05.wallet" )
run('rm -rf ' + os.path.abspath(args.wallet_dir))
run('mkdir -p ' + os.path.abspath(args.wallet_dir))
time.sleep(.4)
run(args.cleos + 'wallet create -n default-test05 --to-console' )

def stepStartWallet():
startWallet()
importKeys()

def askServer(_request, _isValid) :
try:
request=json.dumps(_request)
server = "http://%s:%s/v1/beos/address_validator" % (args.ip_address, args.port)
json_rpc_headers = {"content-type": "application/json"}
response = requests.post( server, data=request, headers=json_rpc_headers )
response_json = response.json()
print(datetime.datetime.now(),"Server response" ,response_json )
if response_json['is_valid'] != _isValid:
print(datetime.datetime.now(),"[ERROR] Inconsistent 'is_valid' state for account", _request["account_name"],".")
return False
else :
print(datetime.datetime.now(),"[OK] Validity for", _request["account_name"],"address is as expected.")
return True
except Exception as _ex:
print(datetime.datetime.now(),"[ERROR] Something goes wrong during address validation: ", _ex)
return False

def validateAccount(_name, _isValid):
command = {"account_name":_name}
return askServer(command, _isValid)

def generate_name( val ):

#".12345abcdefghijklmnopqrstuvwxyz"

str_idx_name = str( val )

result = ""
for c in str_idx_name:
result += chr( int(c) + 97 )

return result

def createAccountsWithDelegateRAM():
owner_key = "EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV"
active_key = "EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV"
ram = 5

random.seed( time.time() )

#searching 10 times not existing accounts
for i in range( 0, 10 ):
val_owner = random.randint( 10000, 10000000000 );

#limit - only 12 chars
val_new_account = random.randint( 100000000000, 999999999999 );

#creating names according to EOS rules
owner = generate_name( val_owner )
new_account = generate_name( val_new_account )

#checking if newly created names exist
if validateAccount( owner, False ) and validateAccount( new_account, False ):
break

print("===== Creating accounts using delegateram action owner: %s new_account: %s =====" % ( owner, new_account ) )

#creating 'owner' by 'beos.gateway'
run(args.cleos +' --url http://%s:%s system newaccount beos.gateway %s %s %s --transfer-ram-kbytes %s' % (args.ip_address, args.port, owner, args.public_key, args.public_key, ram ) )
ret_01 = validateAccount( owner, True )
print("=====");

#creating 'new_account' by 'owner' - false-test because 'owner' hasn't any resources
run(args.cleos +' --url http://%s:%s system newaccount %s %s %s %s --transfer-ram-kbytes %s' % (args.ip_address, args.port, owner, new_account, owner_key, active_key, ram ) )
ret_02 = validateAccount( new_account, False )
print("=====");

#adding resources to 'owner'
run(args.cleos +'push action eosio initresource \'[ "%s", "1000000000", "100.0000 BEOS", "100.0000 BEOS" ]\' -p eosio' % ( owner ) )
print("=====");

#creating 'new_account' by 'owner'
run(args.cleos +' --url http://%s:%s system newaccount %s %s %s %s --transfer-ram-kbytes %s' % (args.ip_address, args.port, owner, new_account, owner_key, active_key, ram ) )
ret_03 = validateAccount( new_account, True )
print("=====");

if ret_01 and ret_02 and ret_03:
print(datetime.datetime.now(),"[OK] This test has passed.")
exit(0)
else:
print(datetime.datetime.now(),"[ERROR] This test has failed.")
exit(1)

# Command Line Arguments
parser = argparse.ArgumentParser()

parser.add_argument('--public-key', metavar='', help="EOSIO Public Key", default='EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV', dest="public_key")
parser.add_argument('--private-Key', metavar='', help="EOSIO Private Key", default='5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3', dest="private_key")
parser.add_argument('--ip-address', metavar='', help="Ip address of nodeos and keosd", default='127.0.0.1', dest="ip_address")
parser.add_argument('--port', metavar='', help="Port", default='8888')
parser.add_argument('--main-dir', metavar='', help="Main dictory for: cleos, nodeos, keosd", default='')
parser.add_argument('--cleos', metavar='', help="Cleos command", default='programs/cleos/cleos ')
parser.add_argument('--wallet-dir', metavar='', help="Path to wallet directory", default='./wallet/')

if __name__ == "__main__":
args = parser.parse_args()
args.cleos = args.main_dir + args.cleos

try:
stepStartWallet()
createAccountsWithDelegateRAM()
except Exception as _ex:
print("[ERROR] Exeption `%s` occured while executing test05_account_creation_with_delegate_ram ."%(str(_ex)))

0 comments on commit 19527e4

Please sign in to comment.