How to use the neo.Core.Blockchain.Blockchain.Default function in neo

To help you get started, we’ve selected a few neo examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github CityOfZion / neo-python / neo / Network / LocalNode.py View on Github external
#        self.new_tx_event.wait()

        self.__log.debug("Running add transaction loop")
        while self._disposed == 0:
            transactions = []

            #lock temppool
            #if len(self._temppool == 0): continue
            transactions = list(self._temppool)
            self._temppool = []
            #endlock

            verified = set()
            #lock mempool

            transactions = [tx for tx in transactions if not tx.Hash() in _mempool and not Blockchain.Default().ContainsTransaction(tx.Hash())]

            if len(transactions):
                mempool_current = [v for k,v in _mempool]
                for tx in transactions:
                    if tx.Verify( mempool_current + transactions):
                        verified.add(tx)
                for tx in verified:
                    _mempool[tx.Hash()] = tx

                self.CheckMemPool()
            #endlock

            await self.RelayDirectly(verified)

            if self.InventoryReceived is not None:
                [self.InventoryReceived.on_change(tx) for tx in verified]
github CityOfZion / neo-python / neo / Network / NodeLeader.py View on Github external
def check_bcr_catchup(self):
        """we're exceeding data request speed vs receive + process"""
        logger.debug(f"Checking if BlockRequests has caught up {len(BC.Default().BlockRequests)}")

        # test, perhaps there's some race condition between slow startup and throttle sync, otherwise blocks will never go down
        for peer in self.Peers:  # type: NeoNode
            peer.stop_block_loop(cancel=False)
            peer.stop_peerinfo_loop(cancel=False)
            peer.stop_header_loop(cancel=False)

        if len(BC.Default().BlockRequests) > 0:
            for peer in self.Peers:
                peer.keep_alive()
                peer.health_check(HEARTBEAT_BLOCKS)
                peer_bcr_len = len(peer.myblockrequests)
                # if a peer has cleared its queue then reset heartbeat status to avoid timing out when resuming from "check_bcr" if there's 1 or more really slow peer(s)
                if peer_bcr_len == 0:
                    peer.start_outstanding_data_request[HEARTBEAT_BLOCKS] = 0
github CityOfZion / neo-python / neo / Wallets / Wallet.py View on Github external
    @property
    def IsSynced(self):
        """
        Check if wallet is synced.

        Returns:
            bool: True if wallet is synced.

        """
        if Blockchain.Default().Height == 0:
            return False

        if (int(100 * self._current_height / Blockchain.Default().Height)) < 100:
            return False
        else:
            return True
github CityOfZion / neo-privatenet-docker / scripts / claim_neo_and_gas_fixedwallet.py View on Github external
def run(self):
        dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
        dbloop.start(.1)
        Blockchain.Default().PersistBlocks()

        while Blockchain.Default().Height < 2:
            print("Waiting for chain to sync...")
            time.sleep(1)

        # Claim initial NEO
        address = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y"
        self.claim_initial_neo(address)

        # Open wallet again
        print("Opening wallet %s" % self.wallet_fn)
        self.wallet = UserWallet.Open(self.wallet_fn, to_aes_key("coz"))
        self.wallet.ProcessBlocks()
        self._walletdb_loop = task.LoopingCall(self.wallet.ProcessBlocks)
        self._walletdb_loop.start(1)
        # self.wallet.Rebuild()
github CityOfZion / neo-python / neo / bin / prompt.py View on Github external
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")
github CityOfZion / neo-local / privnet / scripts / claim_neo_and_gas_fixedwallet.py View on Github external
def send_neo(wallet, address_from, address_to, amount):
        assetId = None

        assetId = Blockchain.Default().SystemShare().Hash

        scripthash_to = wallet.ToScriptHash(address_to)
        scripthash_from = wallet.ToScriptHash(address_from)

        f8amount = Fixed8.TryParse(amount)

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

        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:
            raise Exception("insufficient funds, were funds already moved from multi-sig contract?")

        context = ContractParametersContext(tx, isMultiSig=True)
        wallet.Sign(context)

        if context.Completed == False:
            raise Exception("Something went wrong, multi-sig transaction failed")
github CityOfZion / neo-python / neo / bin / prompt.py View on Github external
def __init__(self, history_filename=None):
        PromptData.Prompt = self
        if history_filename:
            PromptInterface.history = PromptFileHistory(history_filename)

        self.input_parser = InputParser()
        self.start_height = Blockchain.Default().Height
        self.start_dt = datetime.datetime.utcnow()
github CityOfZion / neo-python / examples / smart-contract.py View on Github external
# because a KeyboardInterrupt is so violent it can shutdown the DB in an unpredictable state.
    loop.add_signal_handler(SIGINT, system_exit)
    main_task = loop.create_task(setup_and_start(loop))

    try:
        loop.run_forever()
    except SystemExit:
        logger.info("Shutting down...")
        p2p = NetworkService()
        loop.run_until_complete(p2p.shutdown())
        loop.run_until_complete(shutdown())
        loop.stop()
    finally:
        loop.close()

    Blockchain.Default().Dispose()
github CityOfZion / neo-python / neo / Wallets / Wallet.py View on Github external
def GetSyncedBalances(self):
        """
        Returns a list of synced balances. The list looks like this:
        [('NEO', 100.0), ('NEOGas', 100.0)]

        Returns
            list: [(asset_name, amount), ...]
        """
        assets = self.GetCoinAssets()
        balances = []
        for asset in assets:
            if type(asset) is UInt256:
                bc_asset = Blockchain.Default().GetAssetState(asset.ToBytes())
                total = self.GetBalance(asset).value / Fixed8.D
                balances.append((bc_asset.GetName(), total))
            elif type(asset) is NEP5Token.NEP5Token:
                balances.append((asset.symbol, self.GetBalance(asset)))
        return balances
github CityOfZion / neo-python / neo / Prompt / Commands / SC.py View on Github external
def execute(self, arguments):
        if len(arguments) != 1:
            print("Please specify the required parameter")
            return

        Blockchain.Default().Pause()
        contract_script = Build(arguments)
        Blockchain.Default().Resume()
        return contract_script