Exemple #1
0
from neo.Prompt.Commands.Send import construct_and_send, parse_and_sign
from neo.Prompt.Commands.Tokens import token_approve_allowance, token_get_allowance, token_send, token_send_from, token_mint, token_crowdsale_register
from neo.Prompt.Commands.Wallet import DeleteAddress, ImportWatchAddr, ImportToken, ClaimGas, DeleteToken, AddAlias
from neo.Prompt.Utils import get_arg
from neo.Settings import settings, DIR_PROJECT_ROOT
from neo.UserPreferences import preferences
from neocore.KeyPair import KeyPair
from neocore.UInt256 import UInt256

import codecs

# Logfile settings & setup
LOGFILE_FN = os.path.join(DIR_PROJECT_ROOT, 'prompt.log')
LOGFILE_MAX_BYTES = 5e7  # 50 MB
LOGFILE_BACKUP_COUNT = 3  # 3 logfiles history
settings.set_logfile(LOGFILE_FN, LOGFILE_MAX_BYTES, LOGFILE_BACKUP_COUNT)

# Prompt history filename
FILENAME_PROMPT_HISTORY = os.path.join(DIR_PROJECT_ROOT, '.prompt.py.history')


class PromptInterface(object):

    mycommands = []

    go_on = True

    _walletdb_loop = None

    Wallet = None
from neo.contrib.smartcontract import SmartContract
from neo.SmartContract.ContractParameter import ContractParameter, ContractParameterType

# Set the hash of your contract here:
SMART_CONTRACT_HASH = "6537b4bd100e514119e3a7ab49d520d20ef2c2a4"

# Default REST API port is 8080, and can be overwritten with an env var:
API_PORT = os.getenv("NEO_REST_API_PORT", 8080)

# If you want to enable logging to a file, set the filename here:
LOGFILE = os.getenv("NEO_REST_LOGFILE", None)

# Internal: if LOGFILE is set, file logging will be setup with max
# 10 MB per file and 3 rotations:
if LOGFILE:
    settings.set_logfile(LOGFILE, max_bytes=1e7, backup_count=3)

# Internal: get the API token from an environment variable
API_AUTH_TOKEN = os.getenv("NEO_REST_API_TOKEN", None)
if not API_AUTH_TOKEN:
    raise Exception("No NEO_REST_API_TOKEN environment variable found!")

# Internal: setup the smart contract instance
smart_contract = SmartContract(SMART_CONTRACT_HASH)

# Internal: setup the klein instance
app = Klein()

# Internal: generate the @authenticated decorator with valid tokens
authenticated = gen_authenticated_decorator(API_AUTH_TOKEN)
Exemple #3
0
from neo.Prompt.Commands.Invoke import InvokeContract, TestInvokeContract
from neo.Settings import settings
from neo.Wallets.utils import to_aes_key
from neo.VM.OpCode import *
from neocore.BigInteger import BigInteger
from neocore.Fixed8 import Fixed8

# local packages
from db_models import FaucetRequest, IPRequest

# logfile settings & setup
LOGFILE_FILENAME = './logs/faucet.log'
LOGFILE_MAX_BYTES = 10000000  # 1e7 or 10 MB
LOGFILE_BACKUP_COUNT = 3  # 3 logfiles history
settings.set_logfile(fn=LOGFILE_FILENAME,
                     max_bytes=LOGFILE_MAX_BYTES,
                     backup_count=LOGFILE_BACKUP_COUNT)

# extra logfile settings & setup
logger_request = setup_logger(name='logger_request',
                              logfile='./logs/request.log',
                              level=logging.INFO,
                              maxBytes=LOGFILE_MAX_BYTES,
                              backupCount=LOGFILE_BACKUP_COUNT)


class ItemStore(object):
    """ Houses pretty much everything pertaining to the actual faucet """
    Wallet = None
    app = Klein()
Exemple #4
0
from neo.Prompt.Commands.Tokens import token_approve_allowance, token_get_allowance, token_send, token_send_from, \
    token_mint, token_crowdsale_register
from neo.Prompt.Commands.Wallet import DeleteAddress, ImportWatchAddr, ImportToken, ClaimGas, DeleteToken, AddAlias, \
    ShowUnspentCoins
from neo.Prompt.Utils import get_arg, get_from_addr
from neo.Prompt.InputParser import InputParser
from neo.Settings import settings, PrivnetConnectionError, PATH_USER_DATA
from neo.UserPreferences import preferences
from neocore.KeyPair import KeyPair
from neocore.UInt256 import UInt256

# Logfile settings & setup
LOGFILE_FN = os.path.join(PATH_USER_DATA, 'prompt.log')
LOGFILE_MAX_BYTES = 5e7  # 50 MB
LOGFILE_BACKUP_COUNT = 3  # 3 logfiles history
settings.set_logfile(LOGFILE_FN, LOGFILE_MAX_BYTES, LOGFILE_BACKUP_COUNT)

# Prompt history filename
FILENAME_PROMPT_HISTORY = os.path.join(PATH_USER_DATA, '.prompt.py.history')


class PromptFileHistory(FileHistory):
    def append(self, string):
        string = self.redact_command(string)
        if len(string) == 0:
            return
        self.strings.append(string)

        # Save to file.
        with open(self.filename, 'ab') as f:
            def write(t):
Exemple #5
0
def main():
    parser = argparse.ArgumentParser()

    # Network group
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-m",
                       "--mainnet",
                       action="store_true",
                       default=False,
                       help="Use MainNet instead of the default TestNet")
    group.add_argument(
        "-p",
        "--privnet",
        nargs="?",
        metavar="host",
        const=True,
        default=False,
        help=
        "Use a private net instead of the default TestNet, optionally using a custom host (default: 127.0.0.1)"
    )
    group.add_argument(
        "--coznet",
        action="store_true",
        default=False,
        help="Use the CoZ network instead of the default TestNet")
    group.add_argument("-c",
                       "--config",
                       action="store",
                       help="Use a specific config file")

    # Theme
    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'"
    )

    # Verbose
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        default=False,
                        help="Show smart-contract events by default")

    # Where to store stuff
    parser.add_argument("--datadir",
                        action="store",
                        help="Absolute path to use for database directories")

    # peers
    parser.add_argument("--maxpeers",
                        action="store",
                        default=5,
                        help="Max peers to use for P2P Joining")

    # Show the neo-python version
    parser.add_argument(
        "--version",
        action="version",
        version="neo-python v{version}".format(version=__version__))

    args = parser.parse_args()

    # Setting the datadir must come before setting the network, else the wrong path is checked at net setup.
    if args.datadir:
        settings.set_data_dir(args.datadir)

    # 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:
        try:
            settings.setup_privnet(args.privnet)
        except PrivnetConnectionError as e:
            logger.error(str(e))
            return
    elif args.coznet:
        settings.setup_coznet()

    # Logfile settings & setup
    logfile_fn = os.path.join(settings.DATA_DIR_PATH, 'prompt.log')
    logfile_max_bytes = 5e7  # 50 MB
    logfile_backup_count = 3  # 3 logfiles history
    settings.set_logfile(logfile_fn, logfile_max_bytes, logfile_backup_count)

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

    if args.verbose:
        settings.set_log_smart_contract_events(True)

    if args.maxpeers:
        settings.set_max_peers(args.maxpeers)

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

    # Try to set up a notification db
    if NotificationDB.instance():
        NotificationDB.instance().start()

    # Start the prompt interface
    fn_prompt_history = os.path.join(settings.DATA_DIR_PATH,
                                     '.prompt.py.history')
    cli = PromptInterface(fn_prompt_history)

    # Run things

    reactor.callInThread(cli.run)

    NodeLeader.Instance().Start()

    # reactor.run() is blocking, until `quit()` is called which stops the reactor.
    reactor.run()

    # After the reactor is stopped, gracefully shutdown the database.
    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
from neo.Network.api.decorators import json_response, gen_authenticated_decorator, catch_exceptions
from neo.contrib.smartcontract import SmartContract

# Set the hash of your contract here:
SMART_CONTRACT_HASH = "6537b4bd100e514119e3a7ab49d520d20ef2c2a4"

# Default REST API port is 8080, and can be overwritten with an env var:
API_PORT = os.getenv("NEO_REST_API_PORT", 8080)

# If you want to enable logging to a file, set the filename here:
LOGFILE = os.getenv("NEO_REST_LOGFILE", None)

# Internal: if LOGFILE is set, file logging will be setup with max
# 10 MB per file and 3 rotations:
if LOGFILE:
    settings.set_logfile(LOGFILE, max_bytes=1e7, backup_count=3)

# Internal: get the API token from an environment variable
API_AUTH_TOKEN = os.getenv("NEO_REST_API_TOKEN", None)
if not API_AUTH_TOKEN:
    raise Exception("No NEO_REST_API_TOKEN environment variable found!")

# Internal: setup the smart contract instance
smart_contract = SmartContract(SMART_CONTRACT_HASH)

# Internal: setup the klein instance
app = Klein()

# Internal: generate the @authenticated decorator with valid tokens
authenticated = gen_authenticated_decorator(API_AUTH_TOKEN)
Exemple #7
0
class FaucetRequest(Model):
    """
    @param Model: some default model object
    """
    address = CharField()
    last = DateField()

class IPRequest(Model): 
    """
    @param Model: some default model object 
    """
    client = CharField(max_length=1024)
    last = DateField()

settings.set_logfile("logfile.log", max_bytes=1e7, backup_count=3)


class ItemStore(object):
    """
    @param object: some default object # why passing this object though?
    """
    app = Klein()  # initializing Klein instance

    wallet = None  # initializing wallet

    BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # getting the directory of the current file's location

    j2_env = Environment(loader=FileSystemLoader(BASE_DIR),
                         trim_blocks=True) # setting up the jinja2 environment for templates
Exemple #8
0
def main():
    parser = argparse.ArgumentParser()

    # Network group
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-m",
                       "--mainnet",
                       action="store_true",
                       default=False,
                       help="Use MainNet instead of the default TestNet")
    group.add_argument(
        "-p",
        "--privnet",
        nargs="?",
        metavar="host",
        const=True,
        default=False,
        help=
        "Use a private net instead of the default TestNet, optionally using a custom host (default: 127.0.0.1)"
    )
    group.add_argument(
        "--coznet",
        action="store_true",
        default=False,
        help="Use the CoZ network instead of the default TestNet")
    group.add_argument(
        "-u",
        "--unittest",
        nargs="?",
        metavar="host",
        const=True,
        default=False,
        help=
        "Use a private net instead of the default TestNet, optionally using a custom host (default: 127.0.0.1)"
    )
    group.add_argument("-c",
                       "--config",
                       action="store",
                       help="Use a specific config file")

    # Theme
    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'"
    )

    # Verbose
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        default=False,
                        help="Show smart-contract events by default")

    # Where to store stuff
    parser.add_argument("--datadir",
                        action="store",
                        help="Absolute path to use for database directories")

    # peers
    parser.add_argument("--minpeers",
                        action="store",
                        type=int,
                        choices=range(1, 10 + 1),
                        metavar="[1-10]",
                        help="Min peers to use for P2P Joining")

    parser.add_argument("--maxpeers",
                        action="store",
                        type=int,
                        default=5,
                        choices=range(1, 10 + 1),
                        metavar="[1-10]",
                        help="Max peers to use for P2P Joining")

    # Show the neo-python version
    parser.add_argument(
        "--version",
        action="version",
        version="neo-python v{version}".format(version=__version__))

    args = parser.parse_args()

    # Setting the datadir must come before setting the network, else the wrong path is checked at net setup.
    if args.datadir:
        settings.set_data_dir(args.datadir)

    # 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:
        try:
            settings.setup_privnet(args.privnet)
        except PrivnetConnectionError as e:
            logger.error(str(e))
            return
    elif args.coznet:
        settings.setup_coznet()
    elif args.unittest:
        settings.setup_unittest_net()

    # Logfile settings & setup
    logfile_fn = os.path.join(settings.DATA_DIR_PATH, 'prompt.log')
    logfile_max_bytes = 5e7  # 50 MB
    logfile_backup_count = 3  # 3 logfiles history
    settings.set_logfile(logfile_fn, logfile_max_bytes, logfile_backup_count)

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

    if args.verbose:
        settings.set_log_smart_contract_events(True)

    def set_min_peers(num_peers) -> bool:
        try:
            settings.set_min_peers(num_peers)
            print("Minpeers set to ", num_peers)
            return True
        except ValueError:
            print("Please supply a positive integer for minpeers")
            return False

    def set_max_peers(num_peers) -> bool:
        try:
            settings.set_max_peers(num_peers)
            print("Maxpeers set to ", num_peers)
            return True
        except ValueError:
            print("Please supply a positive integer for maxpeers")
            return False

    minpeers = args.minpeers
    maxpeers = args.maxpeers

    if minpeers and maxpeers:
        if minpeers > maxpeers:
            print("minpeers setting cannot be bigger than maxpeers setting")
            return
        if not set_min_peers(minpeers) or not set_max_peers(maxpeers):
            return
    elif minpeers:
        if not set_min_peers(minpeers):
            return
        if minpeers > settings.CONNECTED_PEER_MAX:
            if not set_max_peers(minpeers):
                return
    elif maxpeers:
        if not set_max_peers(maxpeers):
            return
        if maxpeers < settings.CONNECTED_PEER_MIN:
            if not set_min_peers(maxpeers):
                return

    loop = asyncio.get_event_loop()
    # put prompt_toolkit on top of asyncio to avoid blocking
    use_asyncio_event_loop()

    # Instantiate the blockchain and subscribe to notifications
    blockchain = Blockchain(
        DBFactory.getBlockchainDB(settings.chain_leveldb_path))
    Blockchain.RegisterBlockchain(blockchain)

    # Try to set up a notification db
    if NotificationDB.instance():
        NotificationDB.instance().start()

    # Start the prompt interface
    fn_prompt_history = os.path.join(settings.DATA_DIR_PATH,
                                     '.prompt.py.history')
    cli = PromptInterface(fn_prompt_history)

    cli_task = loop.create_task(cli.run())
    p2p = NetworkService()
    loop.create_task(p2p.start())

    async def shutdown():
        all_tasks = asyncio.all_tasks()
        for task in all_tasks:
            task.cancel()
            with suppress(asyncio.CancelledError):
                await task

    # prompt_toolkit hack for not cleaning up see: https://github.com/prompt-toolkit/python-prompt-toolkit/issues/787
    old_attrs = termios.tcgetattr(sys.stdin)

    try:
        loop.run_forever()
    except SystemExit:
        pass
    finally:
        with suppress(asyncio.InvalidStateError):
            app = prompt_toolkit_get_app()
            if app.is_running:
                app.exit()
        with suppress((SystemExit, Exception)):
            cli_task.exception()
        loop.run_until_complete(p2p.shutdown())
        loop.run_until_complete(shutdown())
        loop.run_until_complete(loop.shutdown_asyncgens())
        loop.stop()
        loop.close()

    # Run things

    # After the reactor is stopped, gracefully shutdown the database.
    NotificationDB.close()
    Blockchain.Default().Dispose()

    # clean up prompt_toolkit mess, see above
    termios.tcsetattr(sys.stdin, termios.TCSANOW, old_attrs)