Example #1
0
class XP_RPC():
    def __init__(self):
        self.connection = AuthServiceProxy(
            settings.RPC_URL % (settings.rpc_user, settings.rpc_password))
        self.tax = 1.0

    def get_address(self, name):
        # commands = [["getaddressesbyaccount", name]]
        address = self.connection.getaddressesbyaccount(name)
        if address:
            address = address[0]
        else:
            address = self.connection.getaccountaddress(name)
        return address

    def show_balance(self, name):
        address = self.connection.getaddressesbyaccount(name)
        if address:
            balance = self.connection.getbalance(name)
        else:
            address = self.connection.getaccountaddress(name)
            balance = self.connection.getbalance(name)
        print(balance)
        return balance

    def move_balance(self, name, to_name, amount):
        address = self.connection.getaddressesbyaccount(name)
        to_address = self.connection.getaddressesbyaccount(to_name)
        if address and to_address:
            # req = self.connection.move(name, to_name, amount)
            req = self.connection.move(name, to_name, amount)
        elif address:
            self.connection.getaccountaddress(to_name)
            req = self.connection.move(name, to_name, amount)
        else:
            req = "Error"
        return req

    def send_from(self, name, address, amount):
        txid = self.connection.sendfrom(name, address, amount)
        tx = self.connection.gettransaction(txid)
        if tx:
            fee = tx["fee"]
        else:
            fee = 0
        self.move_balance(name, "taxpot", float(fee) + self.tax)
        return txid

    def validateaddress(self, address):
        return self.connection.validateaddress(address)['isvalid']
Example #2
0
def main():
    bitcoin = AuthServiceProxy("http://{}:{}@127.0.0.1:{}".format(
        RPCUSER, RPCPASSWORD, RPCPORT))
    address = ADDRESS
    if address is None:
        address = bitcoin.getaddressesbyaccount("")[0]
        print("Using wallet address: ", address)
    parent_txid = "NULL"
    subprotocols = [None, gen_media, gen_pastebin, gen_randomdata]

    # Create nodes...
    for i in range(NUM_NODES_TO_CREATE):
        node = create_node(address, parent_txid)

        # Add subprotocols to node
        for _ in range(5):
            subprotocol = secrets.choice(subprotocols)
            if subprotocol is not None:
                node['subprotocols'].append(subprotocol())

        # Create OP_RETURN data
        data = b'meta' + encode_function(ENCODING)(node)
        assert (len(data) < 100000)  # sanity check for op_return max limit
        data_hex = data.hex()

        # bitcoin rpc commands to create and fund tx with metanet data in OP_RETURN
        rawtx = bitcoin.createrawtransaction([], {'data': data_hex})
        result = bitcoin.fundrawtransaction(rawtx, {'changeAddress': address})
        rawtx = result['hex']
        result = bitcoin.signrawtransaction(rawtx)
        assert (result['complete'])
        signedtx = result['hex']
        txid = bitcoin.sendrawtransaction(signedtx)

        # Prepare for next iteration
        parent_txid = txid
        print("[Node {}]: https://test.whatsonchain.com/tx/{}".format(i, txid))
Example #3
0
class BTCRPCCall(object):
    def __init__(self, wallet="receive", currency="btc"):
        yml_config_reader = ConfigFileReader()
        url = yml_config_reader.get_rpc_server(currency=currency,
                                               wallet=wallet)

        self.access = AuthServiceProxy(url)

    def do_getinfo(self):
        return self.access.getinfo()

    def do_get_new_address(self):
        return self.access.getnewaddress()

    def do_set_account(self, address, account):
        return self.access.setaccount(address, account)

    def do_get_transaction(self, txid):
        try:
            return self.access.gettransaction(txid)
        except RuntimeError:
            # return simplejson.dumps ({u'error' : u'txid is not valid'})
            return None

    def do_list_transactions(self, account, count=10, from_index=0):
        try:
            return self.access.listtransactions(account, count, from_index)
        except RuntimeError:
            print "calling failure"

        def do_get_transaction(self, tx_id):
            try:
                return self.access.gettransaction(tx_id)
            except RuntimeError:
                #return simplejson.dumps ({u'error' : u'txid is not valid'})
                return None

    def amount_received_by_address(self, address="", confirms=0):
        return self.access.getreceivedbyaddress(address, confirms)

    def do_validate_address(self, address=""):
        return self.access.validateaddress(address)

    def list_transactions(self, account="", count=10, from_index=0):
        return self.access.listtransactions(account, count, from_index)

    def send_from(self, from_account="", to_address="", amount=0, minconf=1):
        return self.access.sendfrom(from_account, to_address, amount, minconf)

    def get_received_amount_by_account(self, account="", minconf=1):
        return self.access.getreceivedbyaccount(account, minconf)

    def get_balance(self, account="", minconf=1):
        return self.access.getbalance(account, minconf)

    def get_wallet_balance(self):
        return self.access.getbalance()

    def move(self, from_account="", to_account="", amount=0, minconf=1):
        return self.access.move(from_account, to_account, amount, minconf)

    def list_accounts(self, confirmations=1):
        return self.access.listaccounts(confirmations)

    def list_received_by_address(self, confirmations=1, include_empty=False):
        return self.access.listreceivedbyaddress(confirmations, include_empty)

    def get_addresses_by_account(self, account):
        return self.access.getaddressesbyaccount(account)

    def set_tx_fee(self, amount):
        return self.access.settxfee(amount)

    def send_to_address(self, address, amount, subtractfeefromamount=True):
        return self.access.sendtoaddress(address, amount, "", "",
                                         subtractfeefromamount)

    # amount is type of dictionary
    def send_many(self, from_account="", minconf=1, **amounts):
        log.info("From account: %s", from_account)
        log.info("To accounts: %s", json.dumps(amounts))
        amounts_string = json.dumps(amounts['amounts'])
        amounts_object = json.loads(amounts_string)
        try:
            return True, self.access.sendmany(from_account, amounts_object,
                                              minconf)
        except JSONRPCException as ex:
            return False, ex
        except socket.error as e:
            return False, e
Example #4
0
class BtcWallet():
    """btc钱包"""
    BTC_BLOCK_API = 'https://blockchain.info/'

    def __init__(self, app=None, consul_client=None):
        if app and consul_client:
            self.init_consul(app, consul_client)

    def init_consul(self, app, consul_client):
        try:
            rpc_user = app.config.get('CONFIG_BITCOIND_RPC_USER')
            rpc_pwd = app.config.get('CONFIG_BITCOIND_RPC_PASSWORD')
            wallet_passphrase = app.config.get('CONFIG_BITCOIND_WALLET_PASSWORD')
            self.ipport = consul_client.getRandomOneAvailableServiceIpPort(ConsulServiceName.BTC_CLI)
            # s = "http://%s:%s@" % (self.user, self.pwd) + self.ipport
            # print(s)

            self.bitcoin_cli = AuthServiceProxy(
                "http://%s:%s@" % (rpc_user, rpc_pwd) + self.ipport, timeout=10)
            print("Succeed to connect to the BTC node")

        except Exception as e:
            print(str(e))
            print("Failed to connect to the BTC node")

    # 是否连接BTC节点
    def is_connected(self):
        try:
            if self.bitcoin_cli.getwalletinfo().get('walletversion'):
                return True
            return False
        except Exception as e:
            print(str(e))
            print("Failed to connect to the BTC node")

    # 节点是否同步
    def is_sync(self):
        ret = self.bitcoin_cli.getblockchaininfo()
        if ret.get('blocks') != ret.get("headers"):
            return False
        else:
            return True

    # btc地址是否有效
    def is_valid_address(self, coin_address):
        if coin_address is None or coin_address == '':
            return False
        else:
            ret = self.bitcoin_cli.validateaddress(coin_address).get('isvalid')
            print('账户检查结果:', ret)
            return ret

            # return self.bitcoin_cli.validateaddress(coin_address).get('isvalid')

    # 获取账户余额, 默认经过6个区块确认
    def get_balance(self, coin_address):

        transaction_lists = self.bitcoin_cli.listunspent(1, 99999999, [coin_address])
        print(transaction_lists)
        current_amount = 0
        for transaction_list in transaction_lists:
            amount = transaction_list.get('amount')
            amount = float(amount)
            current_amount += amount
        return current_amount

    def get_balance_by_account(self, account):
        try:
            ret = self.bitcoin_cli.getbalance(account)
            return ret
        except Exception as e:
            logging.error('get balance error:{}'.format(str(e)))
            return None


    def estimate_fee(self):
        try:
            fee = self.bitcoin_cli.estimatefee(6)
            return fee
        except Exception as e:
            logging.error('get fee error:{}'.format(str(e)))
            return None

    def create_account(self, stellar_account):
        # private = random_key()
        # address = pubtoaddr(privtopub(private))
        # print(address, private)
        # return address, private
        address = self.bitcoin_cli.getnewaddress(stellar_account)
        private_key = self.bitcoin_cli.dumpprivkey(address)
        return address, private_key

    def get_block_num(self):
        """获取最新区块数"""
        try:
            block_num = self.bitcoin_cli.getblockcount()
            return block_num
        except Exception as e:
            logging.error('Get btc node block number error:{}'.format(str(e)))
            return None


    def get_chain_info(self):
        ret = self.bitcoin_cli.getblockchaininfo()
        return ret

    def get_block_info(self, block_num):
        """获取区块的详细信息"""
        param = "block-height/{}?format=json".format(block_num)
        api_url = self.BTC_BLOCK_API + param
        # print(api_url)

        blocks = requests.get(api_url, timeout=500).json()
        # print(type(blocks))
        return blocks

    # 链外转帐,普通交易
    def payment(self, btc_base_account, address_to, amount):
        try:
            txid = self.bitcoin_cli.sendfrom(btc_base_account, address_to, amount)
            return True, txid
        except Exception as e:
            logging.error('btc payment error:{}'.format(str(e)))
            return False, str(e)

    def hash_get_detail(self, tx_id):
        """
        Arguments:
        1. "txid" (string, required) The transaction id
        """
        # 根据txid获取确认链外交易信息
        ret = self.bitcoin_cli.gettransaction(tx_id)
        abandoned = ret.get("details")[0].get("abandoned")  # 获取abandon信息
        confirmation_num = ret.get('confirmations')  # 获取确认数

        # 如果确认数小于1,则未确认
        if confirmation_num < 1:
            msg = dict(confirm=str(ret))
            # msg = ret.get("details")[0]
            return False, False, msg, None
        # 如果确认数大于1,则确认
        else:
            msg = dict(confirm=str(ret))
            # msg = ret
            fee = abs(ret.get("fee"))
            if abandoned:
                return True, False, msg, None
            else:
                return True, True, msg, fee

    def raw_payment(self, address_from, address_to, collect_amount):
        inputs = []
        # 获取地址余额信息
        try:
            unspend_lists = self.bitcoin_cli.listunspent(1, 9999999, [address_from])
            for unspend_list in unspend_lists:
                # if unspend_list.get('amount') <= 0:
                #     continue
                # else:
                txid = unspend_list.get('txid')
                vout = unspend_list.get('vout')
                inputs.append({'txid': txid, 'vout': vout})

            outputs = {address_to: round(collect_amount, 8)}

            # 交易建立和签名时不用连接比特币网络,只有在执行交易时才需要将交易发送到网络
            # 创建裸交易
            transaction_hash = self.bitcoin_cli.createrawtransaction(inputs, outputs)

            # 使用私钥签名,获取16进制信息
            hex = self.bitcoin_cli.signrawtransaction(transaction_hash).get('hex')

            # 广播到p2p网络,返回交易哈希
            trading_hash = self.bitcoin_cli.sendrawtransaction(hex, False)

            return True, trading_hash, ''
        except Exception as e:
            print(e)
            return None, None, ''

    def btc_transaction_record(self, block_num):
        # 获取某一区块信息
        block_info = self.get_block_info(block_num)
        blocks = block_info.get('blocks')
        txs = blocks[0].get('tx')
        records = []
        for tx in txs:
            outs = tx.get('out')
            hash = tx.get('hash')
            inputs = tx.get('inputs')
            p_out = inputs[0].get('prev_out')
            if not p_out:
                continue
            else:
                addr_from = p_out.get('addr')
            for out in outs:
                re = []
                addr_to = out.get('addr')
                value = out.get('value') / (10 ** 8)
                # addr_to与User表中绑定的地址进行对比,如果有,则说明此address_to有冲币记录
                user = User.address_query_user('BTC', addr_to)
                if not user:
                    continue
                else:
                    re.append(addr_from)
                    re.append(addr_to)
                    re.append(value)
                    re.append(hash)
                    records.append(re)
        return records

    def get_accounts(self, addr):
        try:
            ad = self.bitcoin_cli.getaccount(addr)
            return ad
        except Exception as e:
            # logging.error('get btc_account error:{}'.format(str(e)))
            return None

    def get_address_byaccount(self, account):
        re = self.bitcoin_cli.getaddressesbyaccount(account)

        return re

    def test1(self):

        transaction_list = self.bitcoin_cli.listaccounts()
        # transaction_list = self.bitcoin_cli.getwalletinfo()
        print(transaction_list)
Example #5
0
        addr = raw_input("Enter a Bitcoin address: ")
        print access.getaccount(addr)
    except:
        print "\n---An error occurred---\n"

elif cmd == "getaccountaddress":
    try:
        acct = raw_input("Enter an account name: ")
        print access.getaccountaddress(acct)
    except:
        print "\n---An error occurred---\n"

elif cmd == "getaddressesbyaccount":
    try:
        acct = raw_input("Enter an account name: ")
        print access.getaddressesbyaccount(acct)
    except:
        print "\n---An error occurred---\n"

elif cmd == "getbalance":
    try:
        acct = raw_input("Enter an account (optional): ")
        mc = raw_input("Minimum confirmations (optional): ")
        try:
            print access.getbalance(acct, mc)
        except:
            print access.getbalance()
    except:
        print "\n---An error occurred---\n"
elif cmd == "getbestblockhash":
    print access.getbestblockhash()
Example #6
0
class BitcoinClient(object):
    """Bitcoin client class"""

    # Handler for Bitcoin connection
    connection = None

    network_info = None
    blockchain_info = None
    wallet_info = None

    def __init__(self):
        self.user = os.environ["BITCOIN_USER"]
        self.password = os.environ["BITCOIN_PASSWORD"]
        self.host = os.environ["BITCOIN_HOST"]
        self.port = int(os.environ["BITCOIN_PORT"])

        self.connection = AuthServiceProxy(
            "http://%s:%s@%s:%i" %
            (self.user, self.password, self.host, self.port))

    def info(self):
        # Use following links for reference:
        # https://chainquery.com/bitcoin-api/getblockchaininfo
        # https://chainquery.com/bitcoin-api/getnetworkinfo
        # https://chainquery.com/bitcoin-api/getwalletinfo
        self.blockchain_info = self.connection.getblockchaininfo()
        self.network_info = self.connection.getnetworkinfo()
        self.wallet_info = self.connection.getwalletinfo()

        accounts = []
        for acc in self.connection.listaccounts(0):
            if len(acc) > 0:
                accounts.append(acc)

        # new_address = self.new_address()
        # new_address_valid = self.validate_address(new_address)
        # new_address_pk = self.get_private_key(new_address)

        # New address: "miC9oPat2xrtDstticmrw2YM7UUN9A6jcn"
        # New address private key: "cNci511KkyyU8GqMdZVxv1NxMbUMKqjo75PAQNdBFGgzbD7W8gZm"

        # valid_bitcoin_address = '134dV6U7gQ6wCFbfHUz2CMh6Dth72oGpgH'
        # addr = Address(self, valid_bitcoin_address)

        data_hash = {
            "blocks": int(self.blockchain_info["blocks"]),
            "headers": int(self.blockchain_info["headers"]),
            "bestblockhash": self.blockchain_info["bestblockhash"],
            "difficulty": float(self.blockchain_info["difficulty"]),
            "accounts": accounts,
            "account_addresses": self.connection.getaddressesbyaccount(""),
            # "new_address": str(self.new_account('Trololo')),
            # "new_address": new_address,
            # "new_address_valid": new_address_valid,
            # "new_address_pk": new_address_pk,
            # "valid_address_balance": addr.balance(),
        }
        return data_hash

    def balance(self):
        """Overall balance of current wallet

        Returns:
            (int) balance in satoshis

        """
        balance = float(self.connection.getbalance())
        # return balance
        return int(balance * SATOSHI)

    def new_address(self):
        """Generate new address"""
        return self.connection.getnewaddress()

    def get_private_key(self, address):
        """Fetch private key of specific address owned by you.

        Keyword arguments:
        address -- address (public key) to fetch from
        """
        return self.connection.dumpprivkey(address)

    def validate_address(self, address):
        """Check that address is valid on Blockchain.

        Keyword arguments:
        address -- address (public key) to validate
        """
        result = self.connection.validateaddress(address)
        if "isvalid" in result:
            return result["isvalid"]
        return False

    def new_account(self, name):
        """Generate new account and address.

        Keyword arguments:
        name -- name of the account, not stored in the blockchain
        """
        return self.connection.getnewaddress(name)

    def generate_blocks(self, amount):
        """Generate some blocks. Availabe only in Regtest mode.

        Keyword arguments:
        amount -- number of blocks to generate
        """
        return self.connection.generate(amount)

    def lock_wallet(self):
        """Lock current wallet."""
        return self.connection.walletlock()

    def unlock_wallet(self, passphrase=None, seconds=60):
        """Unlock current wallet with a passphase.

        Keyword arguments:
        passphrase -- the passphrase that unlocks the wallet
        seconds -- the number of seconds after which the decryption key will be automatically deleted from memory
        """
        if not passphrase:
            passphrase = os.environ["BITCOIN_WALLET_PASSPHRASE"]
        return self.connection.walletlock(passphrase, seconds)

    def change_wallet_passphrase(self,
                                 old_passphrase=None,
                                 new_passphrase=None):
        """Set passphrase for current wallet.

        Keyword arguments:
        old_passphrase -- old passphrase that unlocks the wallet
        new_passphrase -- new passphrase that unlocks the wallet
        """
        if not old_passphrase:
            old_passphrase = ''
        if not new_passphrase:
            new_passphrase = os.environ["BITCOIN_WALLET_PASSPHRASE"]
        return self.connection.walletpassphrasechange(old_passphrase,
                                                      new_passphrase)

    def send(self, from_addr, to_addr, amount):
        """Send funds from address to address. Returns transaction ID.

        Keyword arguments:
        from_addr -- address (public key) we're sending funds from
        to_addr -- address (public key) we're sending funds to
        amount -- (float) amount of bitcoins to send
        """
        return self.connection.sendfrom(from_addr, to_addr, amount)
Example #7
0
async def on_ready():
    # Randomize start time, do not remove or you will be rate limited!
    sleep_time = random.randint(1, 299)
    print("Sleeping for %s seconds..." % sleep_time)
    await asyncio.sleep(sleep_time)

    headers = {
        'x-api-key': FAT_PANDA_CLUB_API_KEY,
        'content-type': "application/json",
        'user-agent': "panda-stake-node-%s" % CURRENCY_TICKER.lower()
    }

    # On failure check VPS is able to access target node and RPC credentials are correct
    connection = AuthServiceProxy("http://%s:%s@%s:%s" % \
        ( STAKE_NODE_RPC_USERNAME, STAKE_NODE_RPC_PASSWORD, STAKE_NODE_HOST, STAKE_NODE_PORT) , timeout=10)

    # Customize based on individual daemon
    try:
        current_balance = connection.getbalance()
        recent_transactions = connection.listtransactions("*", 100, 0)
        base_address = connection.getaddressesbyaccount("")
        if len(base_address) == 0:
            base_address = connection.getnewaddress("")
        # base_address = connect.getaccountaddress("")
    except Exception as exception:
        print("Could not connect to daemon: %s" % exception)
        await client.close()
        sys.exit(exception)

    # Submit deposits to panda-bot
    print("Submitting %s tx" % len(recent_transactions))
    url = "https://api.fatpanda.club/stake/%s" % CURRENCY_TICKER.lower()
    payload = {
        "op": "stakes",
        "transactions": recent_transactions,
        "timestamp": int(time.time()),
        "balance": float(current_balance),
        "address": base_address[0]
    }
    response = requests.request("POST", url, headers=headers, json=payload)
    if response.status_code == 200:
        print(response.json())
    elif response.status_code == 429:
        await client.close()
        sys.exit(
            "Rate limited! Please decrease your job frequency and wait a while."
        )
    else:
        await client.close()
        sys.exit(response.json()['message'])

    # Process operations from panda-bot
    response = requests.request("GET", url, headers=headers)

    if response.status_code != 200:
        await client.close()
        sys.exit(response.json()['message'])
    elif response.status_code == 429:
        await client.close()
        sys.exit(
            "Rate limited! Please decrease your job frequency and wait a while."
        )
    else:
        response_json = response.json()
        unstakes = response.json()['unstakes']
        panda_audit_channel = client.get_channel(PANDA_AUDIT_CHANNEL)
        project_audit_channel = client.get_channel(
            response.json()['private_audit_channel'])

        for op in unstakes:
            # Make sure audit messages are correct, for both panda and project
            ### DO NOT CHANGE THIS! This is under project accountability
            project_audit_message = await project_audit_channel.fetch_message(
                op['private_audit_id'])
            project_audit_validation = re.match(
                AUDIT_MESSAGE_REGEX, project_audit_message.content.strip())
            panda_audit_message = await panda_audit_channel.fetch_message(
                op['panda_audit_id'])
            panda_audit_validation = re.match(
                AUDIT_MESSAGE_REGEX, panda_audit_message.content.strip())

            if not project_audit_validation:
                unstake_message = "< %s-%s > project audit validation failed!" % (
                    op['currency'], op['reference'])

            elif not project_audit_validation.group(1).lower() == "%s-%s" % (
                    CURRENCY_TICKER.lower(), op['reference'].lower()):
                unstake_message = "< %s-%s > project ticker validation failed!" % (
                    op['currency'], op['reference'])

            elif not isclose(float(project_audit_validation.group(2)),
                             op['amount'] + op['fee'],
                             abs_tol=1e-5):

                unstake_message = "< %s-%s > project amount validation failed!\n%0.4f vs %0.4f + %0.4f" % (
                    op['currency'], op['reference'],
                    float(project_audit_validation.group(2)), op['amount'],
                    op['fee'])

            elif not project_audit_validation.group(
                    3).lower() == op['to_address'].lower():
                unstake_message = "< %s-%s > project address validation failed!" % (
                    op['currency'], op['reference'])

            elif not panda_audit_validation:
                unstake_message = "< %s-%s > panda audit validation failed!" % (
                    op['currency'], op['reference'])

            elif not panda_audit_validation.group(1).lower() == "%s-%s" % (
                    CURRENCY_TICKER.lower(), op['reference'].lower()):
                unstake_message = "< %s-%s > panda ticker validation failed!" % (
                    op['currency'], op['reference'])

            elif not isclose(float(panda_audit_validation.group(2)),
                             op['amount'] + op['fee'],
                             abs_tol=1e-5):
                unstake_message = "< %s-%s > panda amount validation failed!\n%0.4f vs %0.4f + %0.4f" % (
                    op['currency'], op['reference'],
                    float(panda_audit_validation.group(2)), op['amount'],
                    op['fee'])

            elif not panda_audit_validation.group(
                    3).lower() == op['to_address'].lower():
                unstake_message = "< %s-%s > panda address validation failed!" % (
                    op['currency'], op['reference'])

            else:
                ### ALL CHECKS PERFORMED TO ENSURE AUDIT MESSAGES ARE VALID, ELSE TX IS SKIPPED and NOT PROCESSED
                try:
                    txid = connection.sendtoaddress(op['to_address'],
                                                    op['amount'])
                    unstake_message = "< %s-%s > unstake sent: %s" % (
                        op['currency'], op['reference'], txid)
                except Exception as exception:
                    txid = 'failed'
                    unstake_message = "< %s-%s > unstake failed! %s" % (
                        op['currency'], op['reference'], exception)
            try:
                await panda_audit_channel.send(content=unstake_message)
                await project_audit_channel.send(content=unstake_message)
            except Exception as exception:
                print("Could not send unstake audit messages due to: %s" %
                      exception)

            op['txid'] = txid
            response = requests.request("POST", url, headers=headers, json=op)

    await client.close()
Example #8
0
class BTCRPCCall(object):
  def __init__(self, wallet="receive", currency="btc"):
    yml_config_reader = ConfigFileReader()
    url = yml_config_reader.get_rpc_server(currency=currency, wallet=wallet)

    self.access = AuthServiceProxy(url)

  def do_getinfo(self):
    return self.access.getinfo()

  def do_get_new_address(self):
    return self.access.getnewaddress();

  def do_set_account(self, address, account):
    return self.access.setaccount(address, account)

  def do_get_transaction(self, txid):
    try:
      return self.access.gettransaction(txid)
    except RuntimeError:
      # return simplejson.dumps ({u'error' : u'txid is not valid'})
      return None

  def do_list_transactions(self, account, count=10, from_index=0):
    try:
      return self.access.listtransactions(account, count, from_index)
    except RuntimeError:
      print("calling failure")

    def do_get_transaction(self, tx_id):
        try:
            return self.access.gettransaction(tx_id)
        except RuntimeError:
            #return simplejson.dumps ({u'error' : u'txid is not valid'})
            return None

  def amount_received_by_address(self, address="", confirms=0):
    return self.access.getreceivedbyaddress(address, confirms)

  def do_validate_address(self, address=""):
    return self.access.validateaddress(address)

  def list_transactions(self, account="", count=10, from_index=0):
    return self.access.listtransactions(account, count, from_index)

  def send_from(self, from_account="", to_address="", amount=0, minconf=1):
    return self.access.sendfrom(from_account, to_address, amount, minconf)

  def get_received_amount_by_account(self, account="", minconf=1):
    return self.access.getreceivedbyaccount(account, minconf)

  def get_balance(self, account="", minconf=1):
    return self.access.getbalance(account, minconf)

  def get_wallet_balance(self):
    return self.access.getbalance()

  def move(self, from_account="", to_account="", amount=0, minconf=1):
    return self.access.move(from_account, to_account, amount, minconf)

  def list_accounts(self, confirmations=1):
    return self.access.listaccounts(confirmations)

  def list_received_by_address(self, confirmations=1, include_empty=False):
    return self.access.listreceivedbyaddress(confirmations, include_empty)

  def get_addresses_by_account(self, account):
    return self.access.getaddressesbyaccount(account)

  def set_tx_fee(self, amount):
    return self.access.settxfee(amount)

  def send_to_address(self, address, amount, subtractfeefromamount=True):
    return self.access.sendtoaddress(address, amount, "", "", subtractfeefromamount)

  # amount is type of dictionary
  def send_many(self, from_account="", minconf=1, **amounts):
    log.info("From account: %s", from_account)
    log.info("To accounts: %s", json.dumps(amounts))
    amounts_string = json.dumps(amounts['amounts'])
    amounts_object = json.loads(amounts_string)
    try:
      return True, self.access.sendmany(from_account, amounts_object, minconf)
    except JSONRPCException as ex:
      return False, ex
    except socket.error as e:
      return False, e
            "Ignoring unrecognised/invalid address ('{}')!\n".format(account))
        continue
    else:
        logger.info("Account: {}".format(account))

    if account.endswith(inputUser) == False:
        logger.info("Skipping account. Doesn't belong to current user.\n")
        # pprint("{} with balance {}".format(account, walletAccounts[account]));
        continue

    else:
        nodeBalance = walletAccounts[account]
        if nodeBalance > masternodeCollateral:
            unspentList = rpcConnection.listunspent(
                UNSPENT_MIN_CONF, UNSPENT_MAX_CONF,
                rpcConnection.getaddressesbyaccount(account))
            unspentBalance = Decimal(0)
            if len(unspentList) > 0:
                logger.info(
                    "Unspent list contains {} outs (incl. collateral). Calculating balance without collateral..."
                    .format(len(unspentList)))
                # pprint(unspentList);
                for otx in unspentList:
                    if otx['amount'] != masternodeCollateral:
                        logger.info(
                            "Unspent amount available: {} TFC (txid: {}).".
                            format(Decimal(otx['amount']), otx['txid']))
                        unspentBalance += Decimal(otx['amount'])
                        if account != holdingWalletName:
                            allUnspent.append(otx)
Example #10
0
from pprint import pprint
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_user = '******'
rpc_password = '******'
rpc_host = '192.168.1.86:9332'

rpc_connection = AuthServiceProxy("http://{}:{}@{}".format(
    rpc_user, rpc_password, rpc_host))

best_block_hash = rpc_connection.getbestblockhash()

accounts = rpc_connection.listaccounts()
address_with_name = {
    name: rpc_connection.getaddressesbyaccount(name)
    for name in accounts
}

print(accounts)
pprint(address_with_name)

dest_address = raw_input("Please input the address what you want to send ")
currency = raw_input("Please input the number of currency ") or 0

if currency == 0:
    print("Currency couldn't be less or equal 0")
    print("Currency are required more 0")
else:
    rpc_connection.sendtoaddress(dest_address, int(currency))
Example #11
0
    def check_for_stake(self, RPC, log):
        try:
            rpc_connection = AuthServiceProxy("http://%s:%[email protected]:%s"%(RPC['user'], RPC['pw'], RPC['port']))
            # Check integrity of wallet before getting wallet info
            check_wallet = rpc_connection.checkwallet()
        except:
            return "Unable to connect to wallet. Verify that it's running and your RPC settings are correct"

        if 'wallet check passed' not in check_wallet:
            log.info(check_wallet)
            rpc_connection.repairwallet()
            log.info("**Wallet was repaired**")

        try:
            txs = rpc_connection.listunspent(int(RPC['min_conf']), int(RPC['max_conf'])) # Only work with inputs that aren't mature
        except:
            return "Unable to run 'listunspent' over RPC, check that the wallet is still running"
        input_sum = 0
        utxo_size = Decimal(RPC['UTXO_size'])
        input_tx = []
        addresses_to_reuse = []
        for each_tx in txs:
            # Check out each existing transaction for desired size, sum up inputs that aren't
            if each_tx['amount'] != utxo_size:
                input_sum += each_tx['amount']
                input_tx.append({"txid":each_tx['txid'],"vout":each_tx['vout']})
                if 'account' in each_tx and each_tx['account'] == 'stake_script' and each_tx['address'] not in addresses_to_reuse:
                    # reuse input addresses for a new output if they have the label 'stake_script'
                    addresses_to_reuse.append(each_tx['address'])

        if input_sum < utxo_size:
            log.debug("DEBUG: Total coins: {0} is not enough to make a new packet of {1}".format(input_sum, utxo_size))
            return "Total coins: {0} is not enough to make a new packet of {1} :DEBUG".format(input_sum, utxo_size)

        # Reuse or make a new change and stake addresses
        change_address = rpc_connection.getaddressesbyaccount("change")
        if len(change_address) == 0:
            change_address = [rpc_connection.getnewaddress("change")]
        stake_addresses = rpc_connection.getaddressesbyaccount("stake_script")
        for addr in stake_addresses:
            amount = rpc_connection.getreceivedbyaddress(addr)
            if amount == 0 and addr not in addresses_to_reuse:
                # Only reuse addresses with the label stake_script and zero balance for safety
                addresses_to_reuse.append(addr)

        output_addresses = {}
        number_of_splits = int(input_sum / utxo_size)
        if len(addresses_to_reuse) < number_of_splits:
            # Make as many new addresses as needed to split inputs into 'size' outputs
            num_to_make = number_of_splits - len(addresses_to_reuse)
            #if not arg.noconfirm:
                # TODO implement
            #    print("About to make {0} new stake address(es), confirm".format(num_to_make))
            #    get_permission()
            for _ in range(num_to_make):
                addresses_to_reuse.append(rpc_connection.getnewaddress('stake_script'))

        for _ in range(number_of_splits):
            output_addresses[addresses_to_reuse.pop()] = utxo_size

        #print(output_addresses)
        assert(int(input_sum / utxo_size) == len(output_addresses)), "Not enough output addresses for number of UTXO splits!"

        number_of_splits = len(output_addresses)
        numbytes = 181 * len(input_tx) + 34* (number_of_splits+1) + 10
        numKB = math.ceil(numbytes / 1000)
        TX_FEE = Decimal(RPC['transaction_fee']) * numKB
        log.debug("transaction fee is %d : %d bytes, fee multiple is %d"%(TX_FEE, numbytes,numKB))

        change_amount = input_sum - (utxo_size * number_of_splits) - TX_FEE
        output_addresses[change_address[0]] = change_amount
        assert (change_amount > 0), "Change amount cannot be less than zero"
        assert(change_amount + TX_FEE + (utxo_size*number_of_splits) == input_sum), "Coins will be lost if the total output != input"

        log.debug("{0} Inputs {1}".format(len(input_tx),input_tx))
        log.debug("{0} Outputs {1}".format(len(output_addresses), output_addresses))
        log.info("{0} (Input total) = {2} ({1}_UTXO packets) + {3} (change) + {4} (fee)".format(input_sum,number_of_splits,utxo_size*number_of_splits,change_amount, TX_FEE))

        # Generate, sign, and send the raw transaction
        raw_tx = rpc_connection.createrawtransaction(input_tx, output_addresses)
        signed_tx = rpc_connection.signrawtransaction(raw_tx)
        if not signed_tx['complete']:
            log.error("Signing failed of raw tranaction: {0}\nInputs: {1}\nOutputs: {2}".format(raw_tx, input_tx, output_addresses))
            return "Signing of raw transaction did not complete successfully, make sure wallet is functioning properly"

        #if not arg.noconfirm:
        #    print("About to send transaction, confirm")
        #    get_permission()

        log.info("Attempting to send: {0} (Total inputs) = {2} ({1} new UTXO) + {3} (change) + {4} (fee)".format(input_sum,number_of_splits,utxo_size*number_of_splits,change_amount, TX_FEE))
        try:
            sent = rpc_connection.sendrawtransaction(signed_tx['hex'])
        except Exception as e:
            return "Sending transaction failed (Your wallet might need more time to update): {0}".format(str(e))
        log.info("TX successful: transaction ID: {0}".format(sent))
        now = datetime.datetime.now().strftime("%m-%d %H:%M")
        return "{6} TX {5} successful: {0} (Total inputs) = {2} ({1} new UTXO) + {3} (change) + {4} (fee)".format(input_sum,number_of_splits,utxo_size*number_of_splits,change_amount, TX_FEE, sent, now)
Example #12
0
class BTCRPCCall(object):

    def __init__(self, wallet="receive", currency="btc"):
        yml_config_reader = ConfigFileReader()
        url = yml_config_reader.get_rpc_server(currency=currency, wallet=wallet)

        self.access = AuthServiceProxy(url)

    def do_getinfo(self):
        return self.access.getinfo()

    def do_get_new_address(self):
        return self.access.getnewaddress();

    def do_set_account(self, address, account):
        return self.access.setaccount(address, account)

    def do_get_transaction(self, txid):
        try:
            return self.access.gettransaction(txid)
        except RuntimeError:
            #return simplejson.dumps ({u'error' : u'txid is not valid'})
            return None

    def do_list_transactions(self, account, count=10, from_index=0):
        try:
            return self.access.listtransactions(account, count, from_index)
        except RuntimeError:
            print "calling failure"

    def amount_received_by_address(self, address="", confirms=0):
        return self.access.getreceivedbyaddress(address, confirms)

    def do_validate_address(self, address=""):
        return self.access.validateaddress(address)

    def list_transactions(self, account="", count=10, from_index=0):
        return self.access.listtransactions(account, count, from_index)

    def send_from(self, from_account="", to_address="", amount=0, minconf=1):
        return self.access.sendfrom(from_account, to_address, amount, minconf)

    def get_received_amount_by_account(self, account="", minconf=1):
        return self.access.getreceivedbyaccount(account, minconf)

    def get_balance(self, account="", minconf=1):
        return self.access.getbalance(account, minconf)

    def get_wallet_balance(self):
        return self.access.getbalance()

    def move(self, from_account="", to_account="", amount=0, minconf=1):
        return self.access.move(from_account, to_account, amount, minconf)

    def list_accounts(self, confirmations=1):
        return self.access.listaccounts(confirmations)

    def list_received_by_address(self, confirmations=1, include_empty=False):
        return self.access.listreceivedbyaddress(confirmations, include_empty)

    def get_addresses_by_account(self, account):
        return self.access.getaddressesbyaccount(account)
Example #13
0
pubkeymike = "03985457b91195038af91c1c7b09c693e9a141681319b683c46871b2dbf1beb09d"
pubkeymine = "03133255e240ded2cd1d0b8fa5b659fd7713b74f6ea074f4a80e3cb1f0677df061"
multiaddress = "2NC9uL5Qcnt4awdTBi3jB6ADPVdvwP9iR8L"
redeemscript = "522103133255e240ded2cd1d0b8fa5b659fd7713b74f6ea074f4a80e3cb1f0677df0612103985457b91195038af91c1c7b09c693e9a141681319b683c46871b2dbf1beb09d52ae"

random = "mrTRKLaDF86gLdKnacjxkXJdRFS6S8poTY"
txtorandom = "bdad390ea15f1828466266a97d4f219ff2e64111a60cb204b30148b199260bd0"
random2 = "mmQDjcub4ozy7e7ET6Yx75MDcLQHdhofbU"
#print "NEW", bitcoin.getnewaddress("")
#print bitcoin.validateaddress(mine)



print ""
print "Addresses and priv keys in entire wallet"
addresses = bitcoin.getaddressesbyaccount("")
print addresses
for add in addresses:
    if not add[0] == '2':
        print bitcoin.dumpprivkey(add), add



## Create a multi-sig

print ""
print "Multi sig address"
adds = [pubkeymine, pubkeymike]
print "Addresses used", adds
multi = bitcoin.addmultisigaddress(2, adds)
multi = bitcoin.createmultisig(2, adds)
Example #14
0
while True:
    try:
        round += 1

        # check, how many new addresses coinhouse needs
        address_gen_count = ch_api.how_many_addresses_are_needed()
        # generate and get new addresses from bitcoind
        new_addresses = list(btcd.getnewaddress(btc_account_incoming) for n in range(address_gen_count))
        # register addresses in rails for showing them to end users
        for address in new_addresses:
            ch_api.give_new_addresses(address)

        # check incoming addresses for balance (not yet verified). 
        # if there is enough btc on the account
        # we transfer it to verifying. otherwise it is forced to await more btcs
        incoming_addresses = btcd.getaddressesbyaccount(btc_account_incoming)
        for address in incoming_addresses:
            balance = btcd.getreceivedbyaddress(address, 0)
            if balance > 0:
                is_paid_enough = ch_api.register_payment(address, balance)
                if is_paid_enough:
                    btcd.setaccount(address, btc_account_verifying)

        # check btc verifications and clear the transaction if there 
        # are at least 2 verifications
        verifying_addresses = btcd.getaddressesbyaccount(btc_account_verifying)
        for address in verifying_addresses:
            balance = btcd.getreceivedbyaddress(address, 2)
            is_clear = ch_api.try_clearance(address, balance)
            if is_clear:
                btcd.setaccount(address, btc_account_done)