Exemple #1
0
def main():
    # Use PrivateNet
    settings.setup_privnet()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Exemple #2
0
    def get_peers(self):
        """Get all known nodes and their "state"

        In the current implementation of NodeLeader there is no way
        to know which nodes are bad.
        """
        node = NodeLeader.Instance()
        result = {"connected": [], "unconnected": [], "bad": []}
        connected_peers = []

        for peer in node.Peers:
            result['connected'].append({
                "address": peer.host,
                "port": peer.port
            })
            connected_peers.append("{}:{}".format(peer.host, peer.port))

        # "UnconnectedPeers" is never used. So a check is needed to
        # verify that a given address:port does not belong to a connected peer
        for peer in node.ADDRS:
            addr, port = peer.split(':')
            if peer not in connected_peers:
                result['unconnected'].append({
                    "address": addr,
                    "port": int(port)
                })

        return result
def main():
    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Hook up Klein API to Twisted reactor
    endpoint_description = "tcp:port=%s:interface=localhost" % API_PORT
    endpoint = endpoints.serverFromString(reactor, endpoint_description)
    endpoint.listen(Site(app.resource()))

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Exemple #4
0
 def run(self):
     dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
     dbloop.start(0.1)
     NodeLeader.Instance().Start()
     reactor.suggestThreadPoolSize(15)
     # reactor.callInThread(self.prompt)
     reactor.run(installSignalHandlers=False)
Exemple #5
0
    def __init__(self, incoming_client=False):
        """
        Create an instance.
        The NeoNode class is the equivalent of the C# RemoteNode.cs class. It represents a single Node connected to the client.

        Args:
            incoming_client (bool): True if node is an incoming client and the handshake should be initiated.
        """
        from neo.Network.NodeLeader import NodeLeader

        self.leader = NodeLeader.Instance()
        self.nodeid = self.leader.NodeId
        self.remote_nodeid = random.randint(1294967200, 4294967200)
        self.endpoint = ''
        self.buffer_in = bytearray()
        self.myblockrequests = set()
        self.bytes_in = 0
        self.bytes_out = 0

        self.host = None
        self.port = None
        self.identifier = self.leader.NodeCount
        self.leader.NodeCount += 1
        self.incoming_client = incoming_client
        self.expect_verack_next = False

        self.Log("New Node created %s " % self.identifier)
Exemple #6
0
def start_neo():
    # Use TestNet
    settings.setup_testnet()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    wallet = UserWallet.Open(path, to_aes_key(password))
    # wallet.Rebuild()
    _walletdb_loop = task.LoopingCall(wallet.ProcessBlocks())
    _walletdb_loop.start(.1)
    print("Opened wallet at %s" % path)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run all the things (blocking call)
    reactor.run()
    logger.info("Shutting down.")
Exemple #7
0
def main():
    conn = psycopg2.connect(connection_str)
    cursor = conn.cursor()
    ip_dict = getIpAddressMap(cursor)
    cursor.close()
    conn.close()

    # Use Custom config
    settings.setup("./config.json")
    settings.set_max_peers(500)

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code,
                         args=(
                             connection_str,
                             ip_dict,
                         ))
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run all the things (blocking call)
    reactor.run()
    logger.info("Shutting down.")
Exemple #8
0
    def get_peers(self):
        """Get all known nodes and their 'state' """
        node = NodeLeader.Instance()
        result = {"connected": [], "unconnected": [], "bad": []}
        connected_peers = []

        for peer in node.Peers:
            result['connected'].append({
                "address": peer.host,
                "port": peer.port
            })
            connected_peers.append("{}:{}".format(peer.host, peer.port))

        for addr in node.DEAD_ADDRS:
            host, port = addr.rsplit(':', 1)
            result['bad'].append({"address": host, "port": port})

        # "UnconnectedPeers" is never used. So a check is needed to
        # verify that a given address:port does not belong to a connected peer
        for addr in node.KNOWN_ADDRS:
            host, port = addr.rsplit(':', 1)
            if addr not in connected_peers:
                result['unconnected'].append({
                    "address": host,
                    "port": int(port)
                })

        return result
Exemple #9
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--config", action="store", help="Config file (default. %s)" % PROTOCOL_CONFIG,
                        default=PROTOCOL_CONFIG)
    args = parser.parse_args()
    settings.setup(args.config)

    logger.info("Starting api.py")
    logger.info("Config: %s", args.config)
    logger.info("Network: %s", settings.net_name)

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()



    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Exemple #10
0
def main():

    settings.setup('protocol.coz.json')
    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    global Wallet
    Wallet = UserWallet.Open(path="infinitewallet", password="******")
    logger.info("Created the Wallet")
    logger.info(Wallet.AddressVersion)
    walletdb_loop = task.LoopingCall(Wallet.ProcessBlocks)
    walletdb_loop.start(1)
    #Wallet.CreateKey(KeyPair.PrivateKeyFromWIF(wif))

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Exemple #11
0
def main():
    # Use TestNet
    settings.setup_testnet()
    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Start a thread with custom code
    t = threading.Thread(target=custom_background_stateinfo)
    t.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    t.start()
    # Run all the things (blocking call)
    reactor.run()
    logger.info("Shutting down.")
Exemple #12
0
    def do_send_created_tx(self):
        passwd = self._gathered_passwords[0]
        tx = self._wallet_send_tx
        self._wallet_send_tx = None
        self._gathered_passwords = None
        self._gather_password_action = None

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

        try:
            context = ContractParametersContext(tx)
            self.Wallet.Sign(context)

            if context.Completed:

                tx.scripts = context.GetScripts()

                self.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())

        except Exception as e:
            print("could not sign %s " % e)
            traceback.print_stack()
            traceback.print_exc()
Exemple #13
0
def InvokeWithTokenVerificationScript(wallet,
                                      tx,
                                      token,
                                      fee=Fixed8.Zero(),
                                      invoke_attrs=None):
    wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True)

    if wallet_tx:

        token_contract_state = Blockchain.Default().GetContract(
            token.ScriptHash.ToString())
        print("token contract  %s " % token_contract_state)

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

        if invoke_attrs:
            tx.Attributes += invoke_attrs

        reedeem_script = token_contract_state.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\x00')

        verification_contract = Contract.Create(
            reedeem_script, param_list,
            wallet.GetDefaultContract().PublicKeyHash)

        context = ContractParametersContext(wallet_tx)

        wallet.Sign(context)

        context.Add(verification_contract, 0, 0)

        if context.Completed:

            wallet_tx.scripts = context.GetScripts()

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

            if relayed:
                print("Relayed Tx: %s " % wallet_tx.Hash.ToString())

                # if it was relayed, we save tx
                wallet.SaveTransaction(wallet_tx)

                return wallet_tx
            else:
                print("Could not relay tx %s " % wallet_tx.Hash.ToString())
        else:

            print("Incomplete signature")

    else:
        print("Insufficient funds")

    return False
Exemple #14
0
 def quit(self):
     print('Commands completed.')
     self.running = False
     NodeLeader.Instance().Shutdown()
     Blockchain.Default().Dispose()
     NotificationDB.close()
     reactor.stop()
Exemple #15
0
    def process_transaction(self, contract_tx, fee=None, address_from=None, change_addr=None):
        standard_contract = self.wallet.GetStandardAddress()
        signer_contract = self.wallet.GetContract(standard_contract)

        try:
            tx = self.wallet.MakeTransaction(tx=contract_tx,
                                             change_address=change_addr,
                                             fee=fee,
                                             from_addr=address_from)
        except ValueError:
            # if not enough unspents while fully synced
            raise JsonRpcError(-300, "Insufficient funds")
        except TXFeeError as e:
            raise JsonRpcError(-300, e)

        if tx is None:
            # if not enough unspents while not being fully synced
            raise JsonRpcError(-300, "Insufficient funds")
        data = standard_contract.Data
        tx.Attributes = [
            TransactionAttribute(usage=TransactionAttributeUsage.Script,
                                 data=data)
        ]
        context = ContractParametersContext(
            tx, isMultiSig=signer_contract.IsMultiSigContract
        )
        self.wallet.Sign(context)
        if context.Completed:
            tx.scripts = context.GetScripts()
            self.wallet.SaveTransaction(tx)
            NodeLeader.Instance().Relay(tx)
            return tx.ToJson()
        else:
            return context.ToJson()
    def test_relay(self):
        leader = NodeLeader.Instance()

        def mock_call_later(delay, method, *args):
            method(*args)

        def mock_connect_tcp(host, port, factory):
            node = NeoNode()
            node.endpoint = Endpoint(host, port)
            leader.AddConnectedPeer(node)
            return node

        def mock_send_msg(node, message):
            return True

        with patch('twisted.internet.reactor.connectTCP', mock_connect_tcp):
            with patch('twisted.internet.reactor.callLater', mock_call_later):
                with patch('neo.Network.NeoNode.NeoNode.SendSerializedMessage',
                           mock_send_msg):
                    leader.Start()

                    miner = MinerTransaction()

                    res = leader.Relay(miner)
                    self.assertFalse(res)

                    tx = self._generate_tx()

                    res = leader.Relay(tx)
                    self.assertEqual(res, True)

                    self.assertTrue(tx.Hash.ToBytes() in leader.MemPool.keys())
                    res2 = leader.Relay(tx)
                    self.assertFalse(res2)
 def quit(self):
     print('Shutting down. This may take a bit...')
     self.go_on = False
     PromptData.close_wallet()
     Blockchain.Default().Dispose()
     NodeLeader.Instance().Shutdown()
     reactor.stop()
Exemple #18
0
def main():
    # Setup the blockchain
    settings.setup('protocol.faucet.json')

    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Start a thread with custom code
    #    d = threading.Thread(target=custom_background_code)
    #    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    #    d.start()

    # Run all the things (blocking call)
    #reactor.run()

    port = os.environ.get('FAUCET_PORT', 8080)
    host = os.environ.get('FAUCET_HOST', 'localhost')

    store = ItemStore()
    store.app.run(host, int(port))

    logger.info("Shutting down.")
Exemple #19
0
def InvokeContract(wallet, tx, fee=Fixed8.Zero()):

    wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee)

    if wallet_tx:

        context = ContractParametersContext(wallet_tx)

        wallet.Sign(context)

        if context.Completed:

            wallet_tx.scripts = context.GetScripts()

            wallet.SaveTransaction(wallet_tx)

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

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

            print("Incomplete signature")

    else:
        print("Insufficient funds")

    return False
Exemple #20
0
    def sign_and_finish(self, wallet, jsn):

        context = ContractParametersContext.FromJson(jsn)
        if context is None:
            print("Failed to parse JSON")
            return None

        wallet.Sign(context)

        if context.Completed:

            print("Signature complete, relaying...")

            tx = context.Verifiable
            tx.scripts = context.GetScripts()

            wallet.SaveTransaction(tx)

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

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

            if relayed:
                print("Relayed Tx: %s " % tx.Hash.ToString())
                self.wait_for_tx(tx)
                return('success')

            else:
                print("Could not relay tx %s " % tx.Hash.ToString())
                return('fail')
        else:
            print("Transaction signed, but the signature is still incomplete")
            return(json.dumps(context.ToJson(), separators=(',', ':')))
Exemple #21
0
def InvokeWithTokenVerificationScript(wallet, tx, token, fee=Fixed8.Zero()):

    wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True)

    if wallet_tx:

        token_contract_state = Blockchain.Default().GetContract(token.ScriptHash.ToString())
        print("token contract  %s " % token_contract_state)

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

        reedeem_script = token_contract_state.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\x00')

        verification_contract = Contract.Create(reedeem_script, param_list, wallet.GetDefaultContract().PublicKeyHash)

        context = ContractParametersContext(wallet_tx)

        wallet.Sign(context)

        context.Add(verification_contract, 0, 0)

        if context.Completed:

            wallet_tx.scripts = context.GetScripts()

            relayed = False

#            print("full wallet tx: %s " % json.dumps(wallet_tx.ToJson(), indent=4))
#            toarray = Helper.ToArray(wallet_tx)
#            print("to arary %s " % toarray)

            # check if we can save the tx first
            save_tx = wallet.SaveTransaction(wallet_tx)

            if save_tx:
                relayed = NodeLeader.Instance().Relay(wallet_tx)
            else:
                print("Could not save tx to wallet, will not send tx")

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

            print("Incomplete signature")

    else:
        print("Insufficient funds")

    return False
Exemple #22
0
def InvokeWithdrawTx(wallet, tx, contract_hash):

    #    print("withdraw tx 1 %s " % json.dumps(tx.ToJson(), indent=4))

    requestor_contract = wallet.GetDefaultContract()
    tx.Attributes = [
        TransactionAttribute(usage=TransactionAttributeUsage.Script,
                             data=Crypto.ToScriptHash(
                                 requestor_contract.Script).Data)
    ]

    withdraw_contract_state = Blockchain.Default().GetContract(
        contract_hash.encode('utf-8'))

    withdraw_verification = None

    if withdraw_contract_state is not None:

        reedeem_script = withdraw_contract_state.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(withdraw_contract_state.Code.ParameterList) > 1:
            param_list = bytearray(withdraw_contract_state.Code.ParameterList)
            param_list[0] = 0

        verification_contract = Contract.Create(
            reedeem_script, param_list, requestor_contract.PublicKeyHash)

        address = verification_contract.Address
        withdraw_verification = verification_contract

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

    context.Add(withdraw_verification, 0, 0)

    if context.Completed:

        tx.scripts = context.GetScripts()

        print("withdraw tx %s " % json.dumps(tx.ToJson(), indent=4))

        wallet.SaveTransaction(tx)

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

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

        print("Incomplete signature")
Exemple #23
0
 def execute(self, arguments):
     if len(arguments) in [1, 2]:
         if len(arguments) == 2:
             try:
                 return NodeLeader.Instance().setBlockReqSizeAndMax(
                     int(arguments[0]), int(arguments[1]))
             except ValueError:
                 print(
                     "Invalid values. Please specify a block request part and max size for each node, like 30 and 1000"
                 )
                 return False
         elif len(arguments) == 1:
             return NodeLeader.Instance().setBlockReqSizeByName(
                 arguments[0])
     else:
         print("Please specify the required parameter")
         return False
    def test_get_transaction(self):
        # delete any tx in the mempool
        self._clear_mempool()

        # generate a new tx
        tx = self._generate_tx(Fixed8.TryParse(5))

        # try to get it
        res = NodeLeader.Instance().GetTransaction(tx.Hash.ToBytes())
        self.assertIsNone(res)

        # now add it to the mempool
        NodeLeader.Instance().MemPool[tx.Hash.ToBytes()] = tx

        # and try to get it
        res = NodeLeader.Instance().GetTransaction(tx.Hash.ToBytes())
        self.assertTrue(res is tx)
Exemple #25
0
 def quit(self):
     print('Shutting down. This may take a bit...')
     self.go_on = False
     NotificationDB.close()
     Blockchain.Default().Dispose()
     #reactor.stop() # >>> commented out reactor
     NodeLeader.Instance().Shutdown()
     sys.exit()  # >>> close all widgets
Exemple #26
0
def custom_background_code():
    """ Custom code run in a background thread. Prints the current block height.

    This function is run in a daemonized thread, which means it can be instantly killed at any
    moment, whenever the main thread quits. If you need more safety, don't use a  daemonized
    thread and handle exiting this thread in another way (eg. with signals and events).

    Raises an exception every 5 minutes the block count is blocked and restarts the node
    """
    if settings.is_mainnet:
        network = 'Mainnet'
    elif settings.is_testnet:
        network = 'Testnet'
    else:
        network = 'Privnet'
    counter = 0
    previous_block_count = 0

    while True:
        try:
            logger.info(
                f"Block {str(Blockchain.Default().Height)} / {str(Blockchain.Default().HeaderHeight)}"
            )
            logger.info(
                f"Connected to {len(NodeLeader.Instance().Peers)} peers.")
            for peer in NodeLeader.Instance().Peers:
                logger.info(peer.Address)
            logger.info("\n")
            if previous_block_count == Blockchain.Default().Height:
                counter += 1
                if counter % 5 == 0:
                    error = '{} Node is blocking'.format(network)
                    message = 'Node is blocking at block: {}. Connected peers: {}. Attempting restart.'
                    message = message.format(Blockchain.Default().Height,
                                             len(NodeLeader.Instance().Peers))
                    raise NodeBlockingException(error, message)
            else:
                previous_block_count = Blockchain.Default().Height
                counter = 0
        except Exception as e:
            logger.warning(e)
            NodeLeader.Instance().Shutdown()
            NodeLeader.Instance().Start()
            counter = 0
        sleep(15)
Exemple #27
0
def InvokeContract(wallet, tx, fee=Fixed8.Zero(), from_addr=None, owners=None):
    if from_addr is not None:
        from_addr = PromptUtils.lookup_addr_str(wallet, from_addr)

    try:
        wallet_tx = wallet.MakeTransaction(tx=tx,
                                           fee=fee,
                                           use_standard=True,
                                           from_addr=from_addr)
    except ValueError:
        print("Insufficient funds")
        return False
    except TXFeeError as e:
        print(e)
        return False

    if wallet_tx:

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

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

        if owners:
            gather_signatures(context, wallet_tx, list(owners))

        if context.Completed:

            wallet_tx.scripts = context.GetScripts()

            relayed = False

            #            print("SENDING TX: %s " % json.dumps(wallet_tx.ToJson(), indent=4))

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

            if relayed:
                print("Relayed Tx: %s " % wallet_tx.Hash.ToString())

                wallet.SaveTransaction(wallet_tx)

                return wallet_tx
            else:
                print("Could not relay tx %s " % wallet_tx.Hash.ToString())
        else:

            print("Incomplete signature")

    else:
        print("Insufficient funds")

    return False
Exemple #28
0
def SplitUnspentCoin(wallet, args, prompt_passwd=True):
    """

    example ``wallet split Ab8RGQEWetkhVqXjPHeGN9LJdbhaFLyUXz neo 1 100``
    this would split the second unspent neo vin into 100 vouts

    :param wallet:
    :param args (list): A list of arguments as [Address, asset type, unspent index, divisions]

    :return: bool
    """
    try:
        addr = wallet.ToScriptHash(args[0])
        asset = get_asset_id(wallet, args[1])
        index = int(args[2])
        divisions = int(args[3])
    except Exception as e:
        logger.info("Invalid arguments specified: %s " % e)
        return None

    try:
        unspentItem = wallet.FindUnspentCoinsByAsset(asset,
                                                     from_addr=addr)[index]
    except Exception as e:
        logger.info(
            "Could not find unspent item for asset with index %s %s :  %s" %
            (asset, index, e))
        return None

    outputs = split_to_vouts(asset, addr, unspentItem.Output.Value, divisions)

    contract_tx = ContractTransaction(outputs=outputs,
                                      inputs=[unspentItem.Reference])
    ctx = ContractParametersContext(contract_tx)
    wallet.Sign(ctx)

    print("Splitting: %s " % json.dumps(contract_tx.ToJson(), indent=4))
    if prompt_passwd:
        passwd = prompt("[Password]> ", is_password=True)
        if not wallet.ValidatePassword(passwd):
            print("incorrect password")
            return None

    if ctx.Completed:

        contract_tx.scripts = ctx.GetScripts()

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

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

    return None
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-m", "--mainnet", action="store_true", default=False,
                        help="Use MainNet instead of the default TestNet")
    parser.add_argument("-p", "--privnet", action="store_true", default=False,
                        help="Use PrivNet instead of the default TestNet")
    parser.add_argument("-c", "--config", action="store", help="Use a specific config file")
    parser.add_argument("-t", "--set-default-theme", dest="theme",
                        choices=["dark", "light"], help="Set the default theme to be loaded from the config file. Default: 'dark'")
    parser.add_argument('--version', action='version',
                        version='neo-python v{version}'.format(version=__version__))
    parser.add_argument("-e", "--exec_command", action="store", help="Use a specific commands")


    args = parser.parse_args()

    if args.config and (args.mainnet or args.privnet):
        print("Cannot use both --config and --mainnet/--privnet arguments, please use only one.")
        exit(1)
    if args.mainnet and args.privnet:
        print("Cannot use both --mainnet and --privnet arguments")
        exit(1)

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.privnet:
        settings.setup_privnet()

    mycoms = []
    mycoms2 = []
    if args.exec_command:
        mycoms = args.exec_command.split(',') #print("exec:"+args.exec_command)
        for k in mycoms:
            mycoms2.append( codecs.decode(k, "hex").decode() )


    if args.theme:
        preferences.set_theme(args.theme)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)


    # Start the prompt interface
    cli = PromptInterface()
    cli.mycommands = mycoms2 #['oi', 'oi2']

    # Run
    reactor.suggestThreadPoolSize(15)
    reactor.callInThread(cli.run)
    NodeLeader.Instance().Start()
    reactor.run()
    def test_mempool_check_loop(self):
        # delete any tx in the mempool
        self._clear_mempool()

        # add a tx which is already confirmed
        self._add_existing_tx()

        # and add a tx which is not confirmed
        tx = self._generate_tx(Fixed8.TryParse(20))
        NodeLeader.Instance().MemPool[tx.Hash.ToBytes()] = tx

        # now remove the confirmed tx
        NodeLeader.Instance().MempoolCheck()

        self.assertEqual(
            len(
                list(
                    map(lambda hash: "0x%s" % hash.decode('utf-8'),
                        NodeLeader.Instance().MemPool.keys()))), 1)