Ejemplo n.º 1
0
    def test_disconnect_peer(self):
        peers = self.client('faucet').list_peers()
        if peers:
            logger.warning('Already connected, lets disconnect')
            for peer in peers:
                logger.debug(f'Disconnecting: {peer}')
                # TODO all active channels with the peer need to be closed first
                try:
                    self.client('faucet').disconnect_from_peer(peer)
                except Exception as e:
                    if str(e.details()).endswith(
                            'all active channels with the peer need to be closed first'
                    ):
                        self.client('faucet').close_peer_channels(peer=peer,
                                                                  force=True)
                        rpc_connection = AuthServiceProxy(self.rpc_host)
                        blocks = rpc_connection.generate(10)
                        # try one more time
                        time.sleep(1)
                        self.test_disconnect_peer()
                        break
                    else:
                        raise AssertionError(e.details())

            self.assertEqual([], self.client('faucet').list_peers())
        else:
            try:
                self.connect_to_peer('faucet', 'alice')
                self.test_disconnect_peer()
            except Exception as e:
                self.fail(e)
        time.sleep(1)
Ejemplo n.º 2
0
    def test_open_channel(self):
        try:
            self.connect_to_peer('faucet', 'alice')
            self.connect_to_peer('faucet', 'bob')
        except Exception as e:
            self.fail(e)

        self.send_btc_to_node('alice', amount=100000000)
        self.send_btc_to_node('bob', amount=100000000)

        # alice and bob opens one wau funded channels with faucet
        generate_blocks = self.open_channel('alice', 'faucet', 100000000)
        generate_blocks = True if self.open_channel(
            'bob', 'faucet', 100000000,
            remote_funding=200000) else generate_blocks

        # generate_blocks = True if self.open_channel('faucet', 'bob', 200000) else generate_blocks

        # if generate_blocks:
        # GENERATE 10 blocks, to confirm channel
        rpc_connection = AuthServiceProxy(self.rpc_host)
        blocks = rpc_connection.generate(10)
        self.assertGreaterEqual(len(blocks), 10)

        time.sleep(1)
        try:
            channels = self.client('alice').list_channels()
            self.assertIsNotNone(channels.channels)
            self.assertTrue(
                self.client('faucet').identity_pubkey in set(
                    ch.remote_pubkey for ch in channels.channels))
        except Exception as e:
            self.fail(e)

        try:
            channels = self.client('bob').list_channels()
            self.assertIsNotNone(channels.channels)
            self.assertTrue(
                self.client('faucet').identity_pubkey in set(
                    ch.remote_pubkey for ch in channels.channels))
        except Exception as e:
            self.fail(e)
Ejemplo n.º 3
0
 def send_btc_to_node(self, node, amount=100000000):
     try:
         balance = self.client(node).wallet_balance()
         logger.info(balance)
         if not balance.get('confirmed_balance') or balance.get(
                 'confirmed_balance') < amount:
             faucet_address = self.client(node).address().address
             #     send bitcoin to faucet_address
             logger.debug(amount / 100000000 -
                          balance.get('confirmed_balance') / 100000000)
             rpc_connection = AuthServiceProxy(self.rpc_host)
             txid = rpc_connection.sendtoaddress(
                 faucet_address,
                 float("{0:.8f}".format(amount / 100000000 -
                                        balance.get('confirmed_balance') /
                                        100000000)))
             blocks = rpc_connection.generate(10)
             self.send_btc_to_node(node)
     except Exception as e:
         self.fail(e)
Ejemplo n.º 4
0
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import ssl

import logging

logging.basicConfig()
logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG)

rpc_connection = AuthServiceProxy("https://%s:%[email protected]:8334" %
                                  ('dev', 'abc123'),
                                  ssl_context=ssl._create_unverified_context())
info = rpc_connection.getinfo()
print(info)

blocks = rpc_connection.generate(400)
print(blocks)

info = rpc_connection.getinfo()
print(info)


def generate_initial_blocks():
    pass
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
def generate_valid_source_tx(
        s: protocol.State,
        con: AuthServiceProxy,
        max_tx: int
    ) -> None:
    # Transmit enough funds to addresses so that we won't need
    # to use coinbase transactions.
    # There are at most MAX many transactions in one step. Hence,
    # we need at most that many different addresses. (We can always
    # use the change addresses because our transactions have nearly
    # no costs)

    num_addr = max_tx // 10  # We want at most 50 advertisements to use the
    # same address
    s.source_tx = []

    start = con.getblockcount() + 1
    con.generate(num_addr + 101)
    top = con.getblockcount()

    interval = range(start, top - 100)
    block_hashes = con.batch_([["getblockhash", h] for h in interval])
    blocks = con.batch_([["getblock", ha, 2] for ha in block_hashes])
    del block_hashes
    txs = [block['tx'][0] for block in blocks]
    del blocks

    sent_txs = []
    i = 0
    value = -1
    txid = -1
    n = -1
    for tx in txs:
        for out in tx['vout']:
            if out['scriptPubKey']['type'] == 'pubkey':
                # The pubkey transactions are coinbase transactions because
                value = out['value']
                txid = tx['txid']
                n = out['n']
        if value == -1 or txid == -1 or n == -1:
            raise RuntimeError("No coinbase transaction found.")
        addr = con.getnewaddress()
        sent_value = float(value) / 2  # create two addresses per transaction
        raw_tx = con.createrawtransaction([{'txid': txid, 'vout': n}], {
            addr: sent_value})  # The - is for the fees
        funded_tx = con.fundrawtransaction(raw_tx)
        signed_tx = con.signrawtransactionwithwallet(funded_tx["hex"])
        if signed_tx["complete"] is False:
            raise RuntimeError(
                "bitcoind could not sign the transaction. (During "
                "Initialization)")
        txid = con.sendrawtransaction(signed_tx["hex"])
        sent_txs.append(txid)

        i += 1

        # Create a block each 100 transactions
        if i == 100:
            con.generate(1)
            i = 0

    con.generate(1)

    txs = con.batch_([['getrawtransaction', txid, 1] for txid in sent_txs])
    for tx in txs:
        for out in tx['vout']:
            vout = out['n']
            s.source_tx.append(opreturn.Transaction(tx['txid'], vout))
    c = 0
    for utxo in s.source_tx:
        if not protocol.is_valid_utxo(utxo):
            c += 1
    print("Found %d invalid utxos." % c)
Ejemplo n.º 7
0
    hash_of_reconstructed_animecoin_zstd_uncompressed_data = get_sha256_hash_of_input_data_func(
        reconstructed_animecoin_zstd_uncompressed_data)
    assert (hash_of_reconstructed_animecoin_zstd_uncompressed_data ==
            reconstructed_uncompressed_data_file_hash)
    print('Successfully reconstructed and decompressed data!')
    return reconstructed_animecoin_zstd_uncompressed_data


if 0:  #Demo:
    if 0:  #Start up bitcoind using the regtest network and generate some coins to use:
        rpc_auth_command_string = '-rpcuser='******' -rpcpassword='******'bitcoind.exe ' + rpc_auth_command_string + ' -regtest -server -addresstype=legacy'  #Without -addresstype=legacy the current bitcoind will default to using segwit addresses, which suck (you can't sign messages with them)
        proc = subprocess.Popen(bitcoind_launch_string, shell=True)
        sleep(5)
        rpc_connection = AuthServiceProxy(rpc_connection_string)
        block_generation_output = rpc_connection.generate(
            101)  #Generate some coins to work with

    path_to_animecoin_html_ticket_file = 'C:\\animecoin\\art_folders_to_encode\\Carlo_Angelo__Felipe_Number_02\\artwork_metadata_ticket__2018_05_27__23_42_33_964953.html'
    with open(path_to_animecoin_html_ticket_file, 'r') as f:
        animecoin_ticket_html_string = f.read()

    use_generate_new_compression_dictionary = 1
    if use_generate_new_compression_dictionary:
        animecoin_zstd_compression_dictionary = generate_zstd_dictionary_from_folder_path_and_file_matching_string_func(
            path_where_animecoin_html_ticket_templates_are_stored,
            '*ticket*.html')
        animecoin_zstd_compression_dictionary_raw_data = animecoin_zstd_compression_dictionary.as_bytes(
        )
        compression_dictionary_hash = get_sha256_hash_of_input_data_func(
            animecoin_zstd_compression_dictionary_raw_data)
        with open(
Ejemplo n.º 8
0
working_dir = my_path + "/../state"  # Path to binary files
# Create bin folder if it does not exist:
try:
    os.mkdir(working_dir)
except FileExistsError:
    pass

# Connect to Deamon
con = AuthServiceProxy("http://%s:%[email protected]:%s" %
                       (State.RPC_USER, State.RPC_PASSWORD, port))

peers = []  # List of peers, each with valid credit
users = []  # List of users, each with valid credit

for i in range(0, NUM_PEERS + 1):
    b = con.generate(1)
    tx = con.getblock(b[0])['tx'][0]
    (pri, pub) = generate_key_pair()
    p = protocol.Peer(ip_address=ipaddress.IPv4Address(get_random_bytes(4)),
                      port=int(random.randint(3000, 4000)),
                      public_key=pub.to_string(),
                      private_key=pri.to_string(),
                      cont_tx=opreturn.Transaction(tx, 0),
                      service=bytes([0x01, 0x00]))
    peers.append(p)

for i in range(0, NUM_USERS + 1):
    b = con.generate(1)
    tx = con.getblock(b[0])['tx'][0]
    users.append({'txs': [opreturn.Transaction(tx, 0)]})
Ejemplo n.º 9
0
        sys.exit()

    # Fix problem with wrong format of IPs
    for p in peers:
        if type(p.ip_address) is str:
            p.ip_address = ipaddress.ip_address(p.ip_address)

    # Define a list of tx to take the money from
    generate_valid_source_tx(s, con, MAX)

    # Determine size of coinbase TXs
    # Re-Connect to Daemon (to avoid overburdening bitcoind)
    con = AuthServiceProxy(
        "http://%s:%[email protected]:%s" %
        (State.RPC_USER, State.RPC_PASSWORD, PORT), )
    con.generate(1)
    bh = con.getblockhash(con.getblockcount())
    json = con.getblock(bh, 2)
    coinbase_sizes = [183]
    coinbase_avg_sizes = [156]
    for tx in json['tx']:
        coinbase_sizes.append(tx['size'])
        coinbase_avg_sizes.append(tx['vsize'])
    print("Coinbase transactions have sizes {} and stripped sizes {}.".format(
        coinbase_sizes, coinbase_avg_sizes))

    filename = get_filename(NUM_PEERS, (MIN, MAX, STEP), REPS)
    file_path = get_size_eval_path() + '/' + filename
    error_count = 0
    with open(file_path, 'w') as fd:
        fd.write("------------------------HEADER------------------------\n")
Ejemplo n.º 10
0
def add_confirmations(confirmations):
    if not confirmations in (1, 2, 3, 4, 5, 6):
        return {'error': 'confirmation value supplied not in interval from 1 through 6'}
    bitcoind=AuthServiceProxy("http://%s:%[email protected]:8332" % (config.rpc_user, config.rpc_password), timeout=600)
    blocks=bitcoind.generate(confirmations)
    return {'result': blocks}
Ejemplo n.º 11
0
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import time


# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_connection = AuthServiceProxy("http://*****:*****@172.17.0.3:18332")
# best_block_hash = rpc_connection.getbestblockhash()
# print(rpc_connection.getblock(best_block_hash))
for x in range(5):
    start = time.time()
    #result = rpc_connection.generate(1)
    result = rpc_connection.getbestblockhash()    
    # result = rpc_connection.getblocktemplate()    
    end = time.time()
    print(rpc_connection.generate(1))
    print(end-start)
exit(1)
# batch support : print timestamps of blocks 0 to 99 in 2 RPC round-trips:
commands = [ [ "getblockhash", height] for height in range(100) ]
block_hashes = rpc_connection.batch_(commands)
blocks = rpc_connection.batch_([ [ "getblock", h ] for h in block_hashes ])
block_times = [ block["time"] for block in blocks ]
print(block_times)
Ejemplo n.º 12
0
from bitcoinrpc.authproxy import AuthServiceProxy

access = AuthServiceProxy("http://*****:*****@172.17.0.3:18332")
#Genere 2000 blocks
access.generate(2000)


Ejemplo n.º 13
0
from bitcoinrpc.authproxy import AuthServiceProxy

#Génère un block depuis chaque noeud
for x in range(1, 4):
    access = AuthServiceProxy("http://*****:*****@172.17.0."+str(x+1)+":18332")
    access.generate(1)
Ejemplo n.º 14
0
        bts = round(10*random.random(),8)
        print('Payment %d: %.8f BTCs' %(i+1, bts))
        amount += bts
        print(rpc_con.sendtoaddress(address, bts))
    
    print('Total amount sent to P2SH address: %.8f BTCs (%d TXs)' %(amount, num_txs))
    # Mine 1 block in order the transactions to take effect
    rpc_con.generate(1)


# Lets send some BTs to P2SH address
# I assume that blockchain is initially empty, so i have first to create
# at least 101 blocks to receive the first mining fees, in order to be able
# to make the payment transactions.
print('\nMining first 101 blocks')
rpc_con.generate(101)

# Create random # of payments to P2SH address 
send_bts_to_address(p2sh_addr)

# Check mempool for pending transactions and P2SH address for total received amount
print('\nPending transactions in mempool: %d' %len(rpc_con.getrawmempool()))
print('\nTotal amount received by P2SH address: %.8f BTCs' %rpc_con.getreceivedbyaddress(p2sh_addr))



# ***** Check if the P2SH address has any UTXOs to get funds from

def find_UTXOs_of_address(address):
    '''
    This method scans all UTXOs of all addresses in the wallet and returns only