Ejemplo n.º 1
0
    def show_asset_state(self, args):
        item = get_arg(args)

        if item is not None:

            if item == 'search':
                query = get_arg(args, 1)
                results = Blockchain.Default().SearchAssetState(query)
                print("Found %s results for %s" % (len(results), query))
                for asset in results:
                    bjson = json.dumps(asset.ToJson(), indent=4)
                    tokens = [(Token.Number, bjson)]
                    print_tokens(tokens, self.token_style)
                    print('\n')

                return

            asset = Blockchain.Default().GetAssetState(item)

            if asset is not None:
                bjson = json.dumps(asset.ToJson(), indent=4)
                tokens = [(Token.Number, bjson)]
                print_tokens(tokens, self.token_style)
                print('\n')
            else:
                print("Asset %s not found" % item)
        else:
            print("Please specify an asset hash")
Ejemplo n.º 2
0
    def do_open(self, arguments):
        if self.Wallet:
            self.do_close_wallet()

        item = get_arg(arguments)

        if item and item == 'wallet':

            path = get_arg(arguments, 1)

            if path:

                if not os.path.exists(path):
                    print("Wallet file not found")
                    return

                passwd = prompt("[password]> ", is_password=True)
                password_key = to_aes_key(passwd)

                try:
                    self.Wallet = UserWallet.Open(path, password_key)

                    self.start_wallet_loop()
                    print("Opened wallet at %s" % path)
                except Exception as e:
                    print("Could not open wallet: %s" % e)

            else:
                print("Please specify a path")
        else:
            print("Please specify something to open")
Ejemplo n.º 3
0
    def show_contract_state(self, args):
        item = get_arg(args)

        if item is not None:

            if item.lower() == 'all':
                contracts = Blockchain.Default().ShowAllContracts()
                print("Contracts: %s" % contracts)
            elif item.lower() == 'search':
                query = get_arg(args, 1)
                if query:

                    contracts = Blockchain.Default().SearchContracts(query=query)
                    print("Found %s results for %s" % (len(contracts), query))
                    for contract in contracts:
                        bjson = json.dumps(contract.ToJson(), indent=4)
                        tokens = [(Token.Number, bjson)]
                        print_tokens(tokens, self.token_style)
                        print('\n')
                else:
                    print("Please specify a search query")
            else:
                contract = Blockchain.Default().GetContract(item)

                if contract is not None:
                    contract.DetermineIsNEP5()
                    jsn = contract.ToJson()
                    bjson = json.dumps(jsn, indent=4)
                    tokens = [(Token.Number, bjson)]
                    print_tokens(tokens, self.token_style)
                    print('\n')
        else:
            print("Please specify a contract")
Ejemplo n.º 4
0
    def do_withdraw(self, arguments):
        if not self.Wallet:
            print("Please open a wallet")
            return

        item = get_arg(arguments, 0)

        if item:

            if item == 'holds':
                PrintHolds(self.Wallet)
            elif item == 'delete_holds':
                index_to_delete = -1
                if get_arg(arguments, 1) and int(get_arg(arguments, 1)) > -1:
                    index_to_delete = int(get_arg(arguments, 1))
                DeleteHolds(self.Wallet, index_to_delete)
            elif item == 'cancel_holds':
                if len(arguments) > 1:
                    CancelWithdrawalHolds(self.Wallet, get_arg(arguments, 1))
                else:
                    print("Please specify contract hash to cancel holds for")
            elif item == 'completed':
                ShowCompletedHolds(self.Wallet)
            elif item == 'cleanup':
                CleanupCompletedHolds(self.Wallet)
            elif item == 'all':
                WithdrawAll(self.Wallet)
        else:
            WithdrawOne(self.Wallet)
Ejemplo n.º 5
0
def ImportMultiSigContractAddr(wallet, args):
    if len(args) < 4:
        print("please specify multisig contract like such: 'import multisig_addr {pubkey in wallet} {minimum # of signatures required} {signing pubkey 1} {signing pubkey 2}...'")
        return

    if wallet is None:
        print("please open a wallet")
        return

    pubkey = get_arg(args, 0)
    m = get_arg(args, 1)
    publicKeys = args[2:]

    if publicKeys[1]:
        pubkey_script_hash = Crypto.ToScriptHash(pubkey, unhex=True)

        verification_contract = Contract.CreateMultiSigContract(pubkey_script_hash, int(m), publicKeys)

        address = verification_contract.Address

        wallet.AddContract(verification_contract)

        print("Added multi-sig contract address %s to wallet" % address)

    return 'Hello'
Ejemplo n.º 6
0
    def do_export(self, arguments):
        item = get_arg(arguments)

        if item == 'wif':
            if not self.Wallet:
                return print("Please open a wallet")

            address = get_arg(arguments, 1)
            if not address:
                return print("Please specify an address")

            passwd = prompt("[wallet password]> ", is_password=True)
            if not self.Wallet.ValidatePassword(passwd):
                return print("Incorrect password")

            keys = self.Wallet.GetKeys()
            for key in keys:
                if key.GetAddress() == address:
                    export = key.Export()
                    print("WIF key export: %s" % export)
            return

        elif item == 'nep2':
            if not self.Wallet:
                return print("Please open a wallet")

            address = get_arg(arguments, 1)
            if not address:
                return print("Please specify an address")

            passwd = prompt("[wallet password]> ", is_password=True)
            if not self.Wallet.ValidatePassword(passwd):
                return print("Incorrect password")

            nep2_passwd1 = prompt("[key password]> ", is_password=True)
            if len(nep2_passwd1) < 10:
                return print("Please provide a password with at least 10 characters")

            nep2_passwd2 = prompt("[key password again]> ", is_password=True)
            if nep2_passwd1 != nep2_passwd2:
                return print("Passwords do not match")

            keys = self.Wallet.GetKeys()
            for key in keys:
                export = key.ExportNEP2(nep2_passwd1)
                print("NEP2 key export: %s" % export)
            return

        print("Command export %s not found" % item)
Ejemplo n.º 7
0
    def do_notifications(self, arguments):
        if NotificationDB.instance() is None:
            print("No notification DB Configured")
            return

        item = get_arg(arguments, 0)
        events = []
        if len(item) == 34:
            addr = item
            events = NotificationDB.instance().get_by_addr(addr)
        else:
            try:
                block_height = int(item)
                if block_height < Blockchain.Default().Height:
                    events = NotificationDB.instance().get_by_block(block_height)
                else:
                    print("Block %s not found" % block_height)
                    return
            except Exception as e:
                print("Could not parse block height %s" % e)
                return

        if len(events):
            [print(json.dumps(e.ToJson(), indent=4)) for e in events]
        else:
            print("No events found for %s" % item)
Ejemplo n.º 8
0
    def do_create(self, arguments):
        item = get_arg(arguments)

        if item and item == 'wallet':

            path = get_arg(arguments, 1)

            if path:

                if os.path.exists(path):
                    print("File already exists")
                    return

                passwd1 = prompt("[password]> ", is_password=True)
                passwd2 = prompt("[password again]> ", is_password=True)

                if passwd1 != passwd2 or len(passwd1) < 10:
                    print("Please provide matching passwords that are at least 10 characters long")
                    return

                password_key = to_aes_key(passwd1)

                try:
                    self.Wallet = UserWallet.Create(path=path,
                                                    password=password_key)
                    contract = self.Wallet.GetDefaultContract()
                    key = self.Wallet.GetKey(contract.PublicKeyHash)
                    print("Wallet %s" % json.dumps(self.Wallet.ToJson(), indent=4))
                    print("Pubkey %s" % key.PublicKey.encode_point(True))
                except Exception as e:
                    print("Exception creating wallet: %s" % e)
                    self.Wallet = None
                    if os.path.isfile(path):
                        try:
                            os.remove(path)
                        except Exception as e:
                            print("Could not remove {}: {}".format(path, e))
                    return

                if self.Wallet:
                    self.start_wallet_loop()

            else:
                print("Please specify a path")
Ejemplo n.º 9
0
 def show_header(self, args):
     item = get_arg(args)
     if item is not None:
         header = Blockchain.Default().GetHeaderBy(item)
         if header is not None:
             print(json.dumps(header.ToJson(), indent=4))
         else:
             print("Could not locate header %s\n" % item)
     else:
         print("Please specify a header")
Ejemplo n.º 10
0
def ImportContractAddr(wallet, args):
    if wallet is None:
        print("please open a wallet")
        return

    contract_hash = get_arg(args, 0)
    pubkey = get_arg(args, 1)

    if contract_hash and pubkey:

        if len(pubkey) != 66:
            print("invalid public key format")

        pubkey_script_hash = Crypto.ToScriptHash(pubkey, unhex=True)

        contract = Blockchain.Default().GetContract(contract_hash)

        if contract is not None:

            reedeem_script = contract.Code.Script.hex()

            # there has to be at least 1 param, and the first
            # one needs to be a signature param
            param_list = bytearray(b'\x00')

            # if there's more than one param
            # we set the first parameter to be the signature param
            if len(contract.Code.ParameterList) > 1:
                param_list = bytearray(contract.Code.ParameterList)
                param_list[0] = 0

            verification_contract = Contract.Create(reedeem_script, param_list, pubkey_script_hash)

            address = verification_contract.Address

            wallet.AddContract(verification_contract)

            print("Added contract addres %s to wallet" % address)
            return

    print("Could not add contract.  Invalid public key or contract address")
Ejemplo n.º 11
0
    def show_block(self, args):
        item = get_arg(args)
        txarg = get_arg(args, 1)
        if item is not None:
            block = Blockchain.Default().GetBlock(item)

            if block is not None:

                bjson = json.dumps(block.ToJson(), indent=4)
                tokens = [(Token.Number, bjson)]
                print_tokens(tokens, self.token_style)
                print('\n')
                if txarg and 'tx' in txarg:

                    for tx in block.FullTransactions:
                        print(json.dumps(tx.ToJson(), indent=4))

            else:
                print("Could not locate block %s" % item)
        else:
            print("please specify a block")
Ejemplo n.º 12
0
    def handle_debug_storage(self, args):
        what = get_arg(args)

        if what == 'on':
            settings.USE_DEBUG_STORAGE = True
            print("Debug storage on")
        elif what == 'off':
            settings.USE_DEBUG_STORAGE = False
            print("Debug Storage off")
        elif what == 'reset':
            DebugStorage.instance().reset()
            print("Reset debug storage")
        else:
            print("Please specify on|off|reset")
Ejemplo n.º 13
0
    def show_account_state(self, args):
        item = get_arg(args)

        if item is not None:
            account = Blockchain.Default().GetAccountState(item, print_all_accounts=True)

            if account is not None:
                bjson = json.dumps(account.ToJson(), indent=4)
                tokens = [(Token.Number, bjson)]
                print_tokens(tokens, self.token_style)
                print('\n')
            else:
                print("Account %s not found" % item)
        else:
            print("Please specify an account address")
Ejemplo n.º 14
0
def BuildAndRun(arguments, wallet, verbose=True, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True):
    arguments, from_addr = get_from_addr(arguments)
    path = get_arg(arguments)

    contract_script = Compiler.instance().load_and_save(path)

    newpath = path.replace('.py', '.avm')
    logger.info("Saved output to %s " % newpath)

    debug_map_path = path.replace('.py', '.debug.json')
    debug_map = None
    if os.path.exists(debug_map_path):
        with open(debug_map_path, 'r') as dbg:
            debug_map = json.load(dbg)

    return DoRun(contract_script, arguments, wallet, path, verbose, from_addr, min_fee, invocation_test_mode, debug_map=debug_map)
def DoRun(contract_script, arguments, wallet, path, verbose=True, from_addr=None, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True, debug_map=None):

    test = get_arg(arguments, 1)

    if test is not None and test == 'test':

        if wallet is not None:

            f_args = arguments[2:]
            i_args = arguments[6:]

            script = GatherLoadedContractParams(f_args, contract_script)

            tx, result, total_ops, engine = test_deploy_and_invoke(script, i_args, wallet, from_addr, min_fee, invocation_test_mode, debug_map=debug_map)
            i_args.reverse()

            return_type_results = []

            try:
                rtype = ContractParameterType.FromString(f_args[1])
                for r in result:
                    cp = ContractParameter.AsParameterType(rtype, r)
                    return_type_results.append(cp.ToJson())
            except Exception as e:
                logger.error('Could not convert result to ContractParameter: %s ' % e)

            if tx is not None and result is not None:
                if verbose:
                    print("\n-----------------------------------------------------------")
                    print("Calling %s with arguments %s " % (path, i_args))
                    print("Test deploy invoke successful")
                    print("Used total of %s operations " % total_ops)
                    print("Result %s " % return_type_results)
                    print("Invoke TX gas cost: %s " % (tx.Gas.value / Fixed8.D))
                    print("-------------------------------------------------------------\n")

                return tx, result, total_ops, engine
            else:
                if verbose:
                    print("Test invoke failed")
                    print("tx is, results are %s %s " % (tx, result))

        else:

            print("please open a wallet to test built contract")

    return None, None, None, None
Ejemplo n.º 16
0
def DoRun(contract_script, arguments, wallet, path, verbose=True, from_addr=None, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True, debug_map=None):

    test = get_arg(arguments, 1)

    if test is not None and test == 'test':

        if wallet is not None:

            f_args = arguments[2:]
            i_args = arguments[6:]

            script = GatherLoadedContractParams(f_args, contract_script)

            tx, result, total_ops, engine = test_deploy_and_invoke(script, i_args, wallet, from_addr, min_fee, invocation_test_mode, debug_map=debug_map)
            i_args.reverse()

            return_type_results = []

            try:
                rtype = ContractParameterType.FromString(f_args[1])
                for r in result:
                    cp = ContractParameter.AsParameterType(rtype, r)
                    return_type_results.append(cp.ToJson())
            except Exception as e:
                logger.error('Could not convert result to ContractParameter: %s ' % e)

            if tx is not None and result is not None:
                if verbose:
                    print("\n-----------------------------------------------------------")
                    print("Calling %s with arguments %s " % (path, i_args))
                    print("Test deploy invoke successful")
                    print("Used total of %s operations " % total_ops)
                    print("Result %s " % return_type_results)
                    print("Invoke TX gas cost: %s " % (tx.Gas.value / Fixed8.D))
                    print("-------------------------------------------------------------\n")

                return tx, result, total_ops, engine
            else:
                if verbose:
                    print("Test invoke failed")
                    print("tx is, results are %s %s " % (tx, result))

        else:

            print("please open a wallet to test built contract")

    return None, None, None, None
Ejemplo n.º 17
0
def DoRun(contract_script, arguments, wallet, path):

    try:

        test = get_arg(arguments, 1)

        if test is not None and test == 'test':

            if wallet is not None:

                f_args = arguments[2:]
                i_args = arguments[5:]

                script = GatherLoadedContractParams(f_args, contract_script)

                tx, result, total_ops = test_deploy_and_invoke(
                    script, i_args, wallet)
                i_args.reverse()

                if tx is not None and result is not None:
                    print(
                        "\n-----------------------------------------------------------"
                    )
                    print("Calling %s with arguments %s " % (path, i_args))
                    print("Test deploy invoke successful")
                    print("Used total of %s operations " % total_ops)
                    print("Result %s " % result)
                    print("Invoke TX gas cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------\n"
                    )

                    return
                else:
                    print("test ivoke failed")
                    print("tx is, results are %s %s " % (tx, result))
                    return

            else:

                print("please open a wallet to test built contract")

    except Exception as e:
        print("could not bulid %s " % e)
        traceback.print_stack()
        traceback.print_exc()
Ejemplo n.º 18
0
 def show_tx(self, args):
     if len(args):
         try:
             txid = UInt256.ParseString(get_arg(args))
             tx, height = Blockchain.Default().GetTransaction(txid)
             if height > -1:
                 jsn = tx.ToJson()
                 jsn['height'] = height
                 jsn['unspents'] = [uns.ToJson(tx.outputs.index(uns)) for uns in
                                    Blockchain.Default().GetAllUnspent(txid)]
                 tokens = [("class:command", json.dumps(jsn, indent=4))]
                 print_formatted_text(FormattedText(tokens), style=self.token_style)
                 print('\n')
         except Exception as e:
             print("Could not find transaction from args: %s (%s)" % (e, args))
     else:
         print("Please specify a TX hash")
Ejemplo n.º 19
0
 def show_tx(self, args):
     item = get_arg(args)
     if item is not None:
         try:
             tx, height = Blockchain.Default().GetTransaction(item)
             if height > -1:
                 bjson = json.dumps(tx.ToJson(), indent=4)
                 tokens = [(Token.Command, bjson)]
                 print_tokens(tokens, self.token_style)
                 print('\n')
         except Exception as e:
             print("Could not find transaction with id %s" % item)
             print(
                 "Please specify a TX hash like 'db55b4d97cf99db6826967ef4318c2993852dff3e79ec446103f141c716227f6'"
             )
     else:
         print("Please specify a TX hash")
Ejemplo n.º 20
0
    def show_account_state(self, args):
        item = get_arg(args)

        if item is not None:
            account = Blockchain.Default().GetAccountState(
                item, print_all_accounts=True)

            if account is not None:
                bjson = json.dumps(account.ToJson(), indent=4)
                tokens = [("class:number", bjson)]
                print_formatted_text(FormattedText(tokens),
                                     style=self.token_style)
                print('\n')
            else:
                print("Account %s not found" % item)
        else:
            print("Please specify an account address")
Ejemplo n.º 21
0
 def show_tx(self, args):
     if len(args):
         try:
             txid = UInt256.ParseString(get_arg(args))
             tx, height = Blockchain.Default().GetTransaction(txid)
             if height > -1:
                 jsn = tx.ToJson()
                 jsn['height'] = height
                 jsn['unspents'] = [uns.ToJson(tx.outputs.index(uns)) for uns in
                                    Blockchain.Default().GetAllUnspent(txid)]
                 tokens = [(Token.Command, json.dumps(jsn, indent=4))]
                 print_tokens(tokens, self.token_style)
                 print('\n')
         except Exception as e:
             print("Could not find transaction from args: %s (%s)" % (e, args))
     else:
         print("Please specify a TX hash")
Ejemplo n.º 22
0
def DoRun(contract_script, arguments, wallet, path, verbose=True):

    test = get_arg(arguments, 1)

    if test is not None and test == 'test':

        if wallet is not None:

            f_args = arguments[2:]
            i_args = arguments[6:]

            script = GatherLoadedContractParams(f_args, contract_script)

            tx, result, total_ops, engine = test_deploy_and_invoke(
                script, i_args, wallet)
            i_args.reverse()
            #print (type(result))

            if tx is not None and result is not None:
                if False:
                    print(
                        "\n-----------------------------------------------------------"
                    )
                    print("Calling %s with arguments %s " % (path, i_args))
                    print("Test deploy invoke successful")
                    print("Used total of %s operations " % total_ops)
                    print("Result %s " % result)
                    print(type(result))
                    print("Invoke TX gas cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------\n"
                    )

                return tx, result, total_ops, engine
            else:
                if verbose:
                    print("Test invoke failed")
                    print("tx is, results are %s %s " % (tx, result))

        else:

            print("please open a wallet to test built contract")

    return None, None, None, None
Ejemplo n.º 23
0
 def execute(self, arguments):
     c1 = get_arg(arguments)
     if c1 is not None:
         try:
             c1 = int(c1)
             if c1 > settings.CONNECTED_PEER_MAX:
                 print(
                     'minpeers setting cannot be bigger than maxpeers setting'
                 )
                 return
             settings.set_min_peers(c1)
         except ValueError:
             print("Please supply a positive integer for minpeers")
             return
         print(f"Minpeers set to {c1}")
         return c1
     else:
         print(f"Maintaining minpeers at {settings.CONNECTED_PEER_MIN}")
         return
Ejemplo n.º 24
0
def LoadAndRun(arguments, wallet):
    arguments, from_addr = get_from_addr(arguments)

    path = get_arg(arguments)

    if '.avm' not in path:
        raise TypeError

    with open(path, 'rb') as f:

        content = f.read()

        try:
            content = binascii.unhexlify(content)
        except Exception:
            pass

        script = content

        return DoRun(script, arguments, wallet, path, from_addr=from_addr)
Ejemplo n.º 25
0
 def execute(self, arguments):
     if len(arguments):
         try:
             txid = UInt256.ParseString(get_arg(arguments))
             tx, height = Blockchain.Default().GetTransaction(txid)
             if height > -1:
                 jsn = tx.ToJson()
                 jsn['height'] = height
                 jsn['unspents'] = [uns.ToJson(tx.outputs.index(uns)) for uns in
                                    Blockchain.Default().GetAllUnspent(txid)]
                 print(json.dumps(jsn, indent=4))
                 return jsn
             else:
                 print(f"Could not find transaction for hash {txid}")
                 return
         except Exception:
             print("Could not find transaction from args: %s" % arguments)
             return
     else:
         print("Please specify the required parameter")
         return
Ejemplo n.º 26
0
    def execute(self, arguments):
        c1 = get_arg(arguments)
        if c1 is not None:

            try:
                c1 = int(c1)
            except ValueError:
                print("Invalid argument")
                return

            if c1 > 10:
                print("Max peers is limited to 10")
                return

            try:
                settings.set_max_peers(c1)
                if c1 < settings.CONNECTED_PEER_MIN:
                    settings.set_min_peers(c1)
                    print(f"Minpeers set to {c1}")
            except ValueError:
                print("Please supply a positive integer for maxpeers")
                return

            nodemgr = NodeManager()
            nodemgr.max_clients = c1

            current_max = settings.CONNECTED_PEER_MAX
            connected_count = len(nodemgr.nodes)
            if current_max < connected_count:
                to_remove = connected_count - c1
                for _ in range(to_remove):
                    last_connected_node = nodemgr.nodes[-1]
                    wait_for(last_connected_node.disconnect()
                             )  # need to avoid it being labelled as dead/bad

            print(f"Maxpeers set to {c1}")
            return c1
        else:
            print(f"Maintaining maxpeers at {settings.CONNECTED_PEER_MAX}")
            return
Ejemplo n.º 27
0
    def execute(self, arguments):
        if NotificationDB.instance() is None:
            print("No notification DB Configured")
            return

        item = get_arg(arguments)
        if item is not None:
            if item[0:2] == "0x":
                item = item[2:]

            if len(item) == 34 and item[0] == 'A':
                events = NotificationDB.instance().get_by_addr(item)

            elif len(item) == 40:
                events = NotificationDB.instance().get_by_contract(item)

            else:
                try:
                    block_height = int(item)
                    if block_height < Blockchain.Default().Height:
                        events = NotificationDB.instance().get_by_block(
                            block_height)
                    else:
                        print("Block %s not found" % block_height)
                        return
                except Exception:
                    print("Could not find notifications from args: %s" %
                          arguments)
                    return

            if len(events):
                [print(json.dumps(e.ToJson(), indent=4)) for e in events]
                return events
            else:
                print("No events found for %s" % item)
                return
        else:
            print("Please specify the required parameter")
            return
Ejemplo n.º 28
0
def LoadAndRun(arguments, wallet):

    path = get_arg(arguments)

    try:

        with open(path, 'rb') as f:

            content = f.read()

            try:
                content = binascii.unhexlify(content)
            except Exception as e:
                pass

            script = content

            print("arguments.... %s " % arguments)
            DoRun(script, arguments, wallet, path)

    except Exception as e:
        print("Could not load script %s " % e)
Ejemplo n.º 29
0
    def execute(self, arguments):
        item = get_arg(arguments)
        if item is not None:
            if item.lower() == "all":
                assets = Blockchain.Default().ShowAllAssets()
                assetlist = []
                for asset in assets:
                    state = Blockchain.Default().GetAssetState(
                        asset.decode('utf-8')).ToJson()
                    asset_dict = {state['name']: state['assetId']}
                    assetlist.append(asset_dict)
                print(json.dumps(assetlist, indent=4))
                return assetlist

            if item.lower() == 'neo':
                assetId = Blockchain.Default().SystemShare().Hash
            elif item.lower() == 'gas':
                assetId = Blockchain.Default().SystemCoin().Hash
            else:
                try:
                    assetId = UInt256.ParseString(item)
                except Exception:
                    print("Could not find asset from args: %s" % arguments)
                    return

            asset = Blockchain.Default().GetAssetState(assetId.ToBytes())

            if asset is not None:
                print(json.dumps(asset.ToJson(), indent=4))
                return asset.ToJson()
            else:
                print("Asset %s not found" % item)
                return
        else:
            print('Please specify the required parameter')
            return
Ejemplo n.º 30
0
    def execute(self, arguments):
        c1 = get_arg(arguments)
        if c1 is not None:
            try:
                current_max = settings.CONNECTED_PEER_MAX
                settings.set_max_peers(c1)
                c1 = int(c1)
                p_len = len(NodeLeader.Instance().Peers)
                if c1 < current_max and c1 < p_len:
                    to_remove = p_len - c1
                    peers = NodeLeader.Instance().Peers
                    for i in range(to_remove):
                        peer = peers[-1]  # disconnect last peer added first
                        peer.Disconnect("Max connected peers reached", isDead=False)
                        peers.pop()

                print(f"Maxpeers set to {c1}")
                return c1
            except ValueError:
                print("Please supply a positive integer for maxpeers")
                return
        else:
            print(f"Maintaining maxpeers at {settings.CONNECTED_PEER_MAX}")
            return
Ejemplo n.º 31
0
def LoadAndRun(arguments, wallet):

    arguments, from_addr = get_from_addr(arguments)

    path = get_arg(arguments)

    try:

        with open(path, 'rb') as f:

            content = f.read()

            try:
                content = binascii.unhexlify(content)
            except Exception as e:
                pass

            script = content

            print("arguments.... %s " % arguments)
            DoRun(script, arguments, wallet, path, from_addr=from_addr)

    except Exception as e:
        print("Could not load script %s " % e)
Ejemplo n.º 32
0
def LoadAndRun(arguments, wallet):
    arguments, from_addr = get_from_addr(arguments)

    path = get_arg(arguments)

    try:

        with open(path, 'rb') as f:

            content = f.read()

            try:
                content = binascii.unhexlify(content)
            except Exception as e:
                pass

            script = content

            DoRun(script, arguments, wallet, path, from_addr=from_addr)

    except Exception as e:
        traceback.print_stack()
        traceback.print_exc(e)
        print("Could not load script %s " % e)
Ejemplo n.º 33
0
    def do_open(self, arguments):
        if self.Wallet:
            self.do_close_wallet()
        item = get_arg(arguments)

        if item and item == 'wallet':
            path = get_arg(arguments, 1)

            if path:
                if not os.path.exists(path):
                    print("Wallet file not found")
                    return

                #passwd = prompt("[password]> ", is_password=True)
                #password_key = to_aes_key(passwd)

                try:
                    self.Wallet = UserWallet.Open(path, to_aes_key("coz"))
                    self.Wallet.ProcessBlocks()
                    self._walletdb_loop = task.LoopingCall(
                        self.Wallet.ProcessBlocks)
                    self._walletdb_loop.start(1)

                    #print("\n\nWallet current height is: %s" % self.Wallet.WalletHeight)
                    #print("\nWait %s seconds after openning wallet..." % 3)
                    #time.sleep(3)
                    print("Opened wallet at %s" % path)

                    #TODO - NeoCompiler.io syncing process
                    blockchainheight = max(Blockchain.Default().HeaderHeight,
                                           Blockchain.Default().Height)
                    print("\nWallet current height is: %s / %s" %
                          (self.Wallet._current_height, blockchainheight))
                    print(
                        "Waiting (at least 3 seconds) before continuing with this wallet ..."
                    )
                    #time.sleep(3)
                    timenow = time.time()
                    timebase = time.time()
                    while (timenow - timebase < 3):
                        timenow = time.time()
                    print(
                        "Waiting until wallet reaches current blockchain height."
                    )
                    walletheight = self.Wallet._current_height
                    blockchainheight = max(Blockchain.Default().HeaderHeight,
                                           Blockchain.Default().Height)
                    #TODO Maybe use blockchainheight +1
                    while (walletheight < blockchainheight):
                        walletheight = self.Wallet._current_height
                        blockchainheight = max(
                            Blockchain.Default().HeaderHeight,
                            Blockchain.Default().Height)
                    print(
                        "After syncing, wallet current height is: %s / %s\n" %
                        (self.Wallet._current_height, blockchainheight))

                except Exception as e:
                    print("Could not open wallet: %s" % e)

            else:
                print("Please specify a path")
        else:
            print("Please specify something to open")
Ejemplo n.º 34
0
    def show_wallet(self, arguments):
        if not self.Wallet:
            print("Please open a wallet")
            return

        item = get_arg(arguments)

        if not item:
            print("Wallet %s " % json.dumps(self.Wallet.ToJson(), indent=4))
            return

        if item in ['v', '--v', 'verbose']:
            print("Wallet %s " %
                  json.dumps(self.Wallet.ToJson(verbose=True), indent=4))
            return
        elif item == 'migrate' and self.Wallet is not None:
            self.Wallet.Migrate()
            print("Migrated wallet")
        elif item == 'delete_addr':
            addr_to_delete = get_arg(arguments, 1)
            DeleteAddress(self, self.Wallet, addr_to_delete)
        elif item == 'delete_token':
            token_to_delete = get_arg(arguments, 1)
            DeleteToken(self.Wallet, token_to_delete)
        elif item == 'close':
            self.do_close_wallet()
        elif item == 'claim':
            ClaimGas(self.Wallet, True, arguments[1:])
        elif item == 'rebuild':
            self.Wallet.Rebuild()
            try:
                item2 = int(get_arg(arguments, 1))
                item2 = Blockchain.Default().Height
                if item2 and item2 > 0:
                    print("Restarting at %s" % item2)
                    self.Wallet._current_height = item2

                #TODO - NeoCompiler.io syncing process - BEGINS
                print(
                    "Waiting, at least, 30 seconds, for wallet to sync and rebuild..."
                )
                #time.sleep(30)
                timenow = time.time()
                timebase = time.time()
                while (timenow - timebase < 30):
                    timenow = time.time()
                walletheight = self.Wallet._current_height
                blockchainheight = max(Blockchain.Default().HeaderHeight,
                                       Blockchain.Default().Height)
                while (walletheight < blockchainheight):
                    walletheight = self.Wallet._current_height
                    blockchainheight = max(Blockchain.Default().HeaderHeight,
                                           Blockchain.Default().Height)
                #TODO - NeoCompiler.io syncing process - ENDS
            except Exception as e:
                print("Problems happened when rebuilding %s" % e)
                pass
        elif item == 'tkn_send':
            token_send(self.Wallet, arguments[1:])
        elif item == 'tkn_send_from':
            token_send_from(self.Wallet, arguments[1:])
        elif item == 'tkn_approve':
            token_approve_allowance(self.Wallet, arguments[1:])
        elif item == 'tkn_allowance':
            token_get_allowance(self.Wallet, arguments[1:], verbose=True)
        elif item == 'tkn_mint':
            token_mint(self.Wallet, arguments[1:])
        elif item == 'tkn_register':
            token_crowdsale_register(self.Wallet, arguments[1:])
        elif item == 'unspent':
            ShowUnspentCoins(self.Wallet, arguments[1:])
        elif item == 'alias':
            if len(arguments) == 3:
                AddAlias(self.Wallet, arguments[1], arguments[2])
            else:
                print("Please supply an address and title")
        else:
            print("Wallet: '{}' is an invalid parameter".format(item))
Ejemplo n.º 35
0
    def do_send(self, arguments):
        try:
            if not self.Wallet:
                print("please open a wallet")
                return
            if len(arguments) < 3:
                print("Not enough arguments")
                return

            to_send = get_arg(arguments)
            address = get_arg(arguments, 1)
            amount = get_arg(arguments, 2)

            assetId = None

            if to_send.lower() == 'neo':
                assetId = Blockchain.Default().SystemShare().Hash
            elif to_send.lower() == 'gas':
                assetId = Blockchain.Default().SystemCoin().Hash
            elif Blockchain.Default().GetAssetState(to_send):
                assetId = Blockchain.Default().GetAssetState(to_send).AssetId

            scripthash = self.Wallet.ToScriptHash(address)
            if scripthash is None:
                print("invalid address")
                return

            f8amount = Fixed8.TryParse(amount)
            if f8amount is None:
                print("invalid amount format")
                return

            if f8amount.value % pow(
                    10, 8 - Blockchain.Default().GetAssetState(
                        assetId.ToBytes()).Precision) != 0:
                print("incorrect amount precision")
                return

            fee = Fixed8.Zero()
            if get_arg(arguments, 3):
                fee = Fixed8.TryParse(get_arg(arguments, 3))

            output = TransactionOutput(AssetId=assetId,
                                       Value=f8amount,
                                       script_hash=scripthash)
            tx = ContractTransaction(outputs=[output])
            ttx = self.Wallet.MakeTransaction(tx=tx,
                                              change_address=None,
                                              fee=fee)

            if ttx is None:
                print("insufficient funds")
                return

            self._wallet_send_tx = ttx

            self._num_passwords_req = 1
            self._gathered_passwords = []
            self._gathering_password = True
            self._gather_password_action = self.do_send_created_tx

        except Exception as e:
            print("could not send: %s " % e)
            traceback.print_stack()
            traceback.print_exc()
Ejemplo n.º 36
0
def ClaimGas(wallet, require_password=True, args=None):
    """

    Args:
        wallet:
        require_password:
        args:

    Returns:
        (claim transaction, relayed status)
            if successful: (tx, True)
            if unsuccessful: (None, False)
    """
    if args:
        params, from_addr_str = get_from_addr(args)
    else:
        params = None
        from_addr_str = None

    unclaimed_coins = wallet.GetUnclaimedCoins()

    unclaimed_count = len(unclaimed_coins)
    if unclaimed_count == 0:
        print("no claims to process")
        return None, False

    max_coins_per_claim = None
    if params:
        max_coins_per_claim = get_arg(params, 0, convert_to_int=True)
        if not max_coins_per_claim:
            print("max_coins_to_claim must be an integer")
            return None, False
        if max_coins_per_claim <= 0:
            print("max_coins_to_claim must be greater than zero")
            return None, False
    if max_coins_per_claim and unclaimed_count > max_coins_per_claim:
        unclaimed_coins = unclaimed_coins[:max_coins_per_claim]

    unclaimed_coin_refs = [coin.Reference for coin in unclaimed_coins]

    available_bonus = Blockchain.Default().CalculateBonusIgnoreClaimed(
        unclaimed_coin_refs)

    if available_bonus == Fixed8.Zero():
        print("No gas to claim")
        return None, False

    claim_tx = ClaimTransaction()
    claim_tx.Claims = unclaimed_coin_refs
    claim_tx.Attributes = []
    claim_tx.inputs = []

    script_hash = wallet.GetChangeAddress()

    # the following can be used to claim gas that is in an imported contract_addr
    # example, wallet claim --from-addr={smart contract addr}
    if from_addr_str:
        script_hash = wallet.ToScriptHash(from_addr_str)
        standard_contract = wallet.GetStandardAddress()
        claim_tx.Attributes = [
            TransactionAttribute(usage=TransactionAttributeUsage.Script,
                                 data=standard_contract.Data)
        ]

    claim_tx.outputs = [
        TransactionOutput(AssetId=Blockchain.SystemCoin().Hash,
                          Value=available_bonus,
                          script_hash=script_hash)
    ]

    context = ContractParametersContext(claim_tx)
    wallet.Sign(context)

    print("\n---------------------------------------------------------------")
    print("Will make claim for %s GAS" % available_bonus.ToString())
    if max_coins_per_claim and unclaimed_count > max_coins_per_claim:
        print(
            "NOTE: You are claiming GAS on %s unclaimed coins. %s additional claim transactions will be required to claim all available GAS."
            % (max_coins_per_claim,
               math.floor(unclaimed_count / max_coins_per_claim)))
    print(
        "------------------------------------------------------------------\n")

    if require_password:
        print("Enter your password to complete this claim")

        passwd = prompt("[Password]> ", is_password=True)

        if not wallet.ValidatePassword(passwd):
            print("incorrect password")
            return None, False

    if context.Completed:

        claim_tx.scripts = context.GetScripts()

        print("claim tx: %s " % json.dumps(claim_tx.ToJson(), indent=4))

        relayed = NodeLeader.Instance().Relay(claim_tx)

        if relayed:
            print("Relayed Tx: %s " % claim_tx.Hash.ToString())
            wallet.SaveTransaction(claim_tx)
        else:

            print("Could not relay tx %s " % claim_tx.Hash.ToString())
        return claim_tx, relayed

    else:

        print("could not sign tx")

    return None, False
Ejemplo n.º 37
0
def construct_and_send(prompter, wallet, arguments, prompt_password=True):
    try:
        if not wallet:
            print("please open a wallet")
            return False
        if len(arguments) < 3:
            print("Not enough arguments")
            return False

        arguments, from_address = get_from_addr(arguments)
        arguments, user_tx_attributes = get_tx_attr_from_args(arguments)
        arguments, owners = get_owners_from_params(arguments)
        arguments, priority_fee = get_fee(arguments)
        to_send = get_arg(arguments)
        address_to = get_arg(arguments, 1)
        amount = get_arg(arguments, 2)

        assetId = get_asset_id(wallet, to_send)

        if assetId is None:
            print("Asset id not found")
            return False

        scripthash_to = lookup_addr_str(wallet, address_to)
        if scripthash_to is None:
            print("invalid address")
            return False

        scripthash_from = None

        if from_address is not None:
            scripthash_from = lookup_addr_str(wallet, from_address)

        # if this is a token, we will use a different
        # transfer mechanism
        if type(assetId) is NEP5Token:
            return do_token_transfer(assetId, wallet, from_address, address_to, amount_from_string(assetId, amount), prompt_passwd=prompt_password, tx_attributes=user_tx_attributes)

        f8amount = Fixed8.TryParse(amount, require_positive=True)
        if f8amount is None:
            print("invalid amount format")
            return False

        if type(assetId) is UInt256 and f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState(assetId.ToBytes()).Precision) != 0:
            print("incorrect amount precision")
            return False

        fee = Fixed8.Zero()
        if priority_fee is not None:
            fee = priority_fee

        print("sending with fee: %s " % fee.ToString())

        output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to)
        tx = ContractTransaction(outputs=[output])

        ttx = wallet.MakeTransaction(tx=tx,
                                     change_address=None,
                                     fee=fee,
                                     from_addr=scripthash_from)

        if ttx is None:
            print("insufficient funds")
            return False

        if prompt_password:
            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return False

        standard_contract = wallet.GetStandardAddress()

        if scripthash_from is not None:
            signer_contract = wallet.GetContract(scripthash_from)
        else:
            signer_contract = wallet.GetContract(standard_contract)

        if not signer_contract.IsMultiSigContract and owners is None:

            data = standard_contract.Data
            tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script,
                                                  data=data)]

        # insert any additional user specified tx attributes
        tx.Attributes = tx.Attributes + user_tx_attributes

        if owners:
            owners = list(owners)
            for owner in owners:
                tx.Attributes.append(
                    TransactionAttribute(usage=TransactionAttributeUsage.Script, data=owner))

        context = ContractParametersContext(tx, isMultiSig=signer_contract.IsMultiSigContract)
        wallet.Sign(context)

        if owners:
            owners = list(owners)
            gather_signatures(context, tx, owners)

        if context.Completed:

            tx.scripts = context.GetScripts()

#            print("will send tx: %s " % json.dumps(tx.ToJson(),indent=4))

            relayed = NodeLeader.Instance().Relay(tx)

            if relayed:
                wallet.SaveTransaction(tx)

                print("Relayed Tx: %s " % tx.Hash.ToString())
                return tx
            else:

                print("Could not relay tx %s " % tx.Hash.ToString())

        else:
            print("Transaction initiated, but the signature is incomplete")
            print(json.dumps(context.ToJson(), separators=(',', ':')))
            return False

    except Exception as e:
        print("could not send: %s " % e)
        traceback.print_stack()
        traceback.print_exc()

    return False
Ejemplo n.º 38
0
def construct_send_basic(wallet, arguments):
    if not wallet:
        print("please open a wallet")
        return False
    if len(arguments) < 3:
        print("Not enough arguments")
        return False

    arguments, from_address = get_from_addr(arguments)
    arguments, priority_fee = get_fee(arguments)
    arguments, user_tx_attributes = get_tx_attr_from_args(arguments)
    arguments, owners = get_owners_from_params(arguments)
    to_send = get_arg(arguments)
    address_to = get_arg(arguments, 1)
    amount = get_arg(arguments, 2)

    assetId = get_asset_id(wallet, to_send)
    if assetId is None:
        print("Asset id not found")
        return False

    scripthash_to = lookup_addr_str(wallet, address_to)
    if scripthash_to is None:
        logger.debug("invalid address")
        return False

    scripthash_from = None
    if from_address is not None:
        scripthash_from = lookup_addr_str(wallet, from_address)
        if scripthash_from is None:
            logger.debug("invalid address")
            return False

    # if this is a token, we will use a different
    # transfer mechanism
    if type(assetId) is NEP5Token:
        return do_token_transfer(assetId,
                                 wallet,
                                 from_address,
                                 address_to,
                                 amount_from_string(assetId, amount),
                                 tx_attributes=user_tx_attributes)

    f8amount = get_asset_amount(amount, assetId)
    if f8amount is False:
        logger.debug("invalid amount")
        return False
    if float(amount) == 0:
        print("amount cannot be 0")
        return False

    fee = Fixed8.Zero()
    if priority_fee is not None:
        fee = priority_fee
        if fee is False:
            logger.debug("invalid fee")
            return False

    output = TransactionOutput(AssetId=assetId,
                               Value=f8amount,
                               script_hash=scripthash_to)
    contract_tx = ContractTransaction(outputs=[output])
    return [contract_tx, scripthash_from, fee, owners, user_tx_attributes]
Ejemplo n.º 39
0
    def do_import(self, arguments):
        item = get_arg(arguments)

        if not item:
            print("Please specify something to import")
            return

        if item == 'wif':
            if not self.Wallet:
                print("Please open a wallet before importing WIF")
                return

            wif = get_arg(arguments, 1)
            if not wif:
                print("Please supply a valid WIF key")
                return

            try:
                prikey = KeyPair.PrivateKeyFromWIF(wif)
                key = self.Wallet.CreateKey(prikey)
                print("Imported key: %s" % wif)
                print("Pubkey: %s\n" % key.PublicKey.encode_point(True).hex())
                print("Wallet: %s" % json.dumps(self.Wallet.ToJson(), indent=4))
            except ValueError as e:
                print(str(e))
            except Exception as e:
                print(str(e))

            return

        elif item == 'nep2':
            if not self.Wallet:
                print("Please open a wallet before importing a NEP2 key")
                return

            nep2_key = get_arg(arguments, 1)
            if not nep2_key:
                print("Please supply a valid NEP2 encrypted private key")
                return

            nep2_passwd = prompt("[key password]> ", is_password=True)

            try:
                prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd)
                key = self.Wallet.CreateKey(prikey)
                print("Imported NEP2 key: %s" % nep2_key)
                print("Pubkey: %s\n" % key.PublicKey.encode_point(True).hex())
                print("Wallet: %s" % json.dumps(self.Wallet.ToJson(), indent=4))
            except ValueError as e:
                print(str(e))
            except Exception as e:
                print(str(e))

            return

        elif item == 'contract':
            return self.load_smart_contract(arguments)

        elif item == 'contract_addr':
            return ImportContractAddr(self.Wallet, arguments[1:])

        elif item == 'watch_addr':
            return ImportWatchAddr(self.Wallet, get_arg(arguments, 1))

        elif item == 'multisig_addr':
            return ImportMultiSigContractAddr(self.Wallet, arguments[1:])

        elif item == 'token':
            return ImportToken(self.Wallet, get_arg(arguments, 1))

        else:
            print("Import of '%s' not implemented" % item)
Ejemplo n.º 40
0
    def do_import(self, arguments):
        item = get_arg(arguments)

        if not item:
            print("please specify something to import")
            return

        if item == 'wif':
            if not self.Wallet:
                print("Please open a wallet before importing WIF")
                return

            wif = get_arg(arguments, 1)
            if not wif:
                print("Please supply a valid WIF key")
                return

            try:
                prikey = KeyPair.PrivateKeyFromWIF(wif)
                key = self.Wallet.CreateKey(prikey)
                print("Imported key %s " % wif)
                print("Pubkey: %s \n" % key.PublicKey.encode_point(True).hex())
                print("Wallet: %s " %
                      json.dumps(self.Wallet.ToJson(), indent=4))
            except ValueError as e:
                print(str(e))
            except Exception as e:
                print(str(e))

            return

        elif item == 'nep2':
            if not self.Wallet:
                print("Please open a wallet before importing a NEP2 key")
                return

            nep2_key = get_arg(arguments, 1)
            if not nep2_key:
                print("Please supply a valid nep2 encrypted private key")
                return

            nep2_passwd = prompt("[Key Password]> ", is_password=True)

            try:
                prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd)
                key = self.Wallet.CreateKey(prikey)
                print("Imported nep2 key: %s " % nep2_key)
                print("Pubkey: %s \n" % key.PublicKey.encode_point(True).hex())
                print("Wallet: %s " %
                      json.dumps(self.Wallet.ToJson(), indent=4))
            except ValueError as e:
                print(str(e))
            except Exception as e:
                print(str(e))

            return

        elif item == 'contract':
            return self.load_smart_contract(arguments)

        elif item == 'contract_addr':
            return ImportContractAddr(self.Wallet, arguments[1:])

        elif item == 'watch_addr':
            return ImportWatchAddr(self.Wallet, get_arg(arguments, 1))

        elif item == 'multisig_addr':
            return ImportMultiSigContractAddr(self.Wallet, arguments[1:])

        elif item == 'token':
            return ImportToken(self.Wallet, get_arg(arguments, 1))

        else:
            print("Import of '%s' not implemented" % item)
Ejemplo n.º 41
0
def construct_send_many(wallet, arguments):
    if len(arguments) is 0:
        print("Please specify the required parameter")
        return

    outgoing = get_arg(arguments, convert_to_int=True)
    if outgoing is None:
        print("Invalid outgoing number")
        return
    if outgoing < 1:
        print("Outgoing number must be >= 1")
        return

    arguments, from_address = get_from_addr(arguments)
    arguments, change_address = get_change_addr(arguments)
    arguments, priority_fee = get_fee(arguments)
    arguments, owners = get_owners_from_params(arguments)
    arguments, user_tx_attributes = get_tx_attr_from_args(arguments)

    output = []
    for i in range(outgoing):
        try:
            print('Outgoing Number ', i + 1)
            to_send = prompt("Asset to send: ")
            assetId = get_asset_id(wallet, to_send)
            if assetId is None:
                print("Asset id not found")
                return
            if type(assetId) is NEP5Token:
                print('sendmany does not support NEP5 tokens')
                return
            address_to = prompt("Address to: ")
            scripthash_to = lookup_addr_str(wallet, address_to)
            if scripthash_to is None:
                logger.debug("invalid destination address")
                return
            amount = prompt("Amount to send: ")
            f8amount = get_asset_amount(amount, assetId)
            if f8amount is False:
                logger.debug("invalid amount")
                return
            if float(amount) == 0:
                print("Amount cannot be 0")
                return
            tx_output = TransactionOutput(AssetId=assetId,
                                          Value=f8amount,
                                          script_hash=scripthash_to)
            output.append(tx_output)
        except KeyboardInterrupt:
            print('Transaction cancelled')
            return
    contract_tx = ContractTransaction(outputs=output)

    scripthash_from = None

    if from_address is not None:
        scripthash_from = lookup_addr_str(wallet, from_address)
        if scripthash_from is None:
            logger.debug("invalid source address")
            return

    scripthash_change = None

    if change_address is not None:
        scripthash_change = lookup_addr_str(wallet, change_address)
        if scripthash_change is None:
            logger.debug("invalid change address")
            return

    fee = Fixed8.Zero()
    if priority_fee is not None:
        fee = priority_fee
        if fee is False:
            logger.debug("invalid fee")
            return

    print(f"Sending with fee: {fee.ToString()}")
    return [
        contract_tx, scripthash_from, scripthash_change, fee, owners,
        user_tx_attributes
    ]
Ejemplo n.º 42
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                if c1 == 'off' or c1 == '0':
                    print("Debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                if c1 == 'off' or c1 == '0':
                    print("Smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-debug-notify':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print(
                        "Smart contract emit Notify events on execution failure is now enabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(True)
                if c1 == 'off' or c1 == '0':
                    print(
                        "Smart contract emit Notify events on execution failure is now disabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(
                        False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'vm-log':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("VM instruction execution logging is now enabled")
                    settings.set_log_vm_instruction(True)
                if c1 == 'off' or c1 == '0':
                    print("VM instruction execution logging is now disabled")
                    settings.set_log_vm_instruction(False)

            else:
                print(
                    "Cannot configure VM instruction logging. Please specify on|off"
                )

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off', 'config debug on|off', 'config sc-debug-notify on|off' or 'config vm-log on|off'"
                % what)
Ejemplo n.º 43
0
def construct_and_send(prompter, wallet, arguments):
    try:
        if not wallet:
            print("please open a wallet")
            return
        if len(arguments) < 3:
            print("Not enough arguments")
            return

        to_send = get_arg(arguments)
        address_to = get_arg(arguments, 1)
        amount = get_arg(arguments, 2)
        address_from = get_arg(arguments, 3)

        assetId = None

        if to_send.lower() == 'neo':
            assetId = Blockchain.Default().SystemShare().Hash
        elif to_send.lower() == 'gas':
            assetId = Blockchain.Default().SystemCoin().Hash
        elif Blockchain.Default().GetAssetState(to_send):
            assetId = Blockchain.Default().GetAssetState(to_send).AssetId

        scripthash = wallet.ToScriptHash(address_to)
        if scripthash is None:
            print("invalid address")
            return

        f8amount = Fixed8.TryParse(amount)
        if f8amount is None:
            print("invalid amount format")
            return

        if f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState(assetId.ToBytes()).Precision) != 0:
            print("incorrect amount precision")
            return

        fee = Fixed8.Zero()
        if get_arg(arguments, 3):
            fee = Fixed8.TryParse(get_arg(arguments, 3))

        output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash)
        tx = ContractTransaction(outputs=[output])
        ttx = wallet.MakeTransaction(tx=tx, change_address=None, fee=fee)

        if ttx is None:
            print("insufficient funds")
            return


        passwd = prompt("[Password]> ",
                   completer=prompter.completer,
                   is_password=True,
                   history=prompter.history,
                   get_bottom_toolbar_tokens=prompter.get_bottom_toolbar,
                   style=prompter.token_style)

        if not wallet.ValidatePassword(passwd):
            print("incorrect password")
            return

        context = ContractParametersContext(tx)
        wallet.Sign(context)

        if context.Completed:

            tx.scripts = context.GetScripts()

            wallet.SaveTransaction(tx)

            relayed = NodeLeader.Instance().Relay(tx)

            if relayed:
                print("Relayed Tx: %s " % tx.Hash.ToString())
            else:
                print("Could not relay tx %s " % tx.Hash.ToString())

        else:
            print("Could not sign transaction")
            return




    except Exception as e:
        print("could not send: %s " % e)
        traceback.print_stack()
        traceback.print_exc()
Ejemplo n.º 44
0
def construct_and_send(prompter, wallet, arguments, prompt_password=True):
    try:
        if not wallet:
            print("please open a wallet")
            return False
        if len(arguments) < 3:
            print("Not enough arguments")
            return False

        arguments, from_address = get_from_addr(arguments)
        arguments, user_tx_attributes = get_tx_attr_from_args(arguments)

        to_send = get_arg(arguments)
        address_to = get_arg(arguments, 1)
        amount = get_arg(arguments, 2)

        assetId = get_asset_id(wallet, to_send)

        if assetId is None:
            print("Asset id not found")
            return False

        scripthash_to = lookup_addr_str(wallet, address_to)
        if scripthash_to is None:
            print("invalid address")
            return False

        scripthash_from = None

        if from_address is not None:
            scripthash_from = lookup_addr_str(wallet, from_address)

        # if this is a token, we will use a different
        # transfer mechanism
        if type(assetId) is NEP5Token:
            return do_token_transfer(assetId, wallet, from_address, address_to, amount_from_string(assetId, amount), prompt_passwd=prompt_password)

        f8amount = Fixed8.TryParse(amount, require_positive=True)
        if f8amount is None:
            print("invalid amount format")
            return False

        if type(assetId) is UInt256 and f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState(assetId.ToBytes()).Precision) != 0:
            print("incorrect amount precision")
            return False

        fee = Fixed8.Zero()

        output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to)
        tx = ContractTransaction(outputs=[output])

        ttx = wallet.MakeTransaction(tx=tx,
                                     change_address=None,
                                     fee=fee,
                                     from_addr=scripthash_from)

        if ttx is None:
            print("insufficient funds")
            return False

        if prompt_password:
            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return False

        standard_contract = wallet.GetStandardAddress()

        if scripthash_from is not None:
            signer_contract = wallet.GetContract(scripthash_from)
        else:
            signer_contract = wallet.GetContract(standard_contract)

        if not signer_contract.IsMultiSigContract:

            data = standard_contract.Data
            tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script,
                                                  data=data)]

        # insert any additional user specified tx attributes
        tx.Attributes = tx.Attributes + user_tx_attributes

        context = ContractParametersContext(tx, isMultiSig=signer_contract.IsMultiSigContract)
        wallet.Sign(context)

        if context.Completed:

            tx.scripts = context.GetScripts()

#            print("will send tx: %s " % json.dumps(tx.ToJson(),indent=4))

            relayed = NodeLeader.Instance().Relay(tx)

            if relayed:
                wallet.SaveTransaction(tx)

                print("Relayed Tx: %s " % tx.Hash.ToString())
                return tx
            else:

                print("Could not relay tx %s " % tx.Hash.ToString())

        else:
            print("Transaction initiated, but the signature is incomplete")
            print(json.dumps(context.ToJson(), separators=(',', ':')))
            return False

    except Exception as e:
        print("could not send: %s " % e)
        traceback.print_stack()
        traceback.print_exc()

    return False
Ejemplo n.º 45
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                if c1 == 'off' or c1 == '0':
                    print("Debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                if c1 == 'off' or c1 == '0':
                    print("Smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-debug-notify':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print(
                        "Smart contract emit Notify events on execution failure is now enabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(True)
                if c1 == 'off' or c1 == '0':
                    print(
                        "Smart contract emit Notify events on execution failure is now disabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(
                        False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'vm-log':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("VM instruction execution logging is now enabled")
                    settings.set_log_vm_instruction(True)
                if c1 == 'off' or c1 == '0':
                    print("VM instruction execution logging is now disabled")
                    settings.set_log_vm_instruction(False)

            else:
                print(
                    "Cannot configure VM instruction logging. Please specify on|off"
                )

        elif what == 'maxpeers':
            try:
                c1 = int(get_arg(args, 1).lower())
                num_peers = int(c1)
                if num_peers > 0:
                    old_max_peers = settings.CONNECTED_PEER_MAX
                    settings.set_max_peers(num_peers)
                    NodeLeader.Instance().OnUpdatedMaxPeers(
                        old_max_peers, num_peers)
                    print("set max peers to %s " % num_peers)
                else:
                    print("Please specify integer greater than zero")
            except Exception as e:
                print(
                    "Cannot configure max peers. Please specify an integer greater than 0"
                )

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off', 'config debug on|off', 'config sc-debug-notify on|off' or 'config vm-log on|off'"
                % what)
Ejemplo n.º 46
0
    def show_wallet(self, arguments):
        if not self.Wallet:
            print("Please open a wallet")
            return

        item = get_arg(arguments)

        if not item:
            print("Wallet %s " % json.dumps(self.Wallet.ToJson(), indent=4))
            return

        if item in ['v', '--v', 'verbose']:
            print("Wallet %s " % json.dumps(self.Wallet.ToJson(verbose=True), indent=4))
            return
        elif item == 'migrate' and self.Wallet is not None:
            self.Wallet.Migrate()
            print("Migrated wallet")
        elif item == 'delete_addr':
            addr_to_delete = get_arg(arguments, 1)
            DeleteAddress(self, self.Wallet, addr_to_delete)
        elif item == 'delete_token':
            token_to_delete = get_arg(arguments, 1)
            DeleteToken(self.Wallet, token_to_delete)
        elif item == 'close':
            self.do_close_wallet()
        elif item == 'claim':
            ClaimGas(self.Wallet, True, arguments[1:])
        elif item == 'rebuild':
            self.stop_wallet_loop()
            try:
                self.Wallet.Rebuild()
            finally:
                self.start_wallet_loop()
            try:
                item2 = int(get_arg(arguments, 1))
                if item2 and item2 > 0:
                    print("Restarting at %s" % item2)
                    self.Wallet._current_height = item2
            except Exception as e:
                pass
        elif item == 'tkn_send':
            token_send(self.Wallet, arguments[1:])
        elif item == 'tkn_send_from':
            token_send_from(self.Wallet, arguments[1:])
        elif item == 'tkn_approve':
            token_approve_allowance(self.Wallet, arguments[1:])
        elif item == 'tkn_allowance':
            token_get_allowance(self.Wallet, arguments[1:], verbose=True)
        elif item == 'tkn_mint':
            token_mint(self.Wallet, arguments[1:])
        elif item == 'tkn_register':
            token_crowdsale_register(self.Wallet, arguments[1:])
        elif item == 'unspent':
            ShowUnspentCoins(self.Wallet, arguments[1:])
        elif item == 'alias':
            if len(arguments) == 3:
                AddAlias(self.Wallet, arguments[1], arguments[2])
            else:
                print("Please supply an address and title")
        else:
            print("Wallet: '{}' is an invalid parameter".format(item))
Ejemplo n.º 47
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                if c1 == 'off' or c1 == '0':
                    print("Debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                if c1 == 'off' or c1 == '0':
                    print("Smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-debug-notify':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Smart contract emit Notify events on execution failure is now enabled")
                    settings.set_emit_notify_events_on_sc_execution_error(True)
                if c1 == 'off' or c1 == '0':
                    print("Smart contract emit Notify events on execution failure is now disabled")
                    settings.set_emit_notify_events_on_sc_execution_error(False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'vm-log':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("VM instruction execution logging is now enabled")
                    settings.set_log_vm_instruction(True)
                if c1 == 'off' or c1 == '0':
                    print("VM instruction execution logging is now disabled")
                    settings.set_log_vm_instruction(False)

            else:
                print("Cannot configure VM instruction logging. Please specify on|off")

        elif what == 'maxpeers':
            try:
                c1 = int(get_arg(args, 1).lower())
                num_peers = int(c1)
                if num_peers > 0:
                    old_max_peers = settings.CONNECTED_PEER_MAX
                    settings.set_max_peers(num_peers)
                    NodeLeader.Instance().OnUpdatedMaxPeers(old_max_peers, num_peers)
                    print("set max peers to %s " % num_peers)
                else:
                    print("Please specify integer greater than zero")
            except Exception as e:
                print("Cannot configure max peers. Please specify an integer greater than 0")

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off', 'config debug on|off', 'config sc-debug-notify on|off' or 'config vm-log on|off'" % what)
Ejemplo n.º 48
0
 def do_sign(self, arguments):
     jsn = get_arg(arguments)
     parse_and_sign(self, self.Wallet, jsn)
Ejemplo n.º 49
0
def construct_send_many(wallet, arguments):
    if not wallet:
        print("please open a wallet")
        return False
    if len(arguments) is 0:
        print("Not enough arguments")
        return False

    outgoing = get_arg(arguments, convert_to_int=True)
    if outgoing is None:
        print("invalid outgoing number")
        return False
    if outgoing < 1:
        print("outgoing number must be >= 1")
        return False

    arguments, from_address = get_from_addr(arguments)
    arguments, change_address = get_change_addr(arguments)
    arguments, priority_fee = get_fee(arguments)
    arguments, owners = get_owners_from_params(arguments)
    arguments, user_tx_attributes = get_tx_attr_from_args(arguments)

    output = []
    for i in range(outgoing):
        print('Outgoing Number ', i + 1)
        to_send = prompt("Asset to send: ")
        assetId = get_asset_id(wallet, to_send)
        if assetId is None:
            print("Asset id not found")
            return False
        if type(assetId) is NEP5Token:
            print('Sendmany does not support NEP5 tokens')
            return False
        address_to = prompt("Address to: ")
        scripthash_to = lookup_addr_str(wallet, address_to)
        if scripthash_to is None:
            logger.debug("invalid address")
            return False
        amount = prompt("Amount to send: ")
        f8amount = get_asset_amount(amount, assetId)
        if f8amount is False:
            logger.debug("invalid amount")
            return False
        if float(amount) == 0:
            print("amount cannot be 0")
            return False
        tx_output = TransactionOutput(AssetId=assetId,
                                      Value=f8amount,
                                      script_hash=scripthash_to)
        output.append(tx_output)
    contract_tx = ContractTransaction(outputs=output)

    scripthash_from = None

    if from_address is not None:
        scripthash_from = lookup_addr_str(wallet, from_address)
        if scripthash_from is None:
            logger.debug("invalid address")
            return False

    scripthash_change = None

    if change_address is not None:
        scripthash_change = lookup_addr_str(wallet, change_address)
        if scripthash_change is None:
            logger.debug("invalid address")
            return False

    fee = Fixed8.Zero()
    if priority_fee is not None:
        fee = priority_fee
        if fee is False:
            logger.debug("invalid fee")
            return False

    print("sending with fee: %s " % fee.ToString())
    return [
        contract_tx, scripthash_from, scripthash_change, fee, owners,
        user_tx_attributes
    ]
Ejemplo n.º 50
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print("Debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                elif c1 == 'off' or c1 == '0':
                    print("Debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)
                else:
                    print("Cannot configure log. Please specify on|off")

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print("Smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                elif c1 == 'off' or c1 == '0':
                    print("Smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)
                else:
                    print("Cannot configure log. Please specify on|off")

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-debug-notify':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print(
                        "Smart contract emit Notify events on execution failure is now enabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(True)
                elif c1 == 'off' or c1 == '0':
                    print(
                        "Smart contract emit Notify events on execution failure is now disabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(
                        False)
                else:
                    print("Cannot configure log. Please specify on|off")

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'vm-log':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print("VM instruction execution logging is now enabled")
                    settings.set_log_vm_instruction(True)
                elif c1 == 'off' or c1 == '0':
                    print("VM instruction execution logging is now disabled")
                    settings.set_log_vm_instruction(False)
                else:
                    print(
                        "Cannot configure VM instruction logging. Please specify on|off"
                    )

            else:
                print(
                    "Cannot configure VM instruction logging. Please specify on|off"
                )

        elif what == 'node-requests':
            if len(args) in [2, 3]:
                if len(args) == 3:
                    NodeLeader.Instance().setBlockReqSizeAndMax(
                        int(args[1]), int(args[2]))
                elif len(args) == 2:
                    NodeLeader.Instance().setBlockReqSizeByName(args[1])
            else:
                print("Invalid number of arguments")

        elif what == 'maxpeers':
            c1 = get_arg(args, 1)
            if c1 is not None:
                print("Maxpeers set to ", c1)
                settings.set_max_peers(c1)

            else:
                print("Maintaining current number of maxpeers")
        elif what == 'compiler-nep8':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print("Compiler NEP8 instructions on")
                    settings.COMPILER_NEP_8 = True
                elif c1 == 'off' or c1 == '0':
                    print("Compiler NEP8 instructions off")
                    settings.COMPILER_NEP_8 = False
                else:
                    print(
                        "Cannot configure compiler NEP8 instructions. Please specify on|off"
                    )
            else:
                print(
                    "Cannot configure compiler NEP8 instructions. Please specify on|off"
                )

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off', 'config debug on|off', 'config sc-debug-notify on|off', 'config vm-log on|off', config compiler-nep8 on|off, or 'config maxpeers {num_peers}'"
                % what)
Ejemplo n.º 51
0
 def do_sign(self, arguments):
     jsn = get_arg(arguments)
     parse_and_sign(self, self.Wallet, jsn)
Ejemplo n.º 52
0
    def show_wallet(self, arguments):
        if not self.Wallet:
            print("Please open a wallet")
            return

        item = get_arg(arguments)

        if not item:
            print("Wallet %s " % json.dumps(self.Wallet.ToJson(), indent=4))
            return

        if item in ['v', '--v', 'verbose']:
            print("Wallet %s " %
                  json.dumps(self.Wallet.ToJson(verbose=True), indent=4))
            return
        elif item == 'migrate' and self.Wallet is not None:
            self.Wallet.Migrate()
            print("Migrated wallet")
        elif item == 'create_addr':
            addresses_to_create = get_arg(arguments, 1)
            CreateAddress(self, self.Wallet, addresses_to_create)
        elif item == 'delete_addr':
            addr_to_delete = get_arg(arguments, 1)
            DeleteAddress(self, self.Wallet, addr_to_delete)
        elif item == 'delete_token':
            token_to_delete = get_arg(arguments, 1)
            DeleteToken(self.Wallet, token_to_delete)
        elif item == 'close':
            self.do_close_wallet()
        elif item == 'claim':
            ClaimGas(self.Wallet, True, arguments[1:])
        elif item == 'rebuild':
            self.stop_wallet_loop()
            try:
                self.Wallet.Rebuild()
            finally:
                self.start_wallet_loop()
            try:
                item2 = int(get_arg(arguments, 1))
                if item2 and item2 > 0:
                    print("Restarting at %s" % item2)
                    self.Wallet._current_height = item2
            except Exception as e:
                pass
        elif item == 'tkn_send':
            token_send(self.Wallet, arguments[1:])
        elif item == 'tkn_send_from':
            token_send_from(self.Wallet, arguments[1:])
        elif item == 'tkn_approve':
            token_approve_allowance(self.Wallet, arguments[1:])
        elif item == 'tkn_allowance':
            token_get_allowance(self.Wallet, arguments[1:], verbose=True)
        elif item == 'tkn_mint':
            token_mint(self.Wallet, arguments[1:])
        elif item == 'tkn_register':
            token_crowdsale_register(self.Wallet, arguments[1:])
        elif item == 'tkn_history':
            notification_db = NotificationDB.instance()
            token_history(self.Wallet, notification_db, arguments[1:])
        elif item == 'unspent':
            ShowUnspentCoins(self.Wallet, arguments[1:])
        elif item == 'split':
            SplitUnspentCoin(self.Wallet, arguments[1:])
        elif item == 'alias':
            if len(arguments) == 3:
                AddAlias(self.Wallet, arguments[1], arguments[2])
            else:
                print("Please supply an address and title")
        else:
            print("Wallet: '{}' is an invalid parameter".format(item))