Example #1
0
    def open_rpc(self,
                 port,
                 wallet_name,
                 password=wallet_password,
                 timeout=timeout,
                 tries=5):
        if tries == 0:
            tipper_logger.log(
                f"WARNING: FAILED to open {wallet_name}'s wallet!!")
            return
        self.rpc = RPC(port=port,
                       wallet_name=wallet_name,
                       password=password,
                       load_timeout=timeout)

        if not os.path.isfile("aborted-" + wallet_name
                              ):  # Check if wallet was emergency aborted
            self.wallet = Wallet(
                JSONRPCWallet(port=self.rpc.port,
                              password=self.rpc.password,
                              timeout=self.rpc.load_timeout))
        else:
            tipper_logger.log(
                f"WARNING: {wallet_name} had their RPC aborted!!! Trying {tries} more times"
            )
            os.remove("aborted-" + wallet_name)
            self.open_rpc(port=port,
                          wallet_name=wallet_name,
                          password=password,
                          timeout=timeout,
                          tries=tries - 1)
Example #2
0
def get_wallet():
    argsparser = argparse.ArgumentParser(description="Display wallet contents")
    argsparser.add_argument(
        'wallet_rpc_url',
        nargs='?',
        type=url_data,
        default='127.0.0.1:34568',
        help="Wallet RPC URL [user[:password]@]host[:port]")
    argsparser.add_argument(
        '-v',
        dest='verbosity',
        action='count',
        default=0,
        help="Verbosity (repeat to increase; -v for INFO, -vv for DEBUG")
    argsparser.add_argument('-t',
                            dest='timeout',
                            type=int,
                            default=30,
                            help="Request timeout")
    args = argsparser.parse_args()
    level = logging.WARNING
    if args.verbosity == 1:
        level = logging.INFO
    elif args.verbosity > 1:
        level = logging.DEBUG
    logging.basicConfig(level=level, format="%(asctime)-15s %(message)s")
    return Wallet(JSONRPCWallet(timeout=args.timeout, **args.wallet_rpc_url))
    def on_press_button(self, instance, voter=db.current_voter()):
        candidate = instance.text
        address = db.get_address(candidate)

        try:
            login = "******" + str(
                voter[0]) + "--password" + str(
                    voter[1]) + "--rpc-bind-port 28088 --disable-rpc-login"
            child = pexpect.spawn(login, encoding='utf-8')
        except:
            print("error voting")

        w = Wallet(JSONRPCWallet(port=28088))

        #send 1 vote
        txs = w.transfer(address, Decimal('1.0'))

        #destroy wallet
        wallets = db.current_wallets()
        db = DataBase("./monero/", wallets)

        print("You voted for " + candidate)
        sys.exit()

        return 0
Example #4
0
def create_pay_address(label=None):

    wallet = Wallet(JSONRPCWallet(port=WALLET_RPC_PORT, host=WALLET_RPC_HOST))
    account = wallet.accounts[ORDER_ACCOUNT_INDEX]

    address = account.new_address(label=label)
    return str(address)
Example #5
0
def get_balance(details=False):
    wallet = Wallet(
        JSONRPCWallet(
            host=settings.RPC_WALLET_HOST,
            port=settings.RPC_WALLET_PORT,
            user=settings.RPC_WALLET_USER,
            password=settings.RPC_WALLET_PASSWORD,
            timeout=settings.RPC_WALLET_REQUESTS_TIMEOUT,
        ))
    return wallet.balances()
Example #6
0
def transfer(*destinations: Destination):
    wallet = Wallet(
        JSONRPCWallet(
            host=settings.RPC_WALLET_HOST,
            port=settings.RPC_WALLET_PORT,
            user=settings.RPC_WALLET_USER,
            password=settings.RPC_WALLET_PASSWORD,
            timeout=settings.RPC_WALLET_REQUESTS_TIMEOUT,
        ))
    return wallet.transfer_multiple([dest.to_tuple() for dest in destinations])
Example #7
0
def get_address():
    wallet = Wallet(
        JSONRPCWallet(
            host=settings.RPC_WALLET_HOST,
            port=settings.RPC_WALLET_PORT,
            user=settings.RPC_WALLET_USER,
            password=settings.RPC_WALLET_PASSWORD,
            timeout=settings.RPC_WALLET_REQUESTS_TIMEOUT,
        ))
    return wallet.address()
Example #8
0
 def create_wallet(self):
     """
     Anydex operates on existing wallet with corresponding `wallet-rpc-server`.
     Creates instance of `monero-python` Wallet instance.
     """
     self._logger.info('Connect to wallet-rpc-server on %s at %d', self.host, self.port)
     try:
         self.wallet = monero.wallet.Wallet(JSONRPCWallet(host=self.host, port=self.port))
         self.created = True
         self._logger.info('Connection to wallet-rpc-server established')
         return succeed(None)
     except requests.exceptions.ConnectionError:
         return fail(WalletConnectionError(f'Cannot connect to wallet-rpc-server on {self.host} at {self.port}'))
Example #9
0
class MoneroAdapter(Adapter):
    chain = Blockchain.MONERO
    credentials = database.find_credentials(Blockchain.MONERO)
    wallet = Wallet(
        JSONRPCWallet(protocol='http', host='127.0.0.1', port=28088))
    # wallet = Wallet(JSONRPCWallet(protocol=’http’, host=’127.0.0.1’, port=18088, path=’/json_rpc’, user=”,password=”, timeout=30, verify_ssl_certs=True))
    daemon = Daemon(JSONRPCDaemon(port=28081))
    address = credentials['address']
    key = credentials['key']

    # ---STORE---
    @classmethod
    def create_transaction(cls, text):
        p1 = PaymentID(cls.to_hex(text))
        if p1.is_short():
            sender = cls.wallet.addresses()[0]
            sender = sender.with_payment_id(p1)
            transaction = cls.wallet.transfer(sender,
                                              Decimal('0.000000000001'))
            return transaction

    @classmethod
    def get_transaction_count(cls):
        return len(w.outgoing())

    @staticmethod
    def to_hex(text):
        s = text.encode('utf-8')
        return s.hex()

    @classmethod
    def send_raw_transaction(cls, transaction):
        transaction_hash = daemon.send_transaction(transaction)
        return transaction_hash

    @classmethod
    def sign_transaction(cls, transaction):
        return transaction

    @staticmethod
    def add_transaction_to_database(transaction_hash):
        database.add_transaction(transaction_hash, Blockchain.MONERO)

    # ---RETRIEVE---
    @classmethod
    def get_transaction(cls, transaction_hash):
        for item in cls.wallet.outgoing():
            if transaction_hash in str(item):
                return item
Example #10
0
    def get_wallet(self):
        rpc_server: JSONRPCWallet = JSONRPCWallet(
            protocol=self.rpc_protocol,
            host=self.monero_rpc_config_host,
            port=self.monero_rpc_config_port,
            user=self.monero_rpc_config_user,
            password=self.monero_rpc_config_password,
        )
        try:
            wallet: Wallet = Wallet(rpc_server)
        except Unauthorized:
            raise MoneroPaymentMethodRPCUnauthorized
        except SSLError:
            raise MoneroPaymentMethodRPCSSLError
        except Exception as e:
            _logger.critical("Monero RPC Error", exc_info=True)
            raise e

        return wallet
Example #11
0
    def __init__(self):
        self.host = settings.WALLET_HOST
        self.port = settings.WALLET_PORT
        self.username = settings.WALLET_USER
        self.password = settings.WALLET_PASS

        try:
            self.wallet = Wallet(
                JSONRPCWallet(host=self.host,
                              port=self.port,
                              user=self.username,
                              password=self.password,
                              timeout=5))
            if self.wallet:
                self.connected = True
            else:
                self.connected = False
        except:
            self.connected = False
Example #12
0
def source():
    myConfig = RPCconfig.configure()

    try:
        jsonRPC = JSONRPCWallet(myConfig.get_protocol(), myConfig.get_host(),
                                myConfig.get_port(), myConfig.get_path(),
                                myConfig.get_user(), myConfig.get_password())
    except Exception as inst:
        print(type(inst))
        print(inst.args)
        print(inst)

    try:
        mywallet = Wallet(jsonRPC)
        return mywallet
    except ConnectionError as e:
        myRpc = '{protocol}://{host}:{port}{path}'.format(
            protocol=myConfig.get_protocol(),
            host=myConfig.get_host(),
            port=myConfig.get_port(),
            path=myConfig.get_path())
        print('Trouble connecting to Monero RPC at: ' + myRpc)
        return e
    def setData_MO(self, monero_wallet_address, i, s, threaded=True):
        while (not self.stop_all):
            start = time.time()

            try:
                session = requests_html.HTMLSession()
                page = session.get('https://api.moneroocean.stream/miner/' +
                                   monero_wallet_address + '/stats')
                w = Wallet(JSONRPCWallet(port=28088))
                balance = float(page.json()['amtDue']) / 1000000000000 + float(
                    w.balance())
                self.balance_monero_wallets[i] = balance
                self.names_monero_wallets[i] = "XMR"
                self.values_monero_wallets[i] = self.prices_coinmarketcap[
                    self.names_coinmarketcap.index("XMR")] * balance
            except:
                pass

            if not threaded:
                break
            end = time.time()
            elapsed = (end - start)
            if (elapsed < s):
                time.sleep(s - elapsed)
Example #14
0
from waitress import serve

configparser = configparser.ConfigParser()
configparser.read('config.ini')
rpchost = configparser['RPC']['host']
rpcport = configparser['RPC']['port']

host = configparser['Server']['host']
port = configparser['Server']['port']
authorization = configparser['Server']['authorization']

app = Flask(__name__, instance_relative_config=False)
app.config.from_pyfile("config.py")

try:
    wallet = Wallet(JSONRPCWallet(host=rpchost, port=rpcport))
    print("[+] RPC Connection successful")
except Exception as e:
    print("[-] RPC Connection failed, aborting")
    sys.exit(str(e))


def auth_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        authorization_header = request.headers.get('Authorization')
        if authorization_header and authorization_header == authorization:
            return f(*args, **kwargs)

        abort(401, 'Invalid token')
Example #15
0
    'destinations',
    metavar='address:amount',
    nargs='+',
    type=destpair,
    help="Destination address and amount (one or more pairs)")
args = argsparser.parse_args()
prio = getattr(monero.prio, args.prio.upper())

level = logging.WARNING
if args.verbosity == 1:
    level = logging.INFO
elif args.verbosity > 1:
    level = logging.DEBUG
logging.basicConfig(level=level, format="%(asctime)-15s %(message)s")

w = Wallet(JSONRPCWallet(**args.wallet_rpc_url))
txns = w.accounts[args.account].transfer_multiple(args.destinations,
                                                  priority=prio,
                                                  ringsize=args.ring_size,
                                                  payment_id=args.payment_id,
                                                  relay=args.outdir is None)
for tx in txns:
    print(u"Transaction {hash}:\nfee: {fee:21.12f}\n"
          u"Tx key:     {key}\nSize:       {size} B".format(
              hash=tx.hash, fee=tx.fee, key=tx.key, size=len(tx.blob) >> 1))
    if args.outdir:
        outname = os.path.join(args.outdir, tx.hash + '.tx')
        outfile = open(outname, 'wb')
        outfile.write(tx.blob.encode())
        outfile.close()
        print(u"Transaction saved to {}".format(outname))
    "destinations",
    metavar="address:amount",
    nargs="+",
    type=destpair,
    help="Destination address and amount (one or more pairs)",
)
args = argsparser.parse_args()
prio = getattr(monero.const, "PRIO_{:s}".format(args.prio.upper()))

level = logging.WARNING
if args.verbosity == 1:
    level = logging.INFO
elif args.verbosity > 1:
    level = logging.DEBUG
logging.basicConfig(level=level, format="%(asctime)-15s %(message)s")

w = Wallet(JSONRPCWallet(timeout=args.timeout, **args.wallet_rpc_url))
txns = w.accounts[args.account].transfer_multiple(args.destinations,
                                                  priority=prio,
                                                  relay=args.outdir is None)
for tx in txns:
    print(u"Transaction {hash}:\nfee: {fee:21.12f}\n"
          u"Tx key:     {key}\nSize:       {size} B".format(
              hash=tx.hash, fee=tx.fee, key=tx.key, size=len(tx.blob) >> 1))
    if args.outdir:
        outname = os.path.join(args.outdir, tx.hash + ".tx")
        outfile = open(outname, "wb")
        outfile.write(tx.blob)
        outfile.close()
        print(u"Transaction saved to {}".format(outname))
    def set_transaction_data(self, get_raw_data: bool = False):
        if self.server_config.default is True:
            jsonrpcwallet = JSONRPCWallet()
        else:
            jsonrpcwallet = JSONRPCWallet(
                protocol=self.server_config.protocol,
                host=self.server_config.host,
                port=self.server_config.port,
                path=self.server_config.path,
                user=self.server_config.user,
                password=self.server_config.password,
            )

        try:
            wallet = Wallet(jsonrpcwallet)
        except Exception as e:
            # for some reason connection error isn't being caught
            if e.__class__.__name__ == "ConnectionError":
                raise ConnectionError
            else:
                raise e

        this_payment = None
        if settings.security_level == 0 or settings.security_level == -1:
            # get transaction in mem_pool
            incoming_payment = wallet.incoming(tx_id=self.tx_id,
                                               unconfirmed=True,
                                               confirmed=False)
            # https://github.com/monero-ecosystem/monero-python/issues/65
            if incoming_payment:
                tx_in_mem_pool = True
                this_payment: IncomingPayment = incoming_payment.pop()
            else:
                tx_in_mem_pool = False

            if tx_in_mem_pool is False and settings.security_level == 0:
                # raising, because we weren't able to find anything in the mem_pool
                # and security_level=0, which means that we only care about tx's in the mem_pool
                raise NoTXToProcess(
                    f"PaymentProvider: {self.payment_provider} TXID: {self.tx_id} "
                    "Status: No transaction found in mem_pool. "
                    "Your tx probably was processed and has been added to a block. "
                    "This is fine. "
                    f" Security_Level: {settings.security_level} "
                    "Action: Nothing")

        if settings.security_level >= 1 or (settings.security_level == -1
                                            and this_payment is None):
            incoming_payments = wallet.incoming(tx_id=self.tx_id)
            if incoming_payments == []:
                raise NoTXFound(
                    f"Currency: {self.currency} TXID: {self.tx_id} "
                    "Status: No transaction found. Your tx probably hasn't been added to a block yet. "
                    "This is fine. "
                    f"Another notification will execute. Action: Nothing")
            this_payment: IncomingPayment = incoming_payments[0]
            if settings.security_level > 1:

                if this_payment.transaction.confirmations < settings.security_level:
                    raise NumConfirmationsNotMet(
                        f"Currency: {self.currency} TXID: {self.tx_id} "
                        f"Confirmations: current {this_payment.transaction.confirmations}, "
                        f"expected {settings.security_level}")

        self.amount = this_payment.amount
        self.fee = this_payment.transaction.fee
        self.note = this_payment.note
        self.recipient = this_payment.local_address
        self.timestamp = this_payment.transaction.timestamp
        # if the tx is in the mem_pool confirmations will be null, set it to 0 instead
        self.confirmations = (this_payment.transaction.confirmations
                              if this_payment.transaction.confirmations
                              is not None else 0)

        if get_raw_data is True:
            self._raw_data = jsonrpcwallet.raw_request("get_transfer_by_txid",
                                                       {"txid": self.tx_id})
Example #18
0
 def test_multiple_outputs(self):
     daemon = Daemon(JSONRPCDaemon(host="127.0.0.1", port=38081))
     responses.add(responses.POST,
                   self.wallet_jsonrpc_url,
                   json=self._read(
                       "test_multiple_outputs-wallet-00-get_accounts.json"),
                   status=200)
     responses.add(
         responses.POST,
         self.wallet_jsonrpc_url,
         json=self._read("test_multiple_outputs-wallet-01-query_key.json"),
         status=200)
     responses.add(
         responses.POST,
         self.wallet_jsonrpc_url,
         json=self._read(
             "test_multiple_outputs-wallet-02-addresses-account-0.json"),
         status=200)
     responses.add(
         responses.POST,
         self.wallet_jsonrpc_url,
         json=self._read(
             "test_multiple_outputs-wallet-02-addresses-account-1.json"),
         status=200)
     wallet = Wallet(JSONRPCWallet(host="127.0.0.1", port=38083))
     responses.add(
         responses.POST,
         self.daemon_transactions_url,
         json=self._read(
             "test_multiple_outputs-daemon-00-get_transactions.json"),
         status=200)
     tx = daemon.transactions(
         "f79a10256859058b3961254a35a97a3d4d5d40e080c6275a3f9779acde73ca8d"
     )[0]
     outs = tx.outputs(wallet=wallet)
     self.assertEqual(len(outs), 5)
     self.assertEqual(
         outs[0].stealth_address,
         "d3eb42322566c1d48685ee0d1ad7aed2ba6210291a785ec051d8b13ae797d202")
     self.assertEqual(
         outs[1].stealth_address,
         "5bda44d7953e27b84022399850b59ed87408facdf00bbd1a2d4fda4bf9ebf72f")
     self.assertEqual(
         outs[2].stealth_address,
         "4c79c14d5d78696e72959a28a734ec192059ebabb931040b5a0714c67b507e76")
     self.assertEqual(
         outs[3].stealth_address,
         "64de2b358cdf96d498a9688edafcc0e25c60179e813304747524c876655a8e55")
     self.assertEqual(
         outs[4].stealth_address,
         "966240954892294091a48c599c6db2b028e265c67677ed113d2263a7538f9a43")
     self.assertIsNotNone(outs[0].payment)
     self.assertIsNone(
         outs[1].payment)  # FIXME: isn't that change we should recognize?
     self.assertIsNotNone(outs[2].payment)
     self.assertIsNotNone(outs[3].payment)
     self.assertIsNotNone(outs[4].payment)
     self.assertEqual(outs[0].amount, outs[0].payment.amount)
     self.assertEqual(outs[2].amount, outs[2].payment.amount)
     self.assertEqual(outs[3].amount, outs[3].payment.amount)
     self.assertEqual(outs[4].amount, outs[4].payment.amount)
     self.assertEqual(outs[0].amount, Decimal(4))
     self.assertIsNone(outs[1].amount)
     self.assertEqual(outs[2].amount, Decimal(1))
     self.assertEqual(outs[3].amount, Decimal(2))
     self.assertEqual(outs[4].amount, Decimal(8))
     self.assertEqual(
         outs[0].payment.local_address,
         "76Qt2xMZ3m7b2tagubEgkvG81pwf9P3JYdxR65H2BEv8c79A9pCBTacEFv87tfdcqXRemBsZLFVGHTWbqBpkoBJENBoJJS9"
     )
     self.assertEqual(
         outs[2].payment.local_address,
         "78zGgzb45TEL8uvRFjCayUjHS98RFry1f7P4PE4LU7oeLh42s9AtP8fYXVzWqUW4r3Nz4g3V64w9RSiV7o3zUbPZVs5DVaU"
     )
     self.assertEqual(
         outs[3].payment.local_address,
         "73ndji4W2bu4WED87rJDVALMvUsZLLYstZsigbcGfb5YG9SuNyCSYk7Qbttez2mXciKtWRzRN9aYGJbF9TPBidNQNZppnFw"
     )
     self.assertEqual(
         outs[4].payment.local_address,
         "7BJxHKTa4p5USJ9Z5GY15ZARXL6Qe84qT3FnWkMbSJSoEj9ugGjnpQ1N9H1jqkjsTzLiN5VTbCP8f4MYYVPAcXhr36bHXzP"
     )
     self.assertEqual(
         repr(outs[0]),
         "d3eb42322566c1d48685ee0d1ad7aed2ba6210291a785ec051d8b13ae797d202, 4.000000000000 "
         "to [76Qt2x]")