예제 #1
0
 def open_wallet(self, path, pwd):
     try:
         self.Wallet = UserWallet.Open(path, pwd)
         self._walletdb_loop = task.LoopingCall(self.Wallet.ProcessBlocks)
         self._walletdb_loop.start(1)
         print("Wallet %s is opened successfully!" % path)
     except Exception as e:
         print("Could not open wallet: %s" % e)
         sys.exit(1)
예제 #2
0
    def GetWallet1(cls, recreate=False):

        if cls._wallet1 is None or recreate:
            shutil.copyfile(cls.wallet_1_path(), cls.wallet_1_dest())
            cls._wallet1 = UserWallet.Open(
                UserWalletTestCase.wallet_1_dest(),
                to_aes_key(UserWalletTestCase.wallet_1_pass()))

        return cls._wallet1
    def wallet_open(self):
        self.wallet = UserWallet.Open(self.wallet_path, self.wallet_passwd_key)
        # bl: there is some side effect happening here that allows the wallet to be fully/properly initialized.
        # without this, there are errors when sending NEP5 tokens (same goes in prompt.py).
        # don't have time to investigate right now, so doing this as a hack to get things working properly
        self.wallet.ToJson()

        # _walletdb_loop = task.LoopingCall(wallet.ProcessBlocks)
        # _walletdb_loop.start(1)
        self.logger.info("Opened wallet at %s", self.wallet_path)
    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()
        # print("\nOpened wallet. Rebuilding...")
        # time.sleep(10)

        print("\nWait %s min before claiming GAS." % self.min_wait)
        time.sleep(60 * self.min_wait)

        print("\nSending NEO to own wallet...")
        with patch('neo.Prompt.Commands.Send.prompt', side_effect=["coz"]):
            framework = construct_send_basic(self.wallet, ["neo", address, "100000000"])
            tx = process_transaction(self.wallet, contract_tx=framework[0], scripthash_from=framework[1], fee=framework[2], owners=framework[3], user_tx_attributes=framework[4])

        if not tx:
            print("Something went wrong, no tx.")
            return

        # Wait until transaction is on blockchain
        self.wait_for_tx(tx)

        print("Claiming the GAS...")
        claim_tx, relayed = ClaimGas(self.wallet, require_password=False)
        self.wait_for_tx(claim_tx)

        # Finally, need to rebuild the wallet
        self.wallet.Rebuild()

        print("\nAll done!")
        print("- Wallet file: %s" % self.wallet_fn)
        print("- Wallet pwd: %s" % self.wallet_pwd)

        if self.wif_fn:
            with open(self.wif_fn, "w") as f:
                f.write("KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr")

        self.quit()
예제 #5
0
    def test_getwalletheight(self):
        self.app.wallet = UserWallet.Open(
            os.path.join(ROOT_INSTALL_PATH,
                         "neo/data/neo-privnet.sample.wallet"),
            to_aes_key("coz"))

        req = self._gen_rpc_req("getwalletheight", params=[])
        mock_req = mock_request(json.dumps(req).encode("utf-8"))
        res = json.loads(self.app.home(mock_req))

        self.assertEqual(1, res.get('result'))
예제 #6
0
    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 MFF
        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()
        # print("\nOpened wallet. Rebuilding...")
        # time.sleep(10)

        print("\nWait %s min before claiming GAS." % self.min_wait)
        time.sleep(60 * self.min_wait)

        print("\nSending MFF to own wallet...")
        tx = construct_and_send(None,
                                self.wallet, ["neo", address, "100000000"],
                                prompt_password=False)
        if not tx:
            print("Something went wrong, no tx.")
            return

        # Wait until transaction is on blockchain
        self.wait_for_tx(tx)

        print("Claiming the GAS...")
        claim_tx, relayed = ClaimGas(self.wallet, require_password=False)
        self.wait_for_tx(claim_tx)

        # Finally, need to rebuild the wallet
        self.wallet.Rebuild()

        print("\nAll done!")
        print("- Wallet file: %s" % self.wallet_fn)
        print("- Wallet pwd: %s" % self.wallet_pwd)

        if self.wif_fn:
            with open(self.wif_fn, "w") as f:
                f.write("KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr")

        self.quit()
예제 #7
0
    def open_wallet(self, path, password):

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

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

            self._walletdb_loop = task.LoopingCall(self.Wallet.ProcessBlocks)
            self._walletdb_loop.start(1)
            print("Opened wallet at %s" % path)
        except Exception as e:
            print("Could not open wallet: %s" % e)
    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)

        # 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)

        print("\nWait %s min before claiming GAS." % self.min_wait)
        time.sleep(60 * self.min_wait)

        self.wallet.Rebuild()
        print("\nRebuilding wallet...")
        time.sleep(20)

        print("\nSending NEO to own wallet...")
        address = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y"
        with patch('neo.Prompt.Commands.Send.prompt', side_effect=["coz"]):
            framework = construct_send_basic(self.wallet,
                                             ["neo", address, "100000000"])
            tx = process_transaction(self.wallet,
                                     contract_tx=framework[0],
                                     scripthash_from=framework[1],
                                     fee=framework[2],
                                     owners=framework[3],
                                     user_tx_attributes=framework[4])

        if not tx:
            print("Something went wrong, no tx.")
            return

        # Wait until transaction is on blockchain
        self.wait_for_tx(tx)

        print("Claiming the GAS...")
        claim_tx, relayed = ClaimGas(self.wallet, require_password=False)
        self.wait_for_tx(claim_tx)

        # Finally, need to rebuild the wallet
        # self.wallet.Rebuild()
        self.quit()
예제 #9
0
파일: prompt.py 프로젝트: geek96/neo-python
    def do_open_wallet(self):
        passwd = self._gathered_passwords[0]
        path = self._wallet_create_path
        self._wallet_create_path = None
        self._gathered_passwords = None
        self._gather_password_action = None

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

            dbloop = task.LoopingCall(self.Wallet.ProcessBlocks)
            dbloop.start(1)
            print("Opened wallet at %s" % path)
        except Exception as e:
            print("could not open wallet: %s " % e)
예제 #10
0
    def __init__(self, contract_hash, wallet_file_path, wallet_password):
        logger.info("Initializes a BContract Instance")
        self.contract_hash = contract_hash
        self.wallet_file_path = wallet_file_path
        self.wallet_password = wallet_password
        if not os.path.exists(self.wallet_file_path):
            logger.error("Wallet file not found.")
            raise RuntimeError('Wallet File Not found')
        password_key = to_aes_key(self.wallet_password)

        try:
            self.Wallet = UserWallet.Open(self.wallet_file_path, password_key)
            logger.info("Opened wallet at %s" % self.wallet_file_path)
        except Exception as e:
            logger.error("Could not open wallet: %s" % e)
            raise RuntimeError("Could not open wallet: %s" % e)
def wallethandler():
    try:
        global walletinfo
        global _walletdb_loop
        _walletdb_loop = None
        walletinfo = PromptInterface()
        wallet_path = '/home/ubuntu/nosforallneeds'
        passwd = 'nosforallneeds'
        password_key = to_aes_key(passwd)
        walletinfo.Wallet = UserWallet.Open(wallet_path, password_key)
        _walletdb_loop = task.LoopingCall(walletinfo.Wallet.ProcessBlocks)
        _walletdb_loop.start(1)

    except Exception as e:
        print('Exception opening wallet: %s' % e)
        return 'Exception opening wallet.Please try manual deploying your SC. Also please share issue with me @sharedmocha in Discord App.'
예제 #12
0
def custom_background_code():

    wallet = UserWallet.Open(path, to_aes_key(password))
    # wallet.Rebuild()
    # start_wallet_loop(wallet)
    # print("Opened wallet at %s" % path)

    print(wallet.ToJson()['percent_synced'])
    multisig_addr = make_multisig(targetkey, wallet)
    args = ['GAS', 'AK5q8peiC4QKwuZHWX5Dkqhmar1TAGvZBS', '1']  #testing
    while wallet._current_height != Blockchain.Default().Height:
        print("Wallet %s / Blockchain %s" %
              (str(wallet._current_height), str(Blockchain.Default().Height)))
        sleep(15)
    construct_and_send('', wallet, args)
    print("sent")
예제 #13
0
    def createWallet(self):
        # Creating wallet instance
        self.Wallet = UserWallet.Open(path=self.walletpath,
                                      password=self.walletpass)
        print("AddressVersion: ", self.Wallet.AddressVersion)
        self._walletdb_loop = task.LoopingCall(self.Wallet.ProcessBlocks)
        self._walletdb_loop.start(1)

        self.wallet_sh = self.Wallet.GetStandardAddress()
        self.wallet_addr = Crypto.ToAddress(self.wallet_sh)
        for addr in self.Wallet.ToJson()['public_keys']:
            if addr['Address'] == self.wallet_addr:
                self.wallet_pub = addr['Public Key']

        print('Wallet SH', self.wallet_sh)
        print('Wallet Addr', self.wallet_addr)
        print('Wallet Pub', self.wallet_pub)
예제 #14
0
    def __init__(self):

        wallet_path = os.environ.get('FAUCET_WALLET_PATH', '')
        passwd = os.environ.get('FAUCET_WALLET_PASSWORD', '')

        if len(passwd) < 1 or len(wallet_path) < 1:
            raise Exception(
                "Please set FAUCET_WALLET_PASSWORD and FAUCET_WALLET_PATH in your ENV vars"
            )

        self.wallet = UserWallet.Open(path=wallet_path, password=passwd)

        dbloop = task.LoopingCall(self.wallet.ProcessBlocks)
        dbloop.start(.1)

        self.wallet.Rebuild()
        print("created wallet: %s " % self.wallet)
예제 #15
0
    def __init__(self, args=None, chain=None, twist=None):
        self.chain = chain
        self.twist = twist
        self.start_height = self.chain.Height
        self.start_dt = datetime.datetime.utcnow()

        self.args = args
        self.scPath = args[0]

        password = to_aes_key("coz")
        self.wallet = UserWallet.Open("/neo-python/neo-privnet.wallet",
                                      password)
        self.wallet.Rebuild()

        loop = task.LoopingCall(self.wallet.ProcessBlocks)
        self.deferred = loop.start(1)
        self.deferred.addErrback(self.on_loopError)
예제 #16
0
    def __init__(self):

        self._build_run_db()

        wallet_path = os.environ.get('FAUCET_WALLET_PATH','')
        passwd = os.environ.get('FAUCET_WALLET_PASSWORD', '')
        passwd = to_aes_key(passwd)

        if len(passwd) < 1 or len(wallet_path) < 1:
            raise Exception("Please set FAUCET_WALLET_PASSWORD and FAUCET_WALLET_PATH in your ENV vars")

        self.wallet = UserWallet.Open(path=wallet_path, password=passwd)

        dbloop = task.LoopingCall(self.wallet.ProcessBlocks) # huh?
        dbloop.start(.1) # huh?

        self.wallet.Rebuild() # make sure the wallet is up to date
        self.wallet._current_height = 100000 # why set the wallet at that height?
        print("created wallet: %s " % self.wallet) 
예제 #17
0
    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)

        # 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)

        print("\nWait %s min before claiming GAS." % self.min_wait)
        time.sleep(60 * self.min_wait)

        self.wallet.Rebuild()
        print("\nRebuilding wallet...")
        time.sleep(20)

        print("\nSending MFF to own wallet...")
        address = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y"
        tx = construct_and_send(None,
                                self.wallet, ["neo", address, "100000000"],
                                prompt_password=False)
        if not tx:
            print("Something went wrong, no tx.")
            return

        # Wait until transaction is on blockchain
        self.wait_for_tx(tx)

        print("Claiming the GAS...")
        claim_tx, relayed = ClaimGas(self.wallet, require_password=False)
        self.wait_for_tx(claim_tx)

        # Finally, need to rebuild the wallet
        # self.wallet.Rebuild()
        self.quit()
예제 #18
0
    def test_send_to_address_simple(self):
        test_wallet_path = shutil.copyfile(
            WalletFixtureTestCase.wallet_1_path(),
            WalletFixtureTestCase.wallet_1_dest())
        self.app.wallet = UserWallet.Open(
            test_wallet_path,
            to_aes_key(WalletFixtureTestCase.wallet_1_pass()))
        address = 'AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK'

        req = self._gen_rpc_req("sendtoaddress", params=['gas', address, 1])
        mock_req = mock_request(json.dumps(req).encode("utf-8"))
        res = json.loads(self.app.home(mock_req))

        self.assertEqual(res.get('jsonrpc', None), '2.0')
        self.assertIn('txid', res.get('result', {}).keys())
        self.assertIn('vin', res.get('result', {}).keys())

        self.app.wallet.Close()
        self.app.wallet = None
        os.remove(WalletFixtureTestCase.wallet_1_dest())
예제 #19
0
    def test_send_to_address_insufficient_funds(self):
        test_wallet_path = shutil.copyfile(
            WalletFixtureTestCase.wallet_1_path(),
            WalletFixtureTestCase.wallet_1_dest())
        self.app.wallet = UserWallet.Open(
            test_wallet_path,
            to_aes_key(WalletFixtureTestCase.wallet_1_pass()))
        address = 'AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK'

        req = self._gen_rpc_req("sendtoaddress", params=['gas', address, 51])
        mock_req = mock_request(json.dumps(req).encode("utf-8"))
        res = json.loads(self.app.home(mock_req))

        error = res.get('error', {})
        self.assertEqual(error.get('code', None), -300)
        self.assertEqual(error.get('message', None), "Insufficient funds")

        self.app.wallet.Close()
        self.app.wallet = None
        os.remove(WalletFixtureTestCase.wallet_1_dest())
예제 #20
0
    def __init__(self):
        """
        initializes the database by calling the create_tables method; redeclares the contract hash (for redundancy);
        initializes variables that are needed to get the faucet instance running as well as pass data to the smart
        contract; sets up the wallet; checks the height of the blockchain and compares it to the block height of the
        wallet, if they are not equivalent, it processes new blocks until they are

        """
        self._create_tables()
        self.params = []
        self.invoke_args = []
        self.sent_tx = None

        self.token_name = os.environ.get('TOKEN_NAME')
        self.token_symbol = os.environ.get('TOKEN_SYMBOL')
        self.token_script_hash = os.environ.get('TOKEN_SCRIPT_HASH')
        if self.token_name is None or self.token_symbol is None or self.token_script_hash is None:
            raise Exception(
                'Please set TOKEN_NAME, TOKEN_SYMBOL, and TOKEN_SCRIPT_HASH in ./config/nep5-token.json'
            )

        wallet_path = os.environ.get('FAUCET_WALLET_PATH')
        wallet_pwd = to_aes_key(os.environ.get('FAUCET_WALLET_PASSWORD'))
        self.faucet_wallet_addr = os.environ.get('FAUCET_WALLET_ADDRESS')
        if wallet_pwd is None or wallet_path is None or self.faucet_wallet_addr is None:
            raise Exception(
                'Please set FAUCET_WALLET_PATH, FAUCET_WALLET_PASSWORD, and FAUCET_WALLET_ADDRESS '
                'in ./config/environment.json')

        self.wallet = UserWallet.Open(path=wallet_path, password=wallet_pwd)

        dbloop = task.LoopingCall(
            self.wallet.ProcessBlocks)  # specifies what function to call
        dbloop.start(
            .1
        )  # every 0.1 seconds, self.wallet.ProcessBlocks function is called

        self.wallet.Rebuild()
        self.wallet._current_height = 100000  # is this arbitrary or is there a specific reason to set at this height?
        logger.info(f'created wallet: {self.wallet.ToJson()}')
예제 #21
0
    def test_send_to_address_fails_to_sign_tx(self):
        with patch('neo.api.JSONRPC.JsonRpcApi.Wallet.Sign',
                   return_value='False'):
            test_wallet_path = shutil.copyfile(
                WalletFixtureTestCase.wallet_1_path(),
                WalletFixtureTestCase.wallet_1_dest())
            self.app.wallet = UserWallet.Open(
                test_wallet_path,
                to_aes_key(WalletFixtureTestCase.wallet_1_pass()))
            address = 'AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK'

            req = self._gen_rpc_req("sendtoaddress",
                                    params=['gas', address, 1])
            mock_req = mock_request(json.dumps(req).encode("utf-8"))
            res = json.loads(self.app.home(mock_req))

            self.assertEqual(res.get('jsonrpc', None), '2.0')
            self.assertIn('type', res.get('result', {}).keys())
            self.assertIn('hex', res.get('result', {}).keys())

            self.app.wallet.Close()
            self.app.wallet = None
            os.remove(WalletFixtureTestCase.wallet_1_dest())
예제 #22
0
 def test_gettxhistory(self):
     test_wallet_path = shutil.copyfile(
         WalletFixtureTestCase.wallet_1_path(),
         WalletFixtureTestCase.wallet_1_dest()
     )
     self.app.wallet = UserWallet.Open(
         test_wallet_path,
         to_aes_key(WalletFixtureTestCase.wallet_1_pass())
     )
     req = self._gen_rpc_req("gettxhistory")
     mock_req = mock_request(json.dumps(req).encode("utf-8"))
     res = json.loads(self.app.home(mock_req))
     for tx in res['result']:
         self.assertIn('txid', tx.keys())
         self.assertIsNotNone(tx['txid'])
         self.assertIn('block_index', tx.keys())
         self.assertIsNotNone(tx['block_index'])
         self.assertIn('blocktime', tx.keys())
         self.assertIsNotNone(tx['blocktime'])
     self.assertEqual(len(res['result']), 9)
     self.app.wallet.Close()
     self.app.wallet = None
     os.remove(WalletFixtureTestCase.wallet_1_dest())
예제 #23
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 = ""
                if path == "w1.wallet":
                    passwd = 'coz'
                else:
                    passwd = prompt("[Password]> ", is_password=True)

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

                    self._walletdb_loop = task.LoopingCall(self.Wallet.ProcessBlocks)
                    self._walletdb_loop.start(1)
                    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")
예제 #24
0
 def GetWallet1(cls, recreate=False):
     if cls._wallet1 is None or recreate:
         cls._wallet1 = UserWallet.Open(
             LeaderTestCase.wallet_1_dest(),
             to_aes_key(LeaderTestCase.wallet_1_pass()))
     return cls._wallet1
예제 #25
0
class TestContract(BoaFixtureTest):

    dispatched_events = []
    dispatched_logs = []

    now_in_test = 1510235265
    WHITELIST_SALE_RATE = 4666 * 100000000
    WHITELIST_SALE_UPPER_RATE = 5000 * 100000000
    PRESALE_RATE = 4333 * 100000000
    CROWDSALE_WEEK1_RATE = 4000 * 100000000
    CROWDSALE_WEEK2_RATE = 3833 * 100000000
    CROWDSALE_WEEK3_RATE = 3666 * 100000000
    CROWDSALE_WEEK4_RATE = 3500 * 100000000
    WHITELIST_SALE_PERSONAL_CAP = 500 * 100000000  # 500 NEO
    PRESALE_PERSONAL_CAP = 250 * 100000000  # 250 NEO
    CROWDSALE_PERSONAL_CAP = 500 * 100000000  # 500 NEO

    wallet = {
        'ECOSYSTEM_RESERVE_ADDRESS':
        UserWallet.Open('./fixtures/testwallet8.db3', to_aes_key('testwallet'))
    }

    @classmethod
    def tearDownClass(cls):
        super(BoaFixtureTest, cls).tearDownClass()

        try:
            if os.path.exists(settings.DEBUG_STORAGE_PATH):
                shutil.rmtree(settings.DEBUG_STORAGE_PATH)
        except Exception as e:
            print("couldn't remove debug storage %s " % e)

    @classmethod
    def setUpClass(cls):
        super(TestContract, cls).setUpClass()

        cls.dirname = '/'.join(os.path.abspath(__file__).split('/')[:-2])

        def on_notif(evt):
            print(evt)
            cls.dispatched_events.append(evt)
            print("dispatched events %s " % cls.dispatched_events)

        def on_log(evt):
            print(evt)
            cls.dispatched_logs.append(evt)

        events.on(SmartContractEvent.RUNTIME_NOTIFY, on_notif)
        events.on(SmartContractEvent.RUNTIME_LOG, on_log)

    def test_ICOTemplate_1(self):

        output = Compiler.instance().load('%s/ico_template.py' %
                                          TestContract.dirname).default
        out = output.write()

        tx, results, total_ops, engine = TestBuild(out, ['totalSupply', '[]'],
                                                   self.GetWallet1(), '0705',
                                                   '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), TOKEN_TOTAL_SUPPLY)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['WHITELIST_SALE_OPEN', self.now_in_test])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['WHITELIST_SALE_CLOSE', self.now_in_test + 86400])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['WHITELIST_SALE_RATE', self.WHITELIST_SALE_RATE])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(
                ['WHITELIST_SALE_UPPER_RATE', self.WHITELIST_SALE_UPPER_RATE])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param([
                'WHITELIST_SALE_PERSONAL_CAP', self.WHITELIST_SALE_PERSONAL_CAP
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['PRESALE_OPEN', self.now_in_test + 86400 * 2])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['PRESALE_CLOSE', self.now_in_test + 86400 * 3])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(
            out,
            ['set_config',
             parse_param(['PRESALE_RATE', self.PRESALE_RATE])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['PRESALE_PERSONAL_CAP', self.PRESALE_PERSONAL_CAP])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['CROWDSALE_OPEN', self.now_in_test + 86400 * 4])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['CROWDSALE_WEEK1_RATE', self.CROWDSALE_WEEK1_RATE])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['CROWDSALE_WEEK2_RATE', self.CROWDSALE_WEEK2_RATE])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['CROWDSALE_WEEK3_RATE', self.CROWDSALE_WEEK3_RATE])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['CROWDSALE_WEEK4_RATE', self.CROWDSALE_WEEK4_RATE])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(
            out,
            ['get_config', parse_param(['CROWDSALE_WEEK4_RATE'])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), self.CROWDSALE_WEEK4_RATE)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(
                ['CROWDSALE_PERSONAL_CAP', self.CROWDSALE_PERSONAL_CAP])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

    def test_ICOTemplate_2_exchangeable(self):

        output = Compiler.instance().load('%s/ico_template.py' %
                                          TestContract.dirname).default
        out = output.write()

        # before whitelist
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 10 * 100000000,
                self.now_in_test - 1
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

        # check whitelist rate
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 10 * 100000000,
                self.now_in_test
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(),
                         10 * self.WHITELIST_SALE_RATE)

        # check with upper rate
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 450 * 100000000,
                self.now_in_test
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(
            results[0].GetBigInteger(), 400 * self.WHITELIST_SALE_RATE +
            50 * self.WHITELIST_SALE_UPPER_RATE)

        # check presale rate
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 10 * 100000000,
                self.now_in_test + 86400 * 2
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 10 * self.PRESALE_RATE)

        # check crowdsale rate
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 10 * 100000000,
                self.now_in_test + 86400 * 4
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(),
                         10 * self.CROWDSALE_WEEK1_RATE)

        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 10 * 100000000,
                self.now_in_test + 86400 * 4 + 86400 * 7
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(),
                         10 * self.CROWDSALE_WEEK2_RATE)

        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 10 * 100000000,
                self.now_in_test + 86400 * 4 + 86400 * 7 * 2
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(),
                         10 * self.CROWDSALE_WEEK3_RATE)

        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 10 * 100000000,
                self.now_in_test + 86400 * 4 + 86400 * 7 * 3
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(),
                         10 * self.CROWDSALE_WEEK4_RATE)

        # after crowdsale
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 10 * 100000000,
                self.now_in_test + 86400 * 4 + 86400 * 7 * 4 + 1
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

    def test_ICOTemplate_3_personal_cap(self):

        output = Compiler.instance().load('%s/ico_template.py' %
                                          TestContract.dirname).default
        out = output.write()

        # check whitelist cap
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data,
                self.WHITELIST_SALE_PERSONAL_CAP + 1, self.now_in_test
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

        # check presale cap
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, self.PRESALE_PERSONAL_CAP + 1,
                self.now_in_test + 86400 * 2
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

        # check crowdsale cap
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data,
                self.CROWDSALE_PERSONAL_CAP + 1, self.now_in_test + 86400 * 4
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

    def test_ICOTemplate_4_locked_until(self):

        output = Compiler.instance().load('%s/ico_template.py' %
                                          TestContract.dirname).default
        out = output.write()

        tx, results, total_ops, engine = TestBuild(out, [
            'get_locked_until',
            parse_param([bytearray(ECOSYSTEM_RESERVE_ADDRESS)])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(),
                         self.now_in_test + 3 * 30 * 86400)

        # cannot transfer to locked account
        test_transfer_amount = 2400000001
        tx, results, total_ops, engine = TestBuild(out, [
            'transfer',
            parse_param([
                bytearray(TOKEN_OWNER),
                bytearray(ECOSYSTEM_RESERVE_ADDRESS), test_transfer_amount
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), False)

        # cannot transfer from locked account
        tx, results, total_ops, engine = TestBuild(
            out, [
                'transfer',
                parse_param([
                    bytearray(ECOSYSTEM_RESERVE_ADDRESS),
                    bytearray(TOKEN_OWNER), test_transfer_amount
                ])
            ], self.wallet['ECOSYSTEM_RESERVE_ADDRESS'], '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), False)

    def test_ICOTemplate_5_affiliate(self):

        output = Compiler.instance().load('%s/ico_template.py' %
                                          TestContract.dirname).default
        out = output.write()

        #  reconfig to presale
        tx, results, total_ops, engine = TestBuild(
            out, ['set_config',
                  parse_param(['WHITELIST_SALE_OPEN', 0])], self.GetWallet1(),
            '0705', '05')
        tx, results, total_ops, engine = TestBuild(
            out, ['set_config',
                  parse_param(['WHITELIST_SALE_CLOSE', 0])], self.GetWallet1(),
            '0705', '05')
        tx, results, total_ops, engine = TestBuild(
            out,
            ['set_config',
             parse_param(['PRESALE_OPEN', self.now_in_test])],
            self.GetWallet1(), '0705', '05')
        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['PRESALE_CLOSE', self.now_in_test + 86400])
        ], self.GetWallet1(), '0705', '05')

        # set referer
        tx, results, total_ops, engine = TestBuild(out, [
            'set_referrer',
            parse_param([
                self.wallet_3_script_hash.Data,
                bytearray(ADVISOR_FUNDS_ADDRESS)
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        # get referer
        tx, results, total_ops, engine = TestBuild(
            out,
            ['get_referrer',
             parse_param([self.wallet_3_script_hash.Data])], self.GetWallet1(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetByteArray(),
                         bytearray(ADVISOR_FUNDS_ADDRESS))

        # test mint tokens, this should return true
        tx, results, total_ops, engine = TestBuild(
            out, ['mintTokens', '[]', '--attach-neo=10'], self.GetWallet3(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        # balance of address
        tx, results, total_ops, engine = TestBuild(
            out, ['balanceOf',
                  parse_param([self.wallet_3_script_hash.Data])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 10 * self.PRESALE_RATE)

        # sale balance
        tx, results, total_ops, engine = TestBuild(
            out, ['balanceOf',
                  parse_param([bytearray(SALE_FUNDS_ADDRESS)])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(),
                         TOKEN_SALE_AMOUNT - 10 * self.PRESALE_RATE)

        # minted_token
        tx, results, total_ops, engine = TestBuild(
            out, ['get_minted_tokens',
                  parse_param([IS_PRESALE])], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 10 * self.PRESALE_RATE)

        # contributed_neo
        tx, results, total_ops, engine = TestBuild(out, [
            'get_contributed_neo',
            parse_param([IS_PRESALE, self.wallet_3_script_hash.Data])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 10 * 100000000)

        tx, results, total_ops, engine = TestBuild(out, [
            'get_contributed_neo',
            parse_param([IS_CROWDSALE, self.wallet_3_script_hash.Data])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

        # circulation
        tx, results, total_ops, engine = TestBuild(
            out, ['circulation', parse_param([])], self.GetWallet1(), '0705',
            '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), TOKEN_TOTAL_SUPPLY)

        # referer not kyc
        tx, results, total_ops, engine = TestBuild(
            out,
            ['balanceOf',
             parse_param([bytearray(ADVISOR_FUNDS_ADDRESS)])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), TOKEN_ADVISOR_AMOUNT)

        tx, results, total_ops, engine = TestBuild(
            out,
            ['balanceOf',
             parse_param([bytearray(AFFILIATE_FUNDS_ADDRESS)])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), TOKEN_AFFILIATE_AMOUNT)

        # referer kyc registered
        tx, results, total_ops, engine = TestBuild(
            out,
            ['kyc_register',
             parse_param([bytearray(ADVISOR_FUNDS_ADDRESS)])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 1)

        tx, results, total_ops, engine = TestBuild(
            out, ['mintTokens', '[]', '--attach-neo=10'], self.GetWallet3(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(
            out,
            ['balanceOf',
             parse_param([bytearray(ADVISOR_FUNDS_ADDRESS)])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(
            results[0].GetBigInteger(),
            10 * self.PRESALE_RATE * 25 / 1000 + TOKEN_ADVISOR_AMOUNT)

        tx, results, total_ops, engine = TestBuild(
            out,
            ['balanceOf',
             parse_param([bytearray(AFFILIATE_FUNDS_ADDRESS)])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(
            results[0].GetBigInteger(),
            TOKEN_AFFILIATE_AMOUNT - 10 * self.PRESALE_RATE * 25 / 1000)

        # total affiliate
        tx, results, total_ops, engine = TestBuild(
            out,
            ['get_affiliated_tokens', parse_param([])], self.GetWallet1(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(),
                         10 * self.PRESALE_RATE * 25 / 1000)

        #  revert config
        self.test_ICOTemplate_1()

    def test_ICOTemplate_5_sale_and_kyc(self):

        output = Compiler.instance().load('%s/ico_template.py' %
                                          TestContract.dirname).default
        out = output.write()

        # kyc registered in whitelistsale, ok
        tx, results, total_ops, engine = TestBuild(
            out, ['mintTokens', '[]', '--attach-neo=10'], self.GetWallet3(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        # reject kyc
        tx, results, total_ops, engine = TestBuild(
            out, ['kyc_reject',
                  parse_param([self.wallet_3_script_hash.Data])],
            self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 1)

        # kyc rejected, fail
        tx, results, total_ops, engine = TestBuild(
            out, ['mintTokens', '[]', '--attach-neo=10'], self.GetWallet3(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), False)

        #  reconfig to presale
        tx, results, total_ops, engine = TestBuild(
            out, ['set_config',
                  parse_param(['WHITELIST_SALE_OPEN', 0])], self.GetWallet1(),
            '0705', '05')
        tx, results, total_ops, engine = TestBuild(
            out, ['set_config',
                  parse_param(['WHITELIST_SALE_CLOSE', 0])], self.GetWallet1(),
            '0705', '05')
        tx, results, total_ops, engine = TestBuild(
            out,
            ['set_config',
             parse_param(['PRESALE_OPEN', self.now_in_test])],
            self.GetWallet1(), '0705', '05')
        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['PRESALE_CLOSE', self.now_in_test + 86400])
        ], self.GetWallet1(), '0705', '05')

        # kyc rejected, fail
        tx, results, total_ops, engine = TestBuild(
            out, ['mintTokens', '[]', '--attach-neo=10'], self.GetWallet3(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), False)

        #  reconfig to presale
        tx, results, total_ops, engine = TestBuild(
            out, ['set_config', parse_param(['PRESALE_OPEN', 0])],
            self.GetWallet1(), '0705', '05')
        tx, results, total_ops, engine = TestBuild(
            out,
            ['set_config', parse_param(['PRESALE_CLOSE', 0])],
            self.GetWallet1(), '0705', '05')
        tx, results, total_ops, engine = TestBuild(
            out,
            ['set_config',
             parse_param(['CROWDSALE_OPEN', self.now_in_test])],
            self.GetWallet1(), '0705', '05')

        # crowdsale not require kyc, success
        tx, results, total_ops, engine = TestBuild(
            out, ['mintTokens', '[]', '--attach-neo=10'], self.GetWallet3(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        # revert kyc
        tx, results, total_ops, engine = TestBuild(
            out,
            ['kyc_register',
             parse_param([self.wallet_3_script_hash.Data])], self.GetWallet1(),
            '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 1)

        #  revert config
        self.test_ICOTemplate_1()

    def test_ICOTemplate_6_sale_cap(self):

        output = Compiler.instance().load('%s/ico_template.py' %
                                          TestContract.dirname).default
        out = output.write()

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(
                ['WHITELIST_SALE_PERSONAL_CAP', 2 * 70000000 * 100000000])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['PRESALE_PERSONAL_CAP', 2 * 65000000 * 100000000])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        tx, results, total_ops, engine = TestBuild(out, [
            'set_config',
            parse_param(['CROWDSALE_PERSONAL_CAP', 2 * 480000000 * 100000000])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBoolean(), True)

        # check whitelist cap
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 70000000 * 100000000 /
                self.WHITELIST_SALE_RATE * 100000000, self.now_in_test
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

        # # check presale cap
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data, 65000000 * 100000000 /
                self.PRESALE_RATE * 100000000, self.now_in_test + 86400 * 2
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

        # # check crowdsale cap
        tx, results, total_ops, engine = TestBuild(out, [
            'get_exchangeable_amount',
            parse_param([
                self.wallet_3_script_hash.Data,
                480000000 * 100000000 / self.CROWDSALE_WEEK1_RATE * 100000000,
                self.now_in_test + 86400 * 4
            ])
        ], self.GetWallet1(), '0705', '05')
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].GetBigInteger(), 0)

        #  revert config
        self.test_ICOTemplate_1()
    def run(self):
        dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
        dbloop.start(.1)
        Blockchain.Default().PersistBlocks()

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

        print("Creating Wallet...")
        self.wallet = UserWallet.Create(path=self.wallet_fn,
                                        password=self.wallet_pwd)
        self.wallet.ProcessBlocks()

        # Extract infos from wallet
        contract = self.wallet.GetDefaultContract()
        key = self.wallet.GetKey(contract.PublicKeyHash)
        address = key.GetAddress()
        wif = key.Export()
        print("- Address:", address)
        print("- WIF key:", wif)
        self.wallet = None

        # Claim initial NEO
        self.claim_initial_neo(address)

        # Open wallet again
        self.wallet = UserWallet.Open(self.wallet_fn, self.wallet_pwd)
        self._walletdb_loop = task.LoopingCall(self.wallet.ProcessBlocks)
        self._walletdb_loop.start(1)

        print("\nWait %s min before claiming GAS." % self.min_wait)
        time.sleep(60 * self.min_wait)

        print("\nSending NEO to own wallet...")
        tx = construct_and_send(None,
                                self.wallet, ["neo", address, "100000000"],
                                prompt_password=False)
        if not tx:
            print("Something went wrong, no tx.")
            return

        # Wait until transaction is on blockchain
        self.wait_for_tx(tx)

        print("Claiming the GAS...")
        claim_tx, relayed = ClaimGas(self.wallet, require_password=False)
        self.wait_for_tx(claim_tx)

        # Finally, need to rebuild the wallet
        self.wallet.Rebuild()

        print("\nAll done!")
        print("- WIF key: %s" % wif)
        print("- Wallet file: %s" % self.wallet_fn)
        print("- Wallet pwd: %s" % self.wallet_pwd)

        if self.wif_fn:
            with open(self.wif_fn, "w") as f:
                f.write(wif)

        self.quit()
예제 #27
0
class PromptInterface(object):
    go_on = True

    _walletdb_loop = None

    Wallet = None

    _known_things = []

    commands = [
        'quit', 'help', 'block {index/hash} (tx)', 'header {index/hash}',
        'tx {hash}', 'asset {assetId}', 'asset search {query}',
        'contract {contract hash}', 'contract search {query}',
        'notifications {block_number or address}', 'mem', 'nodes', 'state',
        'config debug {on/off}', 'config sc-events {on/off}',
        'build {path/to/file.py} (test {params} {returntype} {needs_storage} {needs_dynamic_invoke} {test_params})',
        'load_run {path/to/file.avm} (test {params} {returntype} {needs_storage} {needs_dynamic_invoke} {test_params})',
        'import wif {wif}', 'import nep2 {nep2_encrypted_key}',
        'import contract {path/to/file.avm} {params} {returntype} {needs_storage} {needs_dynamic_invoke}',
        'import contract_addr {contract_hash} {pubkey}',
        'import watch_addr {address}', 'import token {token_contract_hash}',
        'export wif {address}', 'export nep2 {address}', 'open wallet {path}',
        'create wallet {path}', 'wallet {verbose}', 'wallet claim',
        'wallet migrate', 'wallet rebuild {start block}',
        'wallet delete_addr {addr}', 'wallet alias {addr} {title}',
        'wallet tkn_send {token symbol} {address_from} {address to} {amount} ',
        'wallet tkn_send_from {token symbol} {address_from} {address to} {amount}',
        'wallet tkn_approve {token symbol} {address_from} {address to} {amount}',
        'wallet tkn_allowance {token symbol} {address_from} {address to}',
        'wallet tkn_mint {token symbol} {mint_to_addr} (--attach-neo={amount}, --attach-gas={amount})',
        'wallet unspent', 'wallet close',
        'withdraw_request {asset_name} {contract_hash} {to_addr} {amount}',
        'withdraw holds # lists all current holds',
        'withdraw completed # lists completed holds eligible for cleanup',
        'withdraw cancel # cancels current holds',
        'witdraw cleanup # cleans up completed holds',
        'withdraw # withdraws the first hold availabe',
        'withdraw all # withdraw all holds available',
        'send {assetId or name} {address} {amount} (--from-addr={addr})',
        'sign {transaction in JSON format}',
        'testinvoke {contract hash} {params} (--attach-neo={amount}, --attach-gas={amount})',
        'debugstorage {on/off/reset}'
    ]

    history = FileHistory(FILENAME_PROMPT_HISTORY)

    token_style = None
    start_height = None
    start_dt = None

    def __init__(self):
        self.input_parser = InputParser()
        self.start_height = Blockchain.Default().Height
        self.start_dt = datetime.datetime.utcnow()

        self.token_style = style_from_dict({
            Token.Command:
            preferences.token_style['Command'],
            Token.Neo:
            preferences.token_style['Neo'],
            Token.Default:
            preferences.token_style['Default'],
            Token.Number:
            preferences.token_style['Number'],
        })

    def get_bottom_toolbar(self, cli=None):
        out = []
        try:
            out = [(Token.Command, '[%s] Progress: ' % settings.net_name),
                   (Token.Number, str(Blockchain.Default().Height)),
                   (Token.Neo, '/'),
                   (Token.Number, str(Blockchain.Default().HeaderHeight))]
        except Exception as e:
            pass

        return out

    def get_completer(self):

        standard_completions = [
            'block',
            'tx',
            'header',
            'mem',
            'neo',
            'gas',
            'help',
            'state',
            'nodes',
            'exit',
            'quit',
            'config',
            'import',
            'export',
            'open',
            'wallet',
            'contract',
            'asset',
            'wif',
            'watch_addr',
            'contract_addr',
            'testinvoke',
            'tkn_send',
            'tkn_mint',
            'tkn_send_from',
            'tkn_approve',
            'tkn_allowance',
            'build',
            'notifications',
        ]

        if self.Wallet:
            for addr in self.Wallet.Addresses:
                if addr not in self._known_things:
                    self._known_things.append(addr)
            for alias in self.Wallet.NamedAddr:
                if alias.Title not in self._known_things:
                    self._known_things.append(alias.Title)
            for tkn in self.Wallet.GetTokens().values():
                if tkn.symbol not in self._known_things:
                    self._known_things.append(tkn.symbol)

        all_completions = standard_completions + self._known_things

        completer = WordCompleter(all_completions)

        return completer

    def quit(self):
        print('Shutting down. This may take a bit...')
        self.go_on = False
        self.do_close_wallet()
        reactor.stop()

    def help(self):
        tokens = []
        for c in self.commands:
            tokens.append((Token.Command, "%s\n" % c))
        print_tokens(tokens, self.token_style)

    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:
                    print(path)
                    self.Wallet = UserWallet.Open(path, password_key)

                    self._walletdb_loop = task.LoopingCall(
                        self.Wallet.ProcessBlocks)
                    self._walletdb_loop.start(1)
                    print("Opened wallet at bleeepp blooop %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")

    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._walletdb_loop = task.LoopingCall(
                        self.Wallet.ProcessBlocks)
                    self._walletdb_loop.start(1)

            else:
                print("Please specify a path")

    def do_close_wallet(self):
        if self.Wallet:
            path = self.Wallet._path
            self._walletdb_loop.stop()
            self._walletdb_loop = None
            self.Wallet.Close()
            self.Wallet = None
            print("Closed wallet %s" % path)

    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)

    def do_build(self, arguments):
        BuildAndRun(arguments, self.Wallet)

    def do_load_n_run(self, arguments):
        LoadAndRun(arguments, self.Wallet)

    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)

    def make_withdraw_request(self, arguments):
        if not self.Wallet:
            print("Please open a wallet")
            return
        if len(arguments) == 4:
            RequestWithdrawFrom(self.Wallet, arguments[0], arguments[1],
                                arguments[2], arguments[3])
        else:
            print(
                "Incorrect arg length. Use 'withdraw_request {asset_id} {contract_hash} {to_addr} {amount}'"
            )

    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)

    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)

    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))
                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))

    def do_send(self, arguments):
        construct_and_send(self, self.Wallet, arguments)

    def do_sign(self, arguments):
        jsn = get_arg(arguments)
        parse_and_sign(self, self.Wallet, jsn)

    def show_state(self):
        height = Blockchain.Default().Height
        headers = Blockchain.Default().HeaderHeight

        diff = height - self.start_height
        now = datetime.datetime.utcnow()
        difftime = now - self.start_dt

        mins = difftime / datetime.timedelta(minutes=1)

        bpm = 0
        if diff > 0 and mins > 0:
            bpm = diff / mins

        out = "Progress: %s / %s\n" % (height, headers)
        out += "Block-cache length %s\n" % Blockchain.Default().BlockCacheCount
        out += "Blocks since program start %s\n" % diff
        out += "Time elapsed %s mins\n" % mins
        out += "Blocks per min %s \n" % bpm
        tokens = [(Token.Number, out)]
        print_tokens(tokens, self.token_style)

    def show_nodes(self):
        if len(NodeLeader.Instance().Peers) > 0:
            out = ""
            for peer in NodeLeader.Instance().Peers:
                out += "Peer %s - IO: %s\n" % (peer.Name(), peer.IOStats())
            print_tokens([(Token.Number, out)], self.token_style)
        else:
            print("Not connected yet\n")

    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")

    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")

    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")

    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")

    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")

    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")

    def test_invoke_contract(self, args):
        if not self.Wallet:
            print("Please open a wallet")
            return

        if args and len(args) > 0:
            tx, fee, results, num_ops = TestInvokeContract(self.Wallet, args)

            if tx is not None and results is not None:
                print(
                    "\n-------------------------------------------------------------------------------------------------------------------------------------"
                )
                print("Test invoke successful")
                print("Total operations: %s" % num_ops)
                print("Results %s" % [str(item) for item in results])
                print("Invoke TX GAS cost: %s" % (tx.Gas.value / Fixed8.D))
                print("Invoke TX fee: %s" % (fee.value / Fixed8.D))
                print(
                    "-------------------------------------------------------------------------------------------------------------------------------------\n"
                )
                print(
                    "Enter your password to continue and invoke on the network\n"
                )

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

                result = InvokeContract(self.Wallet, tx, fee)

                return
            else:
                print("Error testing contract invoke")
                return

        print("Please specify a contract to invoke")

    def load_smart_contract(self, args):
        if not self.Wallet:
            print("Please open a wallet")
            return

        function_code = LoadContract(args[1:])

        if function_code:

            contract_script = GatherContractDetails(function_code, self)

            if contract_script is not None:

                tx, fee, results, num_ops = test_invoke(
                    contract_script, self.Wallet, [])

                if tx is not None and results is not None:
                    print(
                        "\n-------------------------------------------------------------------------------------------------------------------------------------"
                    )
                    print("Test deploy invoke successful")
                    print("Total operations executed: %s" % num_ops)
                    print("Results %s " % [str(item) for item in results])
                    print("Deploy Invoke TX GAS cost: %s" %
                          (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX fee: %s" % (fee.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------------------------------------------------------------------------------\n"
                    )
                    print(
                        "Enter your password to continue and deploy this contract"
                    )

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

                    result = InvokeContract(self.Wallet, tx, Fixed8.Zero())

                    return
                else:
                    print("Test invoke failed")
                    print("TX is %s, results are %s" % (tx, results))
                    return

    def show_mem(self):
        process = psutil.Process(os.getpid())
        total = process.memory_info().rss
        totalmb = total / (1024 * 1024)
        out = "Total: %s MB\n" % totalmb
        out += "Total buffers: %s\n" % StreamManager.TotalBuffers()
        print_tokens([(Token.Number, out)], self.token_style)

    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")

    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")

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off' or 'config debug on|off'",
                what)

    def run(self):
        dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
        dbloop.start(.1)

        Blockchain.Default().PersistBlocks()

        tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '),
                  (Token.Command, '\'help\' '),
                  (Token.Default, 'to get started')]

        print_tokens(tokens, self.token_style)
        print('\n')

        while self.go_on:

            try:
                result = prompt(
                    "neo> ",
                    completer=self.get_completer(),
                    history=self.history,
                    get_bottom_toolbar_tokens=self.get_bottom_toolbar,
                    style=self.token_style,
                    refresh_interval=3)
            except EOFError:
                # Control-D pressed: quit
                return self.quit()
            except KeyboardInterrupt:
                # Control-C pressed: do nothing
                continue

            try:
                command, arguments = self.input_parser.parse_input(result)

                if command is not None and len(command) > 0:
                    command = command.lower()

                    if command == 'quit' or command == 'exit':
                        self.quit()
                    elif command == 'help':
                        self.help()
                    elif command == 'create':
                        self.do_create(arguments)
                    elif command == 'open':
                        self.do_open(arguments)
                    elif command == 'build':
                        self.do_build(arguments)
                    elif command == 'load_run':
                        self.do_load_n_run(arguments)
                    elif command == 'import':
                        self.do_import(arguments)
                    elif command == 'export':
                        self.do_export(arguments)
                    elif command == 'wallet':
                        self.show_wallet(arguments)
                    elif command == 'send':
                        self.do_send(arguments)
                    elif command == 'sign':
                        self.do_sign(arguments)
                    elif command == 'block':
                        self.show_block(arguments)
                    elif command == 'tx':
                        self.show_tx(arguments)
                    elif command == 'header':
                        self.show_header(arguments)
                    elif command == 'account':
                        self.show_account_state(arguments)
                    elif command == 'asset':
                        self.show_asset_state(arguments)
                    elif command == 'contract':
                        self.show_contract_state(arguments)
                    elif command == 'testinvoke':
                        self.test_invoke_contract(arguments)
                    elif command == 'withdraw_request':
                        self.make_withdraw_request(arguments)
                    elif command == 'withdraw':
                        self.do_withdraw(arguments)
                    elif command == 'notifications':
                        self.do_notifications(arguments)
                    elif command == 'mem':
                        self.show_mem()
                    elif command == 'nodes' or command == 'node':
                        self.show_nodes()
                    elif command == 'state':
                        self.show_state()
                    elif command == 'debugstorage':
                        self.handle_debug_storage(arguments)
                    elif command == 'config':
                        self.configure(arguments)
                    elif command is None:
                        print("Please specify a command")
                    else:
                        print("Command %s not found" % command)

            except Exception as e:

                print("Could not execute command: %s" % e)
                traceback.print_stack()
                traceback.print_exc()

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.

    settings.setup_privnet()

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

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

    # Start the prompt interface
    #cli = PromptInterface()

    # Run things
    #reactor.suggestThreadPoolSize(15)
    #reactor.callInThread(cli.run)
    NodeLeader.Instance().Start()

    while True:
        f = open("com.txt", "r")
        file_input = f.read()
        f.close()
        #test 020707 07 True False 2 key value25
        if (file_input != ""):
            neo_args = file_input.split(';')
            print(neo_args)

            path = "privnet1"
            nargs = [
                '/Users/jacksonroberts/Desktop/TicketChain/test/RegisterPart.py'
            ]
            nargs.extend(neo_args)
            #print(nargs)

            Wallet = UserWallet.Open(path, to_aes_key("123123123123"))
            tx, result, total_ops, engine = BuildAndRun(nargs, Wallet)
            print(str(result))
            f = open("com.txt", "w")
            f.close()
            f = open("out.txt", "w")
            f.write(result)
            f.close()

        time.sleep(1)

    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
예제 #28
0
 def test_privnet_wallet(self):
     """ Simple test if we can open the privnet wallet """
     wallet = UserWallet.Open(
         os.path.join(ROOT_INSTALL_PATH,
                      "neo/data/neo-privnet.sample.wallet"),
         to_aes_key("coz"))
예제 #29
0
    def test_gather_param(self):
        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value='hello') as fake_prompt:
            result, abort = Utils.gather_param(0, ContractParameterType.String)

            self.assertEqual(result, 'hello')

        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value=1) as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.Integer)

            self.assertEqual(result, 1)

        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value='1') as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.Integer)

            self.assertEqual(result, 1)

        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value=1.03) as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.Integer)

            self.assertEqual(result, 1)

        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value="bytearray(b'abc')") as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.ByteArray)

            self.assertEqual(result, bytearray(b'abc'))

        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value="b'abc'") as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.ByteArray)

            self.assertEqual(result, bytearray(b'abc'))

        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value="abc") as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.Boolean)

            self.assertEqual(result, True)

        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value=0) as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.Boolean)

            self.assertEqual(result, False)

        # test ContractParameterType.ByteArray for address input
        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value='AeV59NyZtgj5AMQ7vY6yhr2MRvcfFeLWSb'
                        ) as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.ByteArray)

            self.assertEqual(
                result,
                bytearray(
                    b'\xf9\x1dkp\x85\xdb|Z\xaf\t\xf1\x9e\xee\xc1\xca<\r\xb2\xc6\xec'
                ))

        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value='["a","b","c"]') as fake_prompt:
            result, abort = Utils.gather_param(0, ContractParameterType.Array)

            self.assertEqual(result, ['a', 'b', 'c'])

        with mock.patch(
                'neo.Prompt.Utils.get_input_prompt',
                return_value='["a","b","c", [1, 3, 4], "e"]') as fake_prompt:
            result, abort = Utils.gather_param(0, ContractParameterType.Array)

            self.assertEqual(result, ['a', 'b', 'c', [1, 3, 4], 'e'])

        # test ContractParameterType.Array without a closed list
        with mock.patch(
                'neo.Prompt.Utils.get_input_prompt',
                return_value='["a","b","c", [1, 3, 4], "e"') as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.Array,
                                               do_continue=False)

            self.assertEqual(result, None)
            self.assertEqual(abort, True)

        # test ContractParameterType.Array with no list
        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value="b'abc'") as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.Array,
                                               do_continue=False)

            self.assertRaises(Exception, "Please provide a list")
            self.assertEqual(result, None)
            self.assertEqual(abort, True)

        # test ContractParameterType.PublicKey
        with mock.patch(
                'neo.Prompt.Utils.get_input_prompt',
                return_value=
                "03cbb45da6072c14761c9da545749d9cfd863f860c351066d16df480602a2024c6"
        ) as fake_prompt:
            test_wallet_path = shutil.copyfile(
                WalletFixtureTestCase.wallet_1_path(),
                WalletFixtureTestCase.wallet_1_dest())
            wallet = UserWallet.Open(
                test_wallet_path,
                to_aes_key(WalletFixtureTestCase.wallet_1_pass()))

            addr_scripthash = wallet.GetStandardAddress()

            result, abort = Utils.gather_param(0,
                                               ContractParameterType.PublicKey)

            script = b'21' + result.encode_point(True) + b'ac'
            pk_script_hash = Crypto.ToScriptHash(script)

            self.assertEqual(
                addr_scripthash, pk_script_hash
            )  # verifies the functionality of ContractParameterType.PublicKey

            wallet.Close()
            wallet = None
            os.remove(WalletFixtureTestCase.wallet_1_dest())

        # test ContractParameterType.PublicKey with bad public key
        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value="blah") as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.PublicKey)
            self.assertIsNone(result)
            self.assertTrue(abort)

        # test unknown ContractParameterType
        with mock.patch('neo.Prompt.Utils.get_input_prompt',
                        return_value="9698b1cac6ce9cbe8517e490778525b929e01903"
                        ) as fake_prompt:
            result, abort = Utils.gather_param(0,
                                               ContractParameterType.Hash160,
                                               do_continue=False)

            self.assertRaises(Exception, "Unknown param type Hash160")
            self.assertEqual(result, None)
            self.assertEqual(abort, True)

        # test Exception
        with mock.patch('sys.stdout', new=StringIO()) as mock_print:
            with mock.patch(
                    'neo.Prompt.Utils.get_input_prompt') as fake_prompt:
                fake_prompt.side_effect = [
                    Exception(-32602, "Invalid params"), KeyboardInterrupt
                ]

                result, abort = Utils.gather_param(
                    0, ContractParameterType.String)

                self.assertEqual(result, None)
                self.assertEqual(abort, True)
                self.assertIn("Invalid params", mock_print.getvalue())

        # test KeyboardInterrupt
        with mock.patch('sys.stdout', new=StringIO()) as mock_print:
            with mock.patch(
                    'neo.Prompt.Utils.get_input_prompt') as fake_prompt:
                fake_prompt.side_effect = [KeyboardInterrupt]

                result, abort = Utils.gather_param(
                    0, ContractParameterType.String)

                self.assertEqual(result, None)
                self.assertEqual(abort, True)
                self.assertIn("Input cancelled", mock_print.getvalue())
예제 #30
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'A utility for signing messages.  Example usage: "np-sign mymessage --wallet_file path/to/my/wallet" or use an NEP2 key/passphrase like "np-sign mymessage -n"'
    )
    parser.add_argument('message',
                        type=str,
                        help='The message in string format to be signed')
    parser.add_argument(
        '-w',
        '--wallet_file',
        type=str,
        default=None,
        help='If using a wallet file, the path to the wallet file')
    parser.add_argument(
        '-a',
        '--address',
        type=str,
        default=False,
        help=
        'If using a wallet file with more than 1 address, the address you would like to use.  Otherwise the default address will be used'
    )
    parser.add_argument(
        '-n',
        '--nep2',
        action='store_true',
        help="Whether to use an NEP2 passhrase rather than a wallet")
    parser.add_argument('--wif',
                        type=str,
                        default=None,
                        help='If using a wif pass in the wif')
    args = parser.parse_args()
    try:

        if args.wallet_file:

            passwd = prompt('[Wallet password]> ', is_password=True)
            wallet = UserWallet.Open(args.wallet_file, to_aes_key(passwd))

            contract = wallet.GetDefaultContract()
            if args.address:
                addr = args.address
                script_hash = Helper.AddrStrToScriptHash(addr)
                contract = wallet.GetContract(script_hash)

                if contract is None:
                    raise Exception('Address %s not found in wallet %s ' %
                                    (addr, args.wallet_file))

            print("Signing With Address %s " % contract.Address)
            signature, pubkey = wallet.SignMessage(args.message,
                                                   contract.ScriptHash)

            pubkey = pubkey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

        elif args.nep2:

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

            prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd)
            keypair = KeyPair(priv_key=prikey)
            contract = Contract.CreateSignatureContract(keypair.PublicKey)
            print("Signing With Address %s " % contract.Address)
            signature = Crypto.Sign(args.message, prikey)

            pubkey = keypair.PublicKey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

        elif args.wif:
            prikey = KeyPair.PrivateKeyFromWIF(args.wif)
            keypair = KeyPair(priv_key=prikey)
            contract = Contract.CreateSignatureContract(keypair.PublicKey)
            print("Signing With Address %s " % contract.Address)
            signature = Crypto.Sign(args.message, prikey)

            pubkey = keypair.PublicKey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

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