예제 #1
0
    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()
예제 #2
0
    def do_open(self, arguments):

        if self.Wallet:
            self.do_close_wallet()

        item = get_arg(arguments)

        if item and item == 'wallet':

            path = get_arg(arguments, 1)

            if path:

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

                passwd = 'coz'  #always use this password
                #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")
예제 #3
0
def main():

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

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

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

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

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
예제 #4
0
    def execute(self, arguments):
        if PromptData.Wallet:
            PromptData.close_wallet()

        path = PromptUtils.get_arg(arguments, 0)

        if not path:
            print("Please specify the required parameter")
            return

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

            PromptData.Prompt.start_wallet_loop()
            print("Opened wallet at %s" % path)
            return PromptData.Wallet
        except Exception as e:
            print("Could not open wallet: %s" % e)
예제 #5
0
def start_neo():
    # Use TestNet
    settings.setup_testnet()

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

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

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

    # Run all the things (blocking call)
    reactor.run()
    logger.info("Shutting down.")
예제 #6
0
 def open_wallet(self):
     """ Open a wallet. Needed for invoking contract methods. """
     assert self.wallet is None
     self.wallet = UserWallet.Open(self.wallet_path, self.wallet_pass)
     self.wallet.ProcessBlocks()
     self._walletdb_loop = task.LoopingCall(self.wallet.ProcessBlocks)
     self._walletdb_loop.start(1)
예제 #7
0
    def do_open(self, arguments):
        if self.Wallet:
            self.do_close_wallet()

        item = get_arg(arguments)

        if item and item == 'wallet':

            path = get_arg(arguments, 1)

            if path:

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

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

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

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

            else:
                print("Please specify a path")
        else:
            print("Please specify something to open")
예제 #8
0
    def execute(self, arguments):
        if PromptData.Wallet:
            PromptData.close_wallet()

        path = PromptUtils.get_arg(arguments, 0)

        if not path:
            print("Please specify the required parameter")
            return

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

        try:
            passwd = prompt("[password]> ", is_password=True)
        except KeyboardInterrupt:
            print("Wallet opening cancelled")
            return
        password_key = to_aes_key(passwd)

        try:
            PromptData.Wallet = UserWallet.Open(path, password_key)
            print("Opened wallet at %s" % path)
            asyncio.create_task(
                PromptData.Wallet.sync_wallet(
                    start_block=PromptData.Wallet._current_height))
            return PromptData.Wallet
        except Exception as e:
            print("Could not open wallet: %s" % e)
예제 #9
0
파일: prompt.py 프로젝트: geek96/neo-python
    def do_create_wallet(self):
        #        print("do create wallet with passwords %s "% self._gathered_passwords)
        psswds = self._gathered_passwords
        path = self._wallet_create_path
        self._wallet_create_path = None
        self._gathered_passwords = None
        self._gather_password_action = None

        if len(psswds) != 2 or psswds[0] != psswds[1] or len(psswds[0]) < 10:
            print(
                "please provide matching passwords that are at least 10 characters long"
            )
            return

        passwd = psswds[1]

        try:
            self.Wallet = UserWallet.Create(path=path, password=passwd)
        except Exception as e:
            print("Exception creating wallet: %s " % e)

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

        dbloop = task.LoopingCall(self.Wallet.ProcessBlocks)
        dbloop.start(1)
예제 #10
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
예제 #11
0
파일: main.py 프로젝트: rph8/neopanda
def runRawTransaction(operation, args):
    invocation_tx = InvocationTransaction()

    smartcontract_scripthash = UInt160.ParseString(CONTRACT_HASH)
    sb = ScriptBuilder()
    sb.EmitAppCallWithOperationAndArgs(
        smartcontract_scripthash,
        operation,
        args)
    invocation_tx.Script = binascii.unhexlify(sb.ToArray())

    wallet = UserWallet.Create(
        'neo-privnet.wallet', to_aes_key('coz'), generate_default_key=False)
    private_key = KeyPair.PrivateKeyFromWIF(
        "KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr")

    wallet.CreateKey(private_key)
    context = ContractParametersContext(invocation_tx)
    wallet.Sign(context)

    invocation_tx.scripts = context.GetScripts()
    raw_tx = invocation_tx.ToArray()

    payload = {"jsonrpc": "2.0", "id": 1,
               "method": "sendrawtransaction",
               "params": [raw_tx.decode("ascii")]}

    res = requests.post(
        "http://neo-nodes:30333/testNeoConnection", json=payload)
    print("received POST result")
    print(res.status_code)
    result = res.text
    print(result)
    return result
예제 #12
0
 def open_wallet(self):
     """ Open a wallet. Needed for invoking contract operations. """
     if self.wallet is not None:
         return
     self.wallet = UserWallet.Open(self.wallet_path, self.wallet_pass)
     self._walletdb_loop = task.LoopingCall(self.wallet.ProcessBlocks)
     self._walletdb_loop.start(1)
    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()
예제 #14
0
    def openWallet(self):
        """ open a Wallet. Needed for invoking contract methods """
        if not os.path.exists(self.walletpath):
            logger.info("Wallet file not found")
            return
        else:
            assert self.Wallet is None
            aespasswd = to_aes_key(self.walletpw)
            self.Wallet = UserWallet.Open(self.walletpath, aespasswd)
            print("Opened wallet at: ", self.walletpath)

            self.wallet_sh = self.Wallet.GetStandardAddress()
            self.wallet_addr = Crypto.ToAddress(self.wallet_sh)

            print('Wallet Sh', self.wallet_sh)
            print('Wallet Addr', self.wallet_addr)

            self.Wallet.Rebuild()

            print("Wallet is syncing...")
            while self.Wallet.IsSynced is False:
                self._walletdb_loop = task.LoopingCall(
                    self.Wallet.ProcessBlocks)
                self._walletdb_loop.start(1)
                print(self.Wallet._current_height, "/",
                      Blockchain.Default().Height)

            return len(self.Wallet.GetTransactions())
def create_raw_sc_method_call_tx(
    source_address,
    source_address_wif,
    smartcontract_scripthash,
    smartcontract_method,
    smartcontract_method_args,
):
    source_script_hash = address_to_scripthash(source_address)

    # start by creating a base InvocationTransaction
    # the inputs, outputs and Type do not have to be set anymore.
    invocation_tx = InvocationTransaction()

    # often times smart contract developers use the function ``CheckWitness`` to determine if the transaction is signed by somebody eligible of calling a certain method
    # in order to pass that check you want to add the corresponding script_hash as a transaction attribute (this is generally the script_hash of the public key you use for signing)
    # Note that for public functions like the NEP-5 'getBalance' and alike this would not be needed, but it doesn't hurt either
    invocation_tx.Attributes.append(
        TransactionAttribute(usage=TransactionAttributeUsage.Script,
                             data=source_script_hash))

    smartcontract_scripthash = UInt160.ParseString(smartcontract_scripthash)
    # next we need to build a 'script' that gets executed against the smart contract.
    # this is basically the script that calls the entry point of the contract with the necessary parameters
    sb = ScriptBuilder()

    # call the method on the contract (assumes contract address is a NEP-5 token)
    sb.EmitAppCallWithOperationAndArgs(
        smartcontract_scripthash,
        smartcontract_method,
        smartcontract_method_args,
    )
    invocation_tx.Script = binascii.unhexlify(sb.ToArray())

    # at this point we've build our unsigned transaction and it's time to sign it before we get the raw output that we can send to the network via RPC
    # we need to create a Wallet instance for helping us with signing
    wallet = UserWallet.Create('path',
                               to_aes_key('mypassword'),
                               generate_default_key=False)

    # if you have a WIF use the following
    # this WIF comes from the `neo-test1-w.wallet` fixture wallet
    private_key = KeyPair.PrivateKeyFromWIF(source_address_wif)

    # if you have a NEP2 encrypted key use the following instead
    # private_key = KeyPair.PrivateKeyFromNEP2("NEP2 key string", "password string")

    # we add the key to our wallet
    wallet.CreateKey(private_key)

    # and now we're ready to sign
    context = ContractParametersContext(invocation_tx)
    wallet.Sign(context)

    invocation_tx.scripts = context.GetScripts()
    raw_tx = invocation_tx.ToArray()

    print(raw_tx)

    return raw_tx.decode()
예제 #16
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'))
    def GetWallet3(cls, recreate=False):

        if cls._wallet3 is None or recreate:
            shutil.copyfile(cls.wallet_3_path(), cls.wallet_3_dest())
            cls._wallet3 = UserWallet.Open(cls.wallet_3_dest(),
                                           to_aes_key(cls.wallet_3_pass()))

        return cls._wallet3
예제 #18
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)
예제 #19
0
    def run(self):

        to_addr = self.target_address

        dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
        dbloop.start(.1)

        Blockchain.Default().PersistBlocks()

        wallets = []
        i = 0
        tx_json = ''

        print("Signing new transaction with 3 of 4 node keys...")

        for pkey, wif in nodekeys.items():
            walletpath = "wallet{}.db3".format(i + 1)
            if os.path.exists(walletpath):
                os.remove(walletpath)
            wallet = UserWallet.Create(path=walletpath, password=mypassword)
            wallets.append(wallet)

            print("Importing node private key to to {}".format(walletpath))
            prikey = KeyPair.PrivateKeyFromWIF(wif)
            wallet.CreateKey(prikey)

            print("Importing multi-sig contract to {}".format(walletpath))
            multisig_args = [pkey, '3']
            multisig_args.extend(list(nodekeys.keys()))
            ImportMultiSigContractAddr(wallet, multisig_args)

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

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

            #print("Wallet %s " % json.dumps(wallet.ToJson(), indent=4))

            if i == 0:
                print("Creating spend transaction to {}".format(to_addr))
                tx_json = self.begin_send(
                    wallet, ['neo', to_addr, '100000000', multisig_addr])
                if tx_json is None:
                    break
            else:
                tx_json = self.sign_and_finish(wallet, tx_json)

            if tx_json == 'success':
                print(
                    "Finished, {} should now own all the NEO on the private network."
                    .format(to_addr))
                break
            i += 1

        self.quit()
예제 #20
0
    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)
예제 #21
0
def example2():
    source_address = "AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3"
    source_script_hash = address_to_scripthash(source_address)

    # start by creating a base InvocationTransaction
    # the inputs, outputs and Type do not have to be set anymore.
    invocation_tx = InvocationTransaction()

    # Since we are building a raw transaction, we will add the raw_tx flag

    invocation_tx.raw_tx = True

    # often times smart contract developers use the function ``CheckWitness`` to determine if the transaction is signed by somebody eligible of calling a certain method
    # in order to pass that check you want to add the corresponding script_hash as a transaction attribute (this is generally the script_hash of the public key you use for signing)
    # Note that for public functions like the NEP-5 'getBalance' and alike this would not be needed, but it doesn't hurt either
    invocation_tx.Attributes.append(
        TransactionAttribute(usage=TransactionAttributeUsage.Script,
                             data=source_script_hash))

    # next we need to build a 'script' that gets executed against the smart contract.
    # this is basically the script that calls the entry point of the contract with the necessary parameters
    smartcontract_scripthash = UInt160.ParseString(
        "31730cc9a1844891a3bafd1aa929a4142860d8d3")
    sb = ScriptBuilder()
    # call the NEP-5 `name` method on the contract (assumes contract address is a NEP-5 token)
    sb.EmitAppCallWithOperation(smartcontract_scripthash, 'name')
    invocation_tx.Script = binascii.unhexlify(sb.ToArray())

    # at this point we've build our unsigned transaction and it's time to sign it before we get the raw output that we can send to the network via RPC
    # we need to create a Wallet instance for helping us with signing
    wallet = UserWallet.Create('path',
                               to_aes_key('mypassword'),
                               generate_default_key=False)

    # if you have a WIF use the following
    # this WIF comes from the `neo-test1-w.wallet` fixture wallet
    private_key = KeyPair.PrivateKeyFromWIF(
        "Ky94Rq8rb1z8UzTthYmy1ApbZa9xsKTvQCiuGUZJZbaDJZdkvLRV")

    # if you have a NEP2 encrypted key use the following instead
    # private_key = KeyPair.PrivateKeyFromNEP2("NEP2 key string", "password string")

    # we add the key to our wallet
    wallet.CreateKey(private_key)

    # and now we're ready to sign
    context = ContractParametersContext(invocation_tx)
    wallet.Sign(context)

    invocation_tx.scripts = context.GetScripts()
    raw_tx = invocation_tx.ToArray()

    return raw_tx
예제 #22
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()
예제 #23
0
    def execute(self, arguments):
        path = PromptUtils.get_arg(arguments, 0)

        if not path:
            print("Please specify a path")
            return

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

        if PromptData.Wallet:
            PromptData.close_wallet()

        try:
            passwd1 = prompt("[password]> ", is_password=True)
            passwd2 = prompt("[password again]> ", is_password=True)
        except KeyboardInterrupt:
            print("Wallet creation cancelled")
            return

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

        if PromptData.Wallet:
            asyncio.create_task(
                PromptData.Wallet.sync_wallet(
                    start_block=PromptData.Wallet._current_height))
            return PromptData.Wallet
예제 #24
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 claim_initial_neo(self, target_address):
        wallets = []
        i = 0
        tx_json = None
        dbloops = []

        print("Signing new transaction with 3 of 4 node keys...")
        for pkey, wif in nodekeys.items():
            walletpath = "wallet{}.db3".format(i + 1)
            if os.path.exists(walletpath):
                os.remove(walletpath)
            wallet = UserWallet.Create(path=walletpath,
                                       password=to_aes_key(self.wallet_pwd))
            wallets.append(wallet)

            print("Importing node private key to to {}".format(walletpath))
            prikey = KeyPair.PrivateKeyFromWIF(wif)
            wallet.CreateKey(prikey)

            print("Importing multi-sig contract to {}".format(walletpath))
            keys = list(nodekeys.keys())
            pubkey_script_hash = Crypto.ToScriptHash(pkey, unhex=True)
            verification_contract = Contract.CreateMultiSigContract(
                pubkey_script_hash, 3, keys)
            wallet.AddContract(verification_contract)
            print("Added multi-sig contract address %s to wallet" %
                  verification_contract.Address)

            dbloop = task.LoopingCall(wallet.ProcessBlocks)
            dbloop.start(1)
            dbloops.append(dbloop)

            # print("Wallet %s " % json.dumps(wallet.ToJson(), indent=4))

            if i == 0:
                print(
                    "Creating spend transaction to {}".format(target_address))
                tx_json = self.send_neo(wallet, multisig_addr, target_address,
                                        '100000000')
                if tx_json is None:
                    break
            else:
                tx_json = self.sign_and_finish(wallet, tx_json)

            if tx_json == 'success':
                print(
                    "Finished, {} should now own all the NEO on the private network."
                    .format(target_address))
                break
            i += 1
예제 #26
0
    def Sign(self, NEP2orPrivateKey, NEP2password=None, multisig_args=[]):
        """
        Sign the raw transaction

        Args:
            NEP2orPrivateKey: (str) the NEP2 or PrivateKey string from the address you are sending from. NOTE: Assumes WIF if NEP2password is None.
            NEP2password: (str, optional) the NEP2 password associated with the NEP2 key string. Defaults to None.
            multisig_args: (list, optional) the arguments for importing a multsig address (e.g. [<owner pubkey>, <num required sigs>, [<signing pubkey>, ...]])
        """
        temp_path = "temp_wallet.wallet"
        temp_password = "******"
        wallet = UserWallet.Create(temp_path,
                                   to_aes_key(temp_password),
                                   generate_default_key=False)
        if NEP2password:
            private_key = KeyPair.PrivateKeyFromNEP2(NEP2orWIF, NEP2password)
        else:
            private_key = binascii.unhexlify(NEP2orPrivateKey)
        wallet.CreateKey(private_key)

        if multisig_args:  # import a multisig address
            verification_contract = Contract.CreateMultiSigContract(
                Crypto.ToScriptHash(multisig_args[0], unhex=True),
                multisig_args[1], multisig_args[2])
            wallet.AddContract(verification_contract)

        if self.Type == b'\xd1' and not self.SOURCE_SCRIPTHASH:  # in case of an invocation with no funds transfer
            context = ContractParametersContext(self)
        elif not self._context:  # used during transactions involving a funds transfer
            signer_contract = wallet.GetContract(self.SOURCE_SCRIPTHASH)
            context = ContractParametersContext(
                self, isMultiSig=signer_contract.IsMultiSigContract)
        else:
            context = self._context  # used for a follow-on signature for a multi-sig transaction

        wallet.Sign(context)
        if context.Completed:
            self.scripts = context.GetScripts()
            self.Validate()  # ensure the tx is ready to be relayed
        elif context.ContextItems:
            self._context = context
            print(
                "Transaction initiated, but the signature is incomplete. Sign again with another valid multi-sig keypair."
            )
        else:
            raise SignatureError("Unable to sign transaction.")
        wallet.Close()
        wallet = None
        os.remove(temp_path)
예제 #27
0
    def do_create(self, arguments):
        item = get_arg(arguments)

        if item and item == 'wallet':

            path = get_arg(arguments, 1)

            if path:

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

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

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

                password_key = to_aes_key(passwd1)

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

                if self.Wallet:
                    self._walletdb_loop = task.LoopingCall(
                        self.Wallet.ProcessBlocks)
                    self._walletdb_loop.start(1)

            else:
                print("Please specify a 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)

        # 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()
예제 #29
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)
예제 #30
0
    def test_listaddress_with_wallet(self):
        test_wallet_path = os.path.join(mkdtemp(), "listaddress.db3")
        self.app.wallet = UserWallet.Create(test_wallet_path,
                                            to_aes_key('awesomepassword'))

        req = self._gen_rpc_req("listaddress", params=[])
        mock_req = mock_request(json.dumps(req).encode("utf-8"))
        res = json.loads(self.app.home(mock_req))
        results = res.get('result', [])
        self.assertGreater(len(results), 0)
        self.assertIn(results[0].get('address', None),
                      self.app.wallet.Addresses)
        self.app.wallet.Close()
        self.app.wallet = None
        os.remove(test_wallet_path)