Ejemplo n.º 1
0
    def create_gift_coin(self, blockchain):
        """
        This method creates a new coin for the new client
        """
        # Get address of the client
        hash_public_key = self.hash_pubkey()

        coin_gift_tx_input = TransactionInput(prev_tx="1" * 64,
                                              pk_spender="1" * 64,
                                              signature=bytes(
                                                  "\x11" * 64,
                                                  encoding="utf-8"))
        coin_gift_tx_output = TransactionOutput(
            value=100, hash_pubkey_recipient=hash_public_key)
        coin_gift_tx = Transaction(tx_input=coin_gift_tx_input,
                                   tx_output=coin_gift_tx_output)

        transactions = [coin_gift_tx]

        nonce = 0
        new_block = None
        while True:
            if len(blockchain.blocks) != 0:
                hash_prev_block = blockchain.blocks[len(blockchain.blocks) -
                                                    1].get_hash()
                new_block = Block(transactions, nonce, hash_prev_block)
            else:
                new_block = Block(transactions=transactions,
                                  nonce=nonce,
                                  prev_block_hash="0" * 64)

            if new_block.get_hash().startswith("0" * blockchain.difficulty):
                print("Nonce found:", nonce)
                break

            nonce += 1

        print(coin_gift_tx.serialize())
        message = "\x12" + new_block.serialize()
        self.socket.sendall(message.encode('utf-8'))
Ejemplo n.º 2
0
    def generate(self):
        console.info("generating a transaction")

        tx, src_idx, amount_available = self.find_unspent()

        src_hash = tx.hash
        message = src_hash + int_to_bytes(src_idx)
        signature = self._ecdsa.sign(message)
        key = self._ecdsa.public_key

        tx_input = TransactionInput(
            src_hash=src_hash,
            src_idx=src_idx,
            signature=signature,
            key=key
        )

        amount_send = int(amount_available * random.random())
        fee = int((amount_available - amount_send) * random.random())
        amount_rest = amount_available - amount_send - fee

        peers_with_address = self.peers_with_address()

        # If no known peers, we will send to ourselves
        receiver_key = self._ecdsa.public_key

        # Choose coin receiver at random
        try:
            receiver = random.choice(peers_with_address)
            receiver_key = receiver.address
        except IndexError:
            pass

        # Output that transfers `amount_send` coins to the chosen node
        output_send = TransactionOutput(
            amount=amount_send,
            key=receiver_key
        )

        # Output that transfers the rest of the coins back to us.
        # The coins that are not in outputs constitute the transaction fee
        # (will be collected by the miner who will incude this transaction into
        # a new block)
        output_rest = TransactionOutput(
            amount=amount_rest,
            key=self._ecdsa.public_key
        )

        return Transaction(
            inputs=[tx_input],
            outputs=[output_send, output_rest]
        )
Ejemplo n.º 3
0
    def make_next_block(self):
        if not self.blockchain.blocks:
            new_block = Block(time.time(), [
                Transaction(None, self.address, self.blockchain.mining_reward,
                            0)
            ], 'Genesis', 1)
        else:
            txs = []
            invalid_txs = []

            highest_fee_txs = sorted(self.blockchain.mempool,
                                     key=lambda x: x.fee,
                                     reverse=True)
            included_amount = {}
            for tx in highest_fee_txs:
                if tx.from_address not in included_amount:
                    included_amount[tx.from_address] = 0
                if tx.amount + tx.fee <= self.blockchain.get_balance(
                        tx.from_address) - included_amount[tx.from_address]:
                    txs.append(tx)
                    included_amount[tx.from_address] += tx.amount + tx.fee
                    if len(txs) >= self.blockchain.MAX_TX_PER_BLOCK - 1:
                        break
                else:
                    invalid_txs.append(tx)
            if invalid_txs:
                self.blockchain.mempool = [
                    tx for tx in self.blockchain.mempool
                    if tx not in invalid_txs
                ]
                self.blockchain.save_data(self.blockchain.mempool, 'mempool')
            total_fees = sum([tx.fee for tx in txs])
            txs.append(
                Transaction(None, self.address,
                            self.blockchain.mining_reward + total_fees, 0))
            timestamp = time.time()
            new_block = Block(timestamp, txs, self.blockchain.blocks[-1].hash,
                              self.calculate_difficulty(timestamp))
        return new_block
Ejemplo n.º 4
0
def get_genesis_transaction(sender_wallet, recipient_wallet, value, all_utxos):
    genesis_transaction = Transaction(
        sender_wallet.public_key_as_str(),
        recipient_wallet.public_key_as_str(),
        value,
        []
    )

    genesis_transaction.generate_signature(sender_wallet.private_key)  # manually sign genesis transaction

    genesis_transaction.transaction_id = "0"  # manually set transaction id

    # manually generate transaction output
    genesis_transaction.outputs.append(TransactionOutput(
        genesis_transaction.recipient,
        genesis_transaction.value,
        genesis_transaction.transaction_id
    ))

    # its important to save our first transaction output in utxos
    all_utxos[genesis_transaction.outputs[0].id] = genesis_transaction.outputs[0]

    return genesis_transaction
Ejemplo n.º 5
0
def send_transaction():
    params = request.get_json(silent=True)
    if params:
        address = params.get('address')
        amount = params.get('amount')
        privkey = params.get('privkey')
        if not privkey or type(privkey) != str or not address or type(
                address) != str or not amount or (type(amount) != int
                                                  and type(amount) != float):
            return json_res(err=1015,
                            message="invalid privkey, address or amount")
        result = Transaction.send_transaction_by_key(privkey, address, amount)
        return json_res(result)
    return json_res(err=1013, message="miss params")
Ejemplo n.º 6
0
async def transaction():
    """HTTP POST endpoint to submit a new transaction to the blockchain."""
    new_tx: str = await request.get_json()
    print(
        f"New transaction FROM: {new_tx['from']} TO: {new_tx['to']} AMOUNT: {new_tx['amount']}\n"
    )

    #TODO:VALIDATION HERE

    tran: Transaction = Transaction(str(new_tx['from']), str(new_tx['to']),
                                    str(new_tx['amount']))

    try:
        await node.add_transaction(node.broadcast_outbox, tran)
    except Exception as ex:
        print("Error '{0}' occured. Arguments {1}.".format(ex, ex.args))
    return "OK"
Ejemplo n.º 7
0
def prepare_chain_for_tests():
    pub, prv = cryptutil.fake_new_keys(2048)
    pub2, prv2 = cryptutil.fake_new_keys(2048)

    pub_txt = pub.exportKey("PEM").decode('ascii')
    pub2_txt = pub2.exportKey("PEM").decode('ascii')

    block_chain.mine_block(pub_txt)
    block_chain.mine_block(pub2_txt)
    block_chain.mine_block(pub_txt)

    trx = Transaction(pub_txt, pub2_txt, 10)
    trx.sign(prv)
    block_chain.add_transaction(trx)

    trx = Transaction(pub_txt, pub2_txt, 10)
    trx.sign(prv)
    block_chain.add_transaction(trx)

    block_chain.mine_block(pub_txt)
Ejemplo n.º 8
0
 def new_transaction(self, transaction):
     # check if we have enough coins to execute that transaction
     if not self.address(
     ) in self.blockchain.balances or self.blockchain.balances[
             self.address()] < transaction['amount']:
         logger.error('You dont have %d!' % transaction['amount'])
         return False
     # create the transaction object
     tx = Transaction(from_pubkey=self.address(),
                      to_pubkey=transaction['to'],
                      amount=transaction['amount'])
     # sign it with our private key
     self.sign_transaction(tx)
     # add it to the transaction pool, waiting to be mined in a block
     self.transaction_pool.append(tx)
     logger.info('Transaction %d to %s added to transaction pool!' %
                 (transaction['amount'], transaction['to']))
     # done!
     return True
Ejemplo n.º 9
0
def add_transaction():
    data = request.json
    transaction = Transaction.from_dict(data)
    transaction_pool.append(transaction)
    return jsonify({"status": "OK"})
Ejemplo n.º 10
0
            nodes.append(
                Malicious(id,
                          create_model(),
                          my_x_train[i],
                          my_new_y_train,
                          my_x_test[i],
                          my_y_test[i],
                          equally_fully_connected(id, ids),
                          policy_update_model_weights_name="equal",
                          policy_update_model_weights_func=
                          my_policy_update_model_weights))

    # set blockchain
    genesis_transaction = Transaction(nodes[0].id,
                                      int(time.time()),
                                      flmodel=nodes[0].get_model())  # node 0
    blockchain = Blockchain(
        genesis_transaction,
        policy_update_txs_weight_name="heaviest",
        policy_update_txs_weight_func=my_policy_update_txs_weight)
    # blockchain.print()

    # round
    # TODO: GPU
    # TODO: websocket
    elapsed_times = list()
    for r in range(num_round):
        start_time = time.time()

        print("Round", r)
Ejemplo n.º 11
0
def coinbase_tx():
    coinbase_tx = Transaction.generate_coinbase_transaction(
        Scorpio.get_pubkey_der(),
        Scorpio.get_latest_block().index + 1)
    return json_res(coinbase_tx)
Ejemplo n.º 12
0
from blockchain import Block, Transaction

# SAMPLE BLOCKCHAIN EXAMPLE

# Genesis block building
genesis_transaction = []
genesis_transaction.append(Transaction('sample.pdf'))
genesisBlock = Block(0, genesis_transaction, 1)

# Adding blocks with different transcations
second_transactions = []
second_transactions.append(Transaction('test.pdf'))
second_transactions.append(Transaction('docfile.docx'))
second = Block(genesisBlock.get_blockhash(), second_transactions, 1)

third_transactions = []
third_transactions.append(Transaction('R1.docx'))
third_transactions.append(Transaction('main.py'))
third = Block(second.get_blockhash(), third_transactions, 1)

print(genesisBlock.get_blockhash())
print(second.get_blockhash())
print(third.get_blockhash())
Ejemplo n.º 13
0
def parseTransaction(obj):
    return Transaction.Transaction(obj['index'],obj['price'],obj['landID'],obj['sellerID'],obj['buyerID'],obj['sellSign'],obj['buySign'],obj['documents'])
Ejemplo n.º 14
0
import random
import time

from blockchain import Block, Blockchain, Transaction

USERS = ['Alice', 'James', 'Smith', 'David', 'Adams', 'Isaac', 'Lewis']

SLEEP_TIME = 0

if __name__ == '__main__':

    chain = Blockchain()

    for _ in range(random.randint(1, 5)):
        block = Block()

        for _ in range(random.randint(1, 3)):
            sender, receiver = random.sample(USERS, k=2)
            transaction = Transaction(sender=sender,
                                      receiver=receiver,
                                      value=random.randint(10, 100))
            block.add_transaction(transaction)
            time.sleep(SLEEP_TIME)
        chain.add_block(block)
        print(chain)
        time.sleep(SLEEP_TIME)
def run_miner():
    """Run the main miner loop.
    """

    global blockchain
    global public
    global private
    new_reward = REWARD
    while True:
        # Load transaction queue and blockchain from server.
        new = []
        blockchain = Blockchain()
        blockchain.add_block(
            Block(
                timestamp=datetime.datetime.now(),
                transactions=[],
                previous_hash=get_genisis().hash_block(),
                nonce=12834
            ),
            cheat=True
        )
        server = load_blockchain()
        txns = load_transactions()

        # Is this _the_ new block?
        # or did the server swoop us :(
        new_chain = load_blockchain()
        num_blocks = 1333 + server.head.height
        for i in range (num_blocks):
            reward = Transaction(
            id = gen_uuid(),
            owner = "mined",
            receiver = public,
            coins = REWARD,
            signature = None
            )
            reward.signature = sign(reward.comp(), private)

            txns = [reward]
            b = Block(
                timestamp = datetime.datetime.now(),
                transactions = txns,
                previous_hash = blockchain.head.hash_block()
            )
            blockchain.add_block(b, cheat=True)
                # Let's mine this block.
        reward = Transaction(
        id = gen_uuid(),
        owner = "mined",
        receiver = public,
        coins = REWARD,
        signature = None
        )
        reward.signature = sign(reward.comp(), private)

        txns = [reward]

        # Construct a new block.
        b = Block(
            timestamp = datetime.datetime.now(),
            transactions = txns,
            previous_hash = b.hash_block()
        )
        print(blockchain.head.height)
        mine_till_found(b)
        # WE MINED THIS BLOCK YAY.
        # AND WE WIN.
        resp = get_route('add', data=str(b))
        if resp['success']:
            print "Block added!"
            delete_queue(txns)
        else:
            print "Couldn't add block:", resp['message']
Ejemplo n.º 16
0
from ecdsa import SECP256k1, SigningKey

from blockchain import Blockchain, Transaction

if __name__ == "__main__":

    if len(sys.argv) == 1:
        raise Exception("Missing private key!")

    private_key = sys.argv[1]
    my_sk = SigningKey.from_string(
        bytes.fromhex(private_key),
        curve=SECP256k1,
    )
    my_vk = my_sk.verifying_key.to_string().hex()

    cycoin = Blockchain()

    tx_1 = Transaction(my_vk, "public key goes here", 10)
    tx_1.sign_transaction(my_sk)

    cycoin.add_transaction(tx_1)

    print("START MINING")
    cycoin.mine_pending_transactions(my_vk)

    print("DONE MINING")
    print("my balance: ", cycoin.get_balance_of_address(my_vk))

    cycoin.print_chain()
Ejemplo n.º 17
0
    def mine_block(self):
        # if no blocks, create the genesis block
        if len(self.blockchain.blocks) == 0:
            self.blockchain.create_genesis_block()
            logger.info('Genesis block created!')
            return True
        else:
            # calculate what the next diffculty should be
            new_block_difficulty = self.blockchain.compute_next_difficulty()

            # add all transactions from the transaction pool to this block
            tx_list = []
            for tx in self.transaction_pool:
                tx_list.append(tx)

            # create the block
            block_candidate = Block()
            # set the new blocks fields based on current blockchain
            block_candidate.fill_block(
                height=self.blockchain.get_last_block().height + 1,
                difficulty=new_block_difficulty,
                previous_hash=self.blockchain.get_last_block().hash,
                transactions=tx_list,
                timestamp=time.time())

            # create the coinbase transaction, awards BLOCK_REWARD coins to ourselves (the miner)
            coinbase_tx = Transaction(from_pubkey='COINBASE',
                                      to_pubkey=self.address(),
                                      amount=BLOCK_REWARD)
            # sign the coinbase transaction
            self.sign_transaction(coinbase_tx)
            # add it to the list of transactions for this block
            block_candidate.transactions.append(coinbase_tx)

            logger.info('Mining block %d ... [difficulty=%d] [target=%s]' %
                        (block_candidate.height, block_candidate.difficulty,
                         block_candidate.difficulty_to_target()))

            # find the correct nonce for this block, this takes a while to calculate, hopefully BLOCK_TIME_IN_SECONDS
            self.find_nonce(block_candidate)

            # if find_nonce terminated because we received a new block discard the block
            if self.new_block_received:
                logger.info('Skipped block %d' % block_candidate.height)
                # reset the flag
                self.new_block_received = False
                # well, we did not mine anything
                return False
            else:
                # try adding the block to our current blockchain using add_block
                if not self.blockchain.add_block(block_candidate):
                    # add_block failed! something was not right in the new block
                    logger.error('Mined block %d discarded!' %
                                 block_candidate.height)
                    return False
                else:
                    # clear the transaction pool. Those transactions are now safely in a block in the blockchain
                    self.transaction_pool = []
                    logger.info('Block %d mined!' % block_candidate.height)
                    # mining successful!
                    return True
Ejemplo n.º 18
0
 def setUp(self):
     t0 = Transaction(0, "hello world")
     t1 = Transaction(t0.hash, "woe is me")
     t2 = Transaction(t1.hash, "woe is me")
     self.b0 = Block(0, 0, t0, t1)
     self.b1 = Block(0, self.b0.hash, t2)
Ejemplo n.º 19
0
 def setUp(self):
     self.t0 = Transaction(0, "hello world")
     self.t1 = Transaction(self.t0.hash, "woe is me")
Ejemplo n.º 20
0
my_blockchain = Blockchain(3, 'MaciekCoins')

maciek = User('maciek')
maciek.export_keys()
jurek = User('jurek')
my_blockchain.user_amount(maciek)
my_blockchain.user_amount(jurek)

print('\n\n___________________Mining________________\n')
my_blockchain.mine_coin(1000, maciek)
my_blockchain.user_amount(maciek)
my_blockchain.user_amount(jurek)

print('\n\n___________________Valid transaction________________\n')
transaction1 = Transaction(maciek, jurek, 100, 1)
transaction2 = Transaction(maciek, jurek, 100, 2)
transaction1.print_trans()
transaction2.print_trans()

block = [
    transaction1.get_signed_transaction(),
    transaction2.get_signed_transaction()
]

my_blockchain.try_add_block(block)

my_blockchain.user_amount(maciek)
my_blockchain.user_amount(jurek)

transaction1 = Transaction(jurek, maciek, 200, 1)
Ejemplo n.º 21
0
    def new_transaction(self, recipient, amount):
        """Send an amount of coins to a recipient"""
        self.consensus()
        if recipient not in [x.name for x in self.friends]:
            self.log("I don't know {}".format(recipient))
            return False

        if amount > self.balance:
            self.log("I don't have enough money to send {} {} Coins.".format(
                recipient, amount))
            return False

        self.log("I'm sending {} {} Coins.".format(recipient, amount))

        outputs = []
        spent_outputs = []
        for block in self.blockchain.ledger:
            for output in block.transaction.outputs:  # Sum all earnings
                if output["public_key"] == self.public_key:
                    outputs.append((block.transaction.hash,
                                    block.transaction.outputs.index(output)))

            for input in block.transaction.inputs:  # Detect outgoings
                if input["public_key"] == self.public_key:
                    spent_outputs.append(
                        (input["hash"], input["output_index"]))

        outputs_for_t_input = []
        for output in outputs:
            if output not in spent_outputs:
                outputs_for_t_input.append(output)
        outputs = outputs_for_t_input

        output_amount = 0
        for b in self.blockchain.ledger:
            for output in outputs:
                if b.transaction.hash == output[0]:
                    output_amount += b.transaction.outputs[output[1]]["amount"]

        for friend in self.friends:
            if friend.name == recipient:
                recipient = friend.public_key

        inputs = []
        for output in outputs:  # Generate inputs
            sig = self.private_key.sign(output[0].encode())
            inputs.append({
                "hash": output[0],
                "output_index": output[1],
                "signature": sig,
                "public_key": self.public_key
            })

        outputs = [{"public_key": recipient, "amount": amount}]
        if amount < output_amount:
            outputs.append({
                "public_key": self.public_key,
                "amount": output_amount - amount
            })

        transaction = Transaction(inputs=inputs.copy(), outputs=outputs.copy())
        self.unverified_transactions_pool.append(transaction)
Ejemplo n.º 22
0
                time.sleep(0.3)

    def run(self):
        self.thread = threading.Thread(target=self.scan_tx)
        self.thread.start()

    def stop(self):
        self.stop_flag = True
        self.thread.join()


if __name__ == '__main__':
    node = Node()
    node.run()

    print("input (file name or stop):")
    while True:
        input_str = input()

        if input_str == "stop":
            node.stop()
            break

        txs = read_from_file(input_str)
        for tx in txs:
            from_adress, to_address, amount = tx
            from_account = node.blockchain.state.get_account(from_adress)

            raw_tx = Transaction(from_adress, to_address, amount)
            node.blockchain.tx_pool.append(raw_tx)
Ejemplo n.º 23
0
    def __init__(self, address):
        """
        Initialization method for Client class

        Convention:
        0x10 - New Transaction
        0x11 - New peers
        0x12 - New mined block
        0x13 - Blockchain
        """

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Make the connection
        self.socket.connect((address, 5000))
        self.byte_size = 1024
        self.peers = []
        print('==> Connected to server.')

        self.generate_key_pair()

        client_listener_thread = threading.Thread(target=self.send_message)
        client_listener_thread.start()

        while True:
            try:
                data = self.receive_message()
                if data[0:1] == '\x11':
                    print('==> Got peers.')
                    update_peers(data[1:])
                elif data[0:1] == '\x10':
                    print('==> New transaction.')
                    transaction_info = data[1:]
                    transaction = Transaction(serialization=transaction_info)

                    # Mining block
                    result = mine_block(transaction=transaction,
                                        blockchain=self.blockchain,
                                        miner_address=self.hash_pubkey())
                    if result["status"]:
                        message = "\x12" + result["new_block"].serialize()
                        print("==> Sending new mined block")
                        self.socket.sendall(message.encode("utf-8"))
                    else:
                        print(
                            "==> Invalid transaction. The block have not been mined"
                        )
                elif data[0:1] == '\x13':
                    print('==> Blockchain downloaded.')
                    blockchain_info = data[1:]
                    self.blockchain = Blockchain(serialization=blockchain_info)
                    update_blockchain_file(self.blockchain.serialize())
                elif data[0:1] == '\x12':
                    print('==> New mined block.')
                    block_info = data[1:]
                    new_block = Block(serialization=block_info)

                    in_blockchain = False
                    for block in self.blockchain.blocks:
                        if new_block.equal_blocks(block):
                            print(
                                "==> This block is already mined and is in your blockchain. It will not be added"
                            )
                            in_blockchain = True
                            break

                    if not in_blockchain:
                        print("\t", new_block.__dict__)
                        print("\tNew Block Hash:", new_block.get_hash())
                        self.blockchain.add_block(new_block)
                        update_blockchain_file(self.blockchain.serialize())

                elif data != "":
                    print("[#] " + data)
            except ConnectionError as error:
                print("==> Server disconnected. ")
                print('\t--' + str(error))
                break
Ejemplo n.º 24
0
json.dump({
    "public": wallets[0][1],
    "private": wallets[0][0]
}, open("walletA.json", "w"))
json.dump({
    "public": wallets[1][1],
    "private": wallets[1][0]
}, open("walletB.json", "w"))
print(repr(wallets))

blocksToSubmit = []

#mine initial block
reward = Transaction(id=gen_uuid(),
                     owner="mined",
                     receiver=wallets[0][1],
                     coins=REWARD,
                     signature="")
lastBlock = construct_and_mine([reward], get_genisis())
blocksToSubmit.append(lastBlock)

balances = (10, 0)

for i in range(ITERS):
    weight = randint(10, 20)
    txns = [
        paySomeone(wallets[0][1], wallets[0][0], wallets[1][1], balances[0])
        for _ in range(weight)
    ]
    lastBlock = construct_and_mine(txns, lastBlock)
    blocksToSubmit.append(lastBlock)
Ejemplo n.º 25
0
from fastecdsa import curve, ecdsa, keys

# Your private key goes here
priv_key = keys.gen_private_key(curve.secp256k1)

# From that we can calculate your public key(which doubles as your wallet address)
pub_key = keys.get_public_key(priv_key, curve.secp256k1)
myWalletAddress = hex(int(str(pub_key.x) + str(pub_key.y)))

# Create new instance of Blockchain class
print('Initialize coin')
rebelCoin = Blockchain()

# Create a transaction & sign it with your key
print('1st trans')
tx1 = Transaction(myWalletAddress, '123456789', 100)
tx1.signTransaction(priv_key)
# These try/except blocks are neccessary for now due to a bug i have where
# there's either an ecdsa error or a key error, but reruning fixes it
try:
    try:
        rebelCoin.addTransaction(tx1)
    except ecdsa.EcdsaError:
        rebelCoin.addTransaction(tx1)
except:
    rebelCoin.addTransaction(tx1)
print()

# Mine block
rebelCoin.minePendingTransactions(myWalletAddress)
Ejemplo n.º 26
0
 def test_post_block(self):
     t0 = Transaction(0, "Foo")
     block = Block(0, self.chain.chain[-1].hash, t0)
     self.chain.add(block)
     response = requests.post('http://localhost:5000/block',
                              data=block.serialize())
def run_miner():
    """Run the main miner loop.
    """
    my_address = "2cb4fc5902917e58e531cfbe1d909727aaf331b4856bf8627e09bf8941b69a40"
    my_private = "610af1630bf08b0072d97bdaf71882cd0a2c86e7af72296b4ee73f508b812c28"
    my_address_2 = "a173fd8d2330cc2b4776730891f50099204376217c67b7b23254aca04fbeb5a3"
    my_private_2 = "d0f783f01ac0df1799856964fe74f702763932e1edf3e9d0074646de885d5559"
    public = my_address_2
    private = my_private_2
    donor = None
    while True:
        print("new public", public)
        print("new private", private)
        global blockchain
        global real_b1
        global fake_b1
        global fake_b2
        blockchain = load_blockchain()

        # Add reward to us yay.

        # my_address_3 =  "5adbd7137903135fa2cc5a2de2035a326319e42188a9c6714b26fa016c6ac1bb"
        # my_private_3 = "91f233e1218135b772ddc87a199e6d3cc18233753623f95385dde62e886304c7"

        amount_1 = blockchain.get_wallet_amount(my_address)
        amount_2 = blockchain.get_wallet_amount(my_address_2)
        # amount_3 = blockchain.get_wallet_amount(my_address_3)
        if amount_1 < 0:
            my_private, my_address = generate_keys()
            public = my_address
            private = my_private
            donor_pub = my_address_2
            donor_private = my_private_2
            donor_amount = amount_2
        else:
            my_private_2, my_address_2 = generate_keys()
            public = my_address_2
            private = my_private_2
            donor_pub = my_address
            donor_private = my_private
            donor_amount = amount_1

        # Add reward to us yay.
        reward = Transaction(
            id = gen_uuid(),
            owner = "mined",
            receiver = public,
            coins = REWARD,
            signature = None
        )
        txns = []
        reward.signature = sign(reward.comp(), private)
        txns.append(reward)

        donation1 = Transaction(
            id = gen_uuid(),
            owner = donor_pub,
            receiver = "3119281c76dc54009925c9208bedc5bd0162c27034a1649fd7e2e5df62dba557",
            coins = donor_amount,
            signature = None
        )
        donation1.signature = sign(donation1.comp(), donor_private)
        donation2 = Transaction(
            id = gen_uuid(),
            owner = donor_pub,
            receiver = public,
            coins = donor_amount,
            signature = None
        )
        donation2.signature = sign(donation2.comp(), donor_private)
        txns.append(donation1)
        txns.append(donation2)
        # Construct a new block.
        real_b1 = Block(
            timestamp = datetime.datetime.now(),
            transactions = txns,
            previous_hash = blockchain.head.hash_block()
        )

        mine_till_found(real_b1)

        new_chain = load_blockchain()
        # print "Adding real block now"
        # resp1 = get_route('add', data=str(real_b1))
        # if resp1['success']:
        #     print "Added real block1!"
        # else:
        #     print "Couldn't add block:", resp1['message']
        if new_chain.head.hash_block() == blockchain.head.hash_block():
            print "Adding real block now"
            resp1 = get_route('add', data=str(real_b1))
            if resp1['success']:
                print "Added real block1!"
            else:
                print "Couldn't add block:", resp1['message']
        else:
            print "Someone else mined the block before us :("
Ejemplo n.º 28
0
def add_transaction():
    data = request.get_json()
    transaction = Transaction(**data)
    node.add_unconfirmed_txn(transaction.__dict__)
    return "transaction received", 200
Ejemplo n.º 29
0
from blockchain import BlockChain, Transaction, Wallet
from blockchain import generate_genesis

if __name__ == '__main__':
    blockchain, satoshi = generate_genesis()

    transaction1 = Transaction(satoshi.private_key, satoshi.public_key, 10, 0.80)
    transaction2 = Transaction(satoshi.private_key, satoshi.public_key, 20, 0.90)

    blockchain.add_transacction(transaction1)
    blockchain.add_transacction(transaction2)

    block = blockchain.mine()

    print("Hash : " + block.hash)
    print("Reward : " + str(block.reward))
Ejemplo n.º 30
0
def run_miner():
    """Run the main miner loop.
    """

    global blockchain
    global public
    global private

    while True:
        # Load transaction queue and blockchain from server.
        txns = load_transactions()
        blockchain = load_blockchain()

        # Loc:  Check our balance
        balance = get_balance(public)
        print "Current balance", balance

        # Loc:  Set up attack
        is_attacking = False
        if balance > 60:
            print "Setting up Finney attack"
            is_attacking = True
            t = Transaction(
                id=gen_uuid(),
                owner=public,
                receiver=
                "6f181e44edfc93de084071e590421e5b083f93da6012d441658b6b31a966ae9c",
                coins=balance,
                signature=None)
            # Sign it.
            t.signature = sign(t.comp(), private)

            # Pay myself a lot!
            for x in range(0, 3):
                txns.append(t)

        # Add reward to us yay.
        reward = Transaction(id=gen_uuid(),
                             owner="mined",
                             receiver=public,
                             coins=REWARD,
                             signature=None)
        reward.signature = sign(reward.comp(), private)
        txns.append(reward)

        # Construct a new block.
        b = Block(timestamp=datetime.datetime.now(),
                  transactions=txns,
                  previous_hash=blockchain.head.hash_block())

        # Let's mine this block.
        mine_till_found(b)

        # Is this _the_ new block?
        # or did the server swoop us :(
        new_chain = load_blockchain()

        if new_chain.head.hash_block() == blockchain.head.hash_block():
            # WE MINED THIS BLOCK YAY.
            # AND WE WIN.

            # Loc: Add in a Finney attack to double spend the coin

            resp = get_route('add', data=str(b))
            if resp['success']:
                print "Block added!"
                delete_queue(txns)
            else:
                print "Couldn't add block:", resp['message']
        else:
            print "Someone else mined the block before us :("