コード例 #1
0
    def modification(frame, hack_block_index, hack_block_content):

        window = tk.Toplevel(frame)

        label = tk.Label(window,
                         text="modification Successful",
                         height=2,
                         width=30,
                         font=('Chinyen', 12))
        label.pack(side="top", fill="x", pady=10)

        hacker_block = bc.Block(
            hack_block_index, date.datetime.now(), hack_block_content,
            public_ledger_A[len(public_ledger_A) - 1].gethash())

        hack_block_index = int(hack_block_index)

        print(type(hack_block_index))
        print(hack_block_content)

        for index in range(len(public_ledger_A)):
            print(public_ledger_A[index].getIndex())
            if public_ledger_A[index].getIndex() == hack_block_index:
                public_ledger_A[index] = hacker_block
                break
コード例 #2
0
    def mine(self):
        """
        Mines new blocks
        """

        self.add_genesis_block()

        while self._mining:
            coinbase_transaction = self.create_coinbase_transaction()
            transactions = [coinbase_transaction]

            for _ in range(constants.BLOCK_MAX_TRANSACTIONS - 1):
                # transaction = self._transaction_generator.generate()
                transaction = self._transaction_queue.get()
                transactions.append(transaction)

            block = blockchain.Block(
                hash_prev=self._hash_prev,
                difficulty=self._config.difficulty,
                transactions=transactions,
            )

            console.info("Mining a new block:" + " " * 32 +
                         "\n{:}\n".format(block.summary))

            found = False
            while not found:
                found = self.mine_one_iteration(block)
                # Throttle mining to reduce CPU load (for the demo)
                time.sleep(self._config.mining_throttle_ms / 1000)
コード例 #3
0
def create_new_block_and_header():
    '''Creates a new block and header with the coinbase transaction included and returns them.'''
    block = blockchain.Block()
    header = blockchain.Header()
    # Create the coinbase Transaction
    coinbase_tx = blockchain.Transaction()
    coinbase_tx.setVersionNumber(
        len(Blockchain))  # Becomes a unique identifier for the transaction
    coinbase_tx.setInCounter(1)
    coinbase_tx.setOutCounter(1)
    coinbase_tx.setListOfInputs([blockchain.compute_double_hash('coinbase')])
    coinbase_tx.setListOfOutputs([blockchain.compute_double_hash('minerpay')])
    coinbase_tx.setTransactionHash(
        blockchain.computeTransactionHash(coinbase_tx))
    # Add to block and update header
    block.addTransaction(coinbase_tx)
    block.setTransactionCounter(block.getTransactionCounter() + 1)
    Tree = Merkel_Tree(list(block.getTransactions()[0].getTransactionHash()))
    Tree.construct_tree()
    header.sethashMerkleRoot(Tree.merkelroot)  # Set Merkel Root
    header.setTimestamp(int(time.time()))
    header.sethashPrevBlock(
        Blockchain[-1].getBlockhash())  # Set Previous Block
    header.setBits(0x1e200000)  # Set the difficulty bits
    block.setBlocksize(179)
    block.setBlockHeader(header)
    block.setBlockhash(blockchain.computeHeaderHash(block.getBlockHeader()))
    return block, header
コード例 #4
0
def mindTransactionBlock():
    chain.syncNode(host, port)
    req = request.get_json()
    sender = req["sender"]
    to = req["to"]
    amount = req["amount"]
    trx = tx.Transaction(sender, {to: int(amount)})
    balance = trx.updateInputs(chain)

    byteTx = pickle.dumps(trx)
    newBlock = blockchain.Block(chain.getLastID_Hash()[0] + 1, byteTx,
                                chain.getLastID_Hash()[1])

    newBlock.mineBlock()
    chain.addBlock(newBlock)
    chain.syncNode(host, port)
    response = {
        "sender": sender,
        "amount": amount,
        "newBlock": {
            "id": newBlock.index,
            "hash": newBlock.hash,
            "previous hash": newBlock.prevHash
        },
        "transaction": {
            "balance": balance,
            "txid": trx.id
        }
    }
    return jsonify(req)
コード例 #5
0
 def NewBlockReceived(self, request, context):
     global Blockchain
     global mine_lock
     global current_block
     global current_header
     print("New Block Received")
     block = blockchain.Block()
     header = blockchain.Header()
     for transaction in request.transaction:
         block.addTransaction(transaction_from_serial(transaction))
     block.setTransactionCounter(request.transaction_counter)
     for header in request.Blockheader:
         header.sethashMerkleRoot(header.hash_merkel_root)
         header.setTimestamp(header.timestamp)
         header.sethashPrevBlock(header.hash_prev_block)
         header.setBits(header.bits)
     block.setBlocksize(request.BlockSize)
     block.setBlockHeader(header)
     block.setBlockhash(request.blockhash)
     Blockchain.append(block)  # Add the new block
     mine_lock = False
     time.sleep(random.randint(0, 3))  # Sleep for random time
     mine_lock = True
     current_block, current_header = create_new_block_and_header(
     )  # Reset the current block and header
     return response
コード例 #6
0
def generate_genesis_block():
    '''Generates the genesis block'''
    # Genesis Transaction
    genesis_transaction = blockchain.Transaction()
    genesis_transaction.setVersionNumber(0)
    genesis_transaction.setOutCounter(1)
    genesis_transaction.setInCounter(1)
    genesis_transaction.setListOfInputs(['genin'])
    genesis_transaction.setListOfOutputs(['genesis07'])
    genesis_transaction.setTransactionHash(
        blockchain.computeTransactionHash(genesis_transaction))
    # Genesis Header
    genesis_header = blockchain.Header()
    genesis_header.sethashPrevBlock('0' * 64)  # Previous Hash of all 0's
    Tree = Merkel_Tree([genesis_transaction.getTransactionHash()])
    Tree.construct_tree()
    genesis_header.sethashMerkleRoot(Tree.merkelroot)
    # Genesis Block
    genesis_block = blockchain.Block()
    genesis_block.setBlockHeader(genesis_header)
    genesis_block.setTransactionCounter(1)
    genesis_block.addTransaction(genesis_transaction)
    genesis_block.setBlocksize(179)
    genesis_block.setBlockhash(
        blockchain.computeHeaderHash(genesis_block.getBlockHeader()))
    return genesis_block
コード例 #7
0
ファイル: test.py プロジェクト: hruzinator/CryptoCurrency
	def test_getSerialiedData(self):
		b = blockchain.Block(
			index = 0,
			timestamp = date.datetime.now(),
			data = b'Some test data',
			lastHash="0",
			proofOfWork=0
		)
		self.assertTrue(b.getSerializedData())
コード例 #8
0
    def test_add_block(self):
        block = blockchain.Block(1558649054, "Genesis Block", None, 0)
        bc = blockchain.Blockchain()
        bc.add(block)

        block2 = blockchain.Block(int(time.time()), "First block", block.hash,
                                  1)
        bc.add(block2)

        block3 = blockchain.Block(int(time.time()), "2nd block", block2.hash,
                                  2)
        bc.add(block3)

        self.assertEqual(
            bc.getblock(0).hash,
            "61977ea186232850707dd0c2f14d74f5981ba9cff82c07966608c56d0d101542")
        self.assertEqual(bc.getblock(1).data, "First block")
        self.assertEqual(bc.getblock(2).data, "2nd block")
        self.assertEqual(bc.getblock(3), None)
コード例 #9
0
def manager():
    chain = blockchain.Chain()
    spam_chain = blockchain.Chain()
    block = blockchain.Block()
    flag = True

    #mining text data
    #filter by naive bayes
    '''
	input feature_result.csv
	'''
    df = pd.read_csv('feature_result.csv', header=None)
    train_matrix = df.values
    model, dictionary = spam_filter.train(train_matrix)

    while flag:
        print("\n####Email tracking demon by blockchain####")
        option = """
		Action set:
			(1) send email by smtp
			(2) recieve&record in blockchain email by pop3
			(3) show the email content(block)
			(4) show the whole email chain
			(5) judge the spam & store in spam chain
			(6) show the spam chain
			(7) exit
				"""
        print(option)
        decide = input('-->Enter: ')
        if decide == '1':
            send_block()
        elif decide == '2':
            recieve_block(chain)
        elif decide == '3':
            index = int(input('input the index of the block: '))
            print_info(chain, index)
        elif decide == '4':
            if len(chain.chain) > 0:
                print_chain(chain)
            else:
                print('no block in the chain')
        elif decide == '5':
            if len(chain.chain) > 0:
                index = int(input('input the index of the block: '))
                judge_spam(chain, index, spam_chain, model, dictionary)
            else:
                print('No block')
        elif decide == '6':
            if len(spam_chain.chain) > 0:
                print_chain(spam_chain)
            else:
                print('No spam eamil in the chain')
        elif decide == '7':
            print('\nexit')
            flag = False
コード例 #10
0
 def invest_submit(investor_name, amount, invest_type):
     invest_detail = [[100000000000, "Government Debt", 0.03, 12],
                      [30000000000, "Corporate Investment", 0.02, 24]]
     detail = invest_detail[invest_type]
     block_detail = str(detail) + "-" + str((investor_name, amount))
     print((investor_name, amount, invest_type, detail, block_detail))
     public_ledger_A.append(
         bc.Block(len(public_ledger_A), date.datetime.now(), block_detail,
                  public_ledger_A[len(public_ledger_A) - 1].gethash()))
     public_ledger_B.append(
         bc.Block(len(public_ledger_B), date.datetime.now(), block_detail,
                  public_ledger_A[len(public_ledger_B) - 1].gethash()))
     public_ledger_C.append(
         bc.Block(len(public_ledger_C), date.datetime.now(), block_detail,
                  public_ledger_A[len(public_ledger_C) - 1].gethash()))
     public_ledger_D.append(
         bc.Block(len(public_ledger_D), date.datetime.now(), block_detail,
                  public_ledger_A[len(public_ledger_D) - 1].gethash()))
     public_ledger_E.append(
         bc.Block(len(public_ledger_E), date.datetime.now(), block_detail,
                  public_ledger_A[len(public_ledger_E) - 1].gethash()))
コード例 #11
0
def judge_spam(chain, index, spam_chain, model, dictionary):
    message_block = chain.chain[index]
    for message in message_block.messages:
        content = message.content
        result_matrix = spam_filter.judge(content, model,
                                          dictionary)  #retunr confusion matrix
        if result_matrix[0][0]:
            print('The mail is Ham')
        else:
            print('The mail is Spam, store the spam in spam_chain')
            block = blockchain.Block()
            block.add_message(message)
            spam_chain.add_block(block)
コード例 #12
0
def verify_and_add_block():
    block_data = request.get_json()
    block = blockchain.Block(block_data["index"],
                             block_data["transactions"],
                             block_data["timestamp"],
                             block_data["previous_hash"],
                             )
    block.hash = block_data['hash']
    added = bchain.add_block_on_shard(block,"")
    if not added:
        return "The block was discarded by the node", 400
    worldstate.update_with_block(block)
    return "Block added to the chain", 201
コード例 #13
0
async def consumer(message, websocket, queue):
    """Consumer implementation for when a web socket message is received."""
    print("consumer message:", message)
    global NODES
    payload = Payload(message)
    if payload.msgtype == "all_nodes":
        return_data = json.dumps(list(NODES.keys()))
        print(return_data)
        await queue.put(return_data)
    elif payload.msgtype == "new_node":
        NODES[payload.msgpayload] = None  #reserve
        blockchain_json = json.dumps(
            [b.__dict__ for b in blockchain.blockchain])
        full_message = Payload(msgtype="full_blockchain",
                               msgpayload=blockchain_json).to_json()
        await websocket.send(full_message)
    elif payload.msgtype == "full_blockchain":
        try:
            json_obj = json.loads(payload.msgpayload)

            for block in json_obj:
                block = blockchain.Block(block['data'], block['previous_hash'],
                                         block['index'], block['timestamp'],
                                         block['hash'], block['nonce'])
                blockchain.blockchain.append(block)
        except:
            blockchain.blockchain = []
            print("Unexpected error:", sys.exc_info()[0], sys.exc_info()[1])

        print('received full blockchain')
    elif payload.msgtype == "new_block":
        json_obj = payload.msgpayload
        block = blockchain.Block(json_obj['data'], json_obj['previous_hash'],
                                 json_obj['index'], json_obj['timestamp'],
                                 json_obj['hash'], json_obj['nonce'])
        blockchain.blockchain.append(block)
    else:
        print("Unknown msgtype received: ", payload.msgtype)
コード例 #14
0
def func2():
    choice = request.form['candidate']
    v1 = b1.vote(int(choice))
    with open('votefile.csv', 'a', newline="") as votefile:
        writer = csv.writer(votefile)
        for key, value in v1.voteobject.items():
            writer.writerow([key, value])
    if b1.vote.count % 4 == 0:
        block1 = b1.Block()
        blockx = block1.mineblock()
        with open('blockchain.abc', 'ab') as blockfile:
            pickle._dump(blockx, blockfile)
        print("block added")
    return redirect('/thanks')
コード例 #15
0
    def load_seed():
        invest_detail = [[100000000000, "Government Debt", 0.03, 12],
                         [30000000000, "Corporate Investment", 0.02, 24]]
        names = [
            "Juliane Hutt", "Millard Rakow", "Maryam Borders",
            "Michaele Walton", "Willis Edsall", "Barb Lamar", "Maira Bryd",
            "Senaida Paris"
            "Hanna Womack", "Irvin Holen", "Layne Richmond", "Hedwig Brunette",
            "Anastacia Derrow", "Ivan Smitherman", "Evia Vice",
            "Mercedez Rader", "Loriann Tesch"
        ]

        for i in range(10):
            seed_1 = []
            seed_1 = invest_detail[int(2 * random.random())]
            block_detail = str(seed_1) + "-" + str((names[int(
                16 * random.random())], int(1000 * random.random())))
            public_ledger_A.append(
                bc.Block(len(public_ledger_A), date.datetime.now(),
                         block_detail,
                         public_ledger_A[len(public_ledger_A) - 1].gethash()))
            public_ledger_B.append(
                bc.Block(len(public_ledger_B), date.datetime.now(),
                         block_detail,
                         public_ledger_A[len(public_ledger_B) - 1].gethash()))
            public_ledger_C.append(
                bc.Block(len(public_ledger_C), date.datetime.now(),
                         block_detail,
                         public_ledger_A[len(public_ledger_C) - 1].gethash()))
            public_ledger_D.append(
                bc.Block(len(public_ledger_D), date.datetime.now(),
                         block_detail,
                         public_ledger_A[len(public_ledger_D) - 1].gethash()))
            public_ledger_E.append(
                bc.Block(len(public_ledger_E), date.datetime.now(),
                         block_detail,
                         public_ledger_A[len(public_ledger_E) - 1].gethash()))
コード例 #16
0
def new_block():
    data = json.loads(request.get_json())

    block = blockchain.Block(index=data['index'],
                             timestamp=data['timestamp'],
                             transactions=data['transactions'],
                             previous_hash=data['previous_hash'],
                             nonce=data['nonce'])

    added = my_blockchain.add_block(block)

    if not added:
        return 'Block was discarded by the node', 400

    return 'Block added to chain', 201
コード例 #17
0
def recieve_block(chain):
    block = blockchain.Block()
    block_message = None
    user = input('Email user: '******'User password: '******'POP3 server: ')
    #pop3_server = poplib.POP3_SSL('pop.googlemail.com', '995')
    #pop3_server = poplib.POP3_SSL(pop3_server, '995')
    temp_server = email_track.fetch_email(user, password, pop3_server)
    temp_server.connect()
    temp_server.decode_email()
    block_message = temp_server.block_message
    block.add_message(blockchain.Email_Content(block_message))
    chain.add_block(block)
    print('add successfully, block: ', block)
    print('\r\n')
コード例 #18
0
ファイル: test.py プロジェクト: hruzinator/CryptoCurrency
	def test_create_block(self):
		ts = date.datetime.now()
		b = blockchain.Block(
			index = 0,
			timestamp = ts,
			data = b'Some test data',
			lastHash="0",
			proofOfWork=0
		)
		self.assertEqual(b.index, 0)
		self.assertEqual(b.timestamp, ts)
		self.assertEqual(b.data, b'Some test data')
		self.assertEqual(b.lastHash, "0")
		self.assertEqual(b.proofOfWork, 0)
		# test that hash of this block was generated
		self.assertTrue(b.hash)
コード例 #19
0
async def add_transaction(broadcast_outbox, transaction):
    """Adds a transaction to a block in the blockchain."""
    TRANSACTIONS_QUEUE.append(transaction.__dict__)
    print("transactions len:", len(TRANSACTIONS_QUEUE))
    if len(TRANSACTIONS_QUEUE) >= 5:
        previous_hash: str = None
        if len(blockchain.blockchain) > 0:
            previous_hash = blockchain.blockchain[len(blockchain.blockchain) -
                                                  1].hash
        block = blockchain.Block(json.dumps(TRANSACTIONS_QUEUE), previous_hash)
        hash_value, nonce = blockchain.proof_of_work(block, 1)
        print(f"proof of work completed. Hash: {hash_value} Nonce:{nonce}")
        block.hash_value = hash_value
        block.nonce = nonce
        block.timestamp = datetime.utcnow().strftime("%y/%m/%d %H:%M")
        blockchain.blockchain.append(block)
        await alert_all_nodes(broadcast_outbox, "new_block", block.__dict__)
        TRANSACTIONS_QUEUE.clear()
コード例 #20
0
ファイル: test.py プロジェクト: HowardDunn/SimpleBlockchain
def test(num_blocks):
    blckchain = blockchain.Blockchain()

    rand2 = random.randint(1, 10)

    for i in range(0, num_blocks):

        block = blockchain.Block()
        for j in range(rand2):
            rand3 = random.randint(1, 100)
            block.add_transaction(rand3)

        blckchain.add_block(block)

    blckchain.blocks[1].add_transaction(57)
    start_time = time.time()
    blckchain.rehash()
    time_taken = time.time() - start_time

    return time_taken
コード例 #21
0
def consensus():
    # Replace chain with longest valid chain in network

    replaced = False
    longest_chain = my_blockchain.chain
    chain_len = len(my_blockchain.chain)

    for node in my_blockchain.nodes:
        chain = []

        # Create blockchain instance from json string returned by node
        url = 'http://127.0.0.1:' + str(node) + '/chain'
        response = requests.get(url)
        data = response.json()
        
        for i in range(0, len(data)):
            block = blockchain.Block(
                index = data[i]['index'],
                timestamp = data[i]['timestamp'],
                transactions = data[i]['transactions'],
                previous_hash = data[i]['previous_hash'],
                nonce = data[i]['nonce']             
            )

            chain.append(block)

        if my_blockchain.validate_chain(longest_chain):
            if my_blockchain.validate_chain(chain) and len(chain) > chain_len:
                replaced = True
                chain_len = len(chain)
                longest_chain = chain
        else:
            replaced = True
            chain_len = len(chain)
            longest_chain = chain
           
    if replaced:
        my_blockchain.chain = longest_chain
        return 'Our chain was replaced'

    return 'Our chain is authoritative'
コード例 #22
0
def add_block(chain):
    train_dir = 'ling-spam\\train-mails'
    emails = [os.path.join(train_dir, f) for f in os.listdir(train_dir)]
    print(emails[0])
    block_msg = None

    for mail in emails[601:]:
        context = None
        with open(mail) as file:
            context = file.read()
            #print(context)
        block_msg = context
        block = blockchain.Block()
        block.add_message(blockchain.Email_Content(block_msg))
        #print(len(chain.chain))
        chain.add_block(block)

    print(len(emails[601:]))
    # print(chain.chain[0])
    # print(chain.chain[1])
    return emails[601:]
コード例 #23
0
    def add_genesis_block(self):
        """
        Assembles genesis block, the first block in the blockchain.
        It is hardcoded and the same for every mining node.
        """
        coinbase_transaction = self.create_coinbase_transaction(
            dest_key=constants.GENESIS_BLOCK_DEST_KEY)

        transactions = [coinbase_transaction]

        genesis_block = blockchain.Block(
            hash_prev=constants.GENESIS_BLOCK_HASH_PREV,
            difficulty=constants.GENESIS_BLOCK_DIFFICULTY,
            hash=constants.GENESIS_BLOCK_HASH,
            merkle_root=constants.GENESIS_BLOCK_MERKLE_ROOT,
            nonce=constants.GENESIS_BLOCK_NONCE,
            extra_nonce=constants.GENESIS_BLOCK_EXTRA_NONCE,
            transactions=transactions)

        self._hash_prev = genesis_block.hash
        self.maybe_add_block(genesis_block)
コード例 #24
0
def create_chain_from_dump(chain_dump):
    generated_blockchain = blockchain.Blockchain()
    # generated_blockchain.create_genesis_block()
    for idx, block_data in enumerate(chain_dump):
        if idx == 0 and not IS_SHARDED:
            continue  # skip genesis block
        block = blockchain.Block(block_data["index"],
                                 block_data["transactions"],
                                 block_data["timestamp"],
                                 block_data["previous_hash"])
        block.hash = block_data['hash']
        if IS_SHARDED:
            #integraty check is not performed

            added= generated_blockchain.add_block_on_shard(block,'')
        else:
            added = generated_blockchain.add_block(block)

        if not added:
            raise Exception("The chain dump is tampered!!")
    return generated_blockchain
コード例 #25
0
def mindCoinBaseBlock(name, amount, chain=chain):
    chain.syncNode(host, port)
    coin = tx.Transaction("coinbase", {name: int(amount)})

    byteCoin = pickle.dumps(coin)
    newBlock = blockchain.Block(chain.getLastID_Hash()[0] + 1, byteCoin,
                                chain.getLastID_Hash()[1])
    newBlock.mineBlock()
    chain.addBlock(newBlock)
    chain.syncNode(host, port)

    response = {
        "sender": name,
        "amount": amount,
        "newBlock": {
            "id": newBlock.index,
            "hash": newBlock.hash,
            "previous hash": newBlock.prevHash
        }
    }
    jsonify(response)
    return jsonify(response)
コード例 #26
0
def new_transaction():
    global LAST_INDEX
    global PREV_HASH
    values = request.get_json()

    # Check that the required fields are in the POST'ed data
    required = ['ts', 'sender', 'recipient', 'amount']
    if not all(k in values for k in required):
        return 'Missing values', 400

    # Create a new Transaction
    index = bchain.new_transaction(values['ts'], values['sender'], values['recipient'], values['amount'])

    if len(bchain.current_transactions) == TX_PER_BLOCK:
        #
        block = blockchain.Block(LAST_INDEX, bchain.current_transactions, time.time(), PREV_HASH)
        block.hash = block.compute_hash()
        PREV_HASH = block.hash
        peer_broadcast("add_block", block.__dict__, [])
        LAST_INDEX += 1
        bchain.current_transactions=[]
        print('block has been broadcasted')

    return 'block has been broadcasted', 201
コード例 #27
0
 def new_block(self, proof, phash):
     block = bl.Block(proof, phash, *self.unconfirmed_transactions)
     self.unconfirmed_transactions = []
     self.chain.add(block)
     return block
コード例 #28
0
from flask import *
import blockchain

FILE = "test.txt"
chain = blockchain.Chain(FILE+".chain.json",blockchain.Block(0,"",""))
app = Flask(__name__)

@app.route("/")
def base():
	chain.load()
	return render_template("file.html",hashes=[block.hash[:8] for block in chain.blocks if block.data != ""],filename=FILE)

@app.route("/<string:hash>")
def byhash(hash):
	chain.load()
	if len(hash)>8: return abort(400)
	for i in range(chain.blocks[-1].index,-1,-1):
		if chain.blocks[i].hash[:8]==hash:
			return Response(chain.blocks[i].data,mimetype="text/plain")
	return abort(404)

if __name__=="__main__":
	app.run(port=8000)
コード例 #29
0
def incoming_command_handler(connection, ip_address, port_number, command,
                             incoming_message):

    global registered_peers

    #------------------------------------------------------------#
    #-- used for populating the peer and registered peer lists --#
    machineID = ""
    key = ""
    ipAddress = ""
    port = ""
    #------------------------------------------------------------#

    outgoing_message = ""
    #------------------------------------------------------------------------------------------------------------------#
    # --------------------------------------- Peer receives list of peers info ----------------------------------------#
    if command == "PEER":

        message_length = len(incoming_message)

        index = 0
        while index < message_length:

            # -----------  MachineID ---------------#
            while incoming_message[index] != " ":
                machineID += incoming_message[index]
                index += 1
            #---------------------------------------#
            index += 1
            # --------------- Key ------------------#
            while incoming_message[index] != " ":
                key += incoming_message[index]
                index += 1
            #---------------------------------------#
            index += 1
            #------------- ipAddress ---------------#
            while incoming_message[index] != " ":
                ipAddress += incoming_message[index]
                index += 1
            #---------------------------------------#
            index += 1
            #------------ portNumber ---------------#
            while incoming_message[index] != " ":
                port += incoming_message[index]
                index += 1
            #---------------------------------------#
            index += 1
            # -- Add peer info to list of peers --#
            peers.append(Peer_Info(machineID, key, ipAddress, port))

            # -- clear each variable so it can be reused --#
            machineID = ""
            key = ""
            ipAddress = ""
            port = ""

    #------------------------------------------------------------------------------------------------------------------#
    # -------------------  Peer receives command to send copy of registered peer list ---------------------------------#
    elif command == "REGP":

        print("sending list of registered peers to %s " % (connection))

        outgoing_message = MESSAGE_HEADER + "|" + "REPL" + "|" + ""

        for x in registered_peers:
            outgoing_message += (str(x.machineID) + " " + str(x.privateKey) +
                                 " " + str(x.ipAddress) + " " +
                                 str(x.portNumber) + " ")

        print(outgoing_message)
        connection.send(outgoing_message.encode("utf-8"))
    #------------------------------------------------------------------------------------------------------------------#
    # -----------------------------------  Peer receive list of registered peers  -------------------------------------#
    elif command == "REPL":
        message_length = len(incoming_message)
        index = 0

        while index < message_length:

            # -------------- MachineID ----------------#
            while incoming_message[index] != " ":
                machineID += incoming_message[index]
                index += 1
            #------------------------------------------#
            index += 1
            #------------------ Key -------------------#
            while incoming_message[index] != " ":
                key += incoming_message[index]
                index += 1
            #------------------------------------------#
            index += 1
            #--------------- ipAddress ----------------#
            while incoming_message[index] != " ":
                ipAddress += incoming_message[index]
                index += 1
            #------------------------------------------#
            index += 1
            #--------------- portNumber ---------------#
            while incoming_message[index] != " ":
                port += incoming_message[index]
                index += 1
            #------------------------------------------#
            index += 1

            #---- Add peer to list of registered peers if not already there ---#
            found = False
            for p in registered_peers:
                if (p.machineID == machineID) and (p.privateKey == key):
                    p.ipAddress = ipAddress
                    p.portNumber = port
                    found = True
                    break
            #------------------------------------------------------------------#
            if (found == False) and (machineID != MACHINE_ID):
                registered_peers.append(
                    Peer_Info(machineID, key, ipAddress, port))

            # -- clear variables to reuse --#
            machineID = ""
            key = ""
            ipAddress = ""
            port = ""

    #---------------------------------------------------------------------------------------------------------------#
    #------------ Peer receive request from another node to join it's list of registered peers ---------------------#
    elif command == "JOIN":
        outgoing_message = MESSAGE_HEADER + "|" + "WELC" + "|" + incoming_message
        print(outgoing_message)
        connection.send(outgoing_message.encode("utf-8"))
    #---------------------------------------------------------------------------------------------------------------#
    #------------ Peer receives confirmation that it has joined list of registered peers for node ------------------#
    elif command == "WELC":
        print(
            "Succesfully joined list of registered peers for node at ip address: %s port number: %s"
            % (ip_address, port_number))
    #---------------------------------------------------------------------------------------------------------------#
    #----------------------------- Peer receives command to update it's blockchain ---------------------------------#
    elif command == "ADDB":

        print("Adding block to blockchain, sent from peer: %s " % (connection))
        #parse the incoming_message to repackage into identical block
        parsedMessage = incoming_message.split("%")
        incomingId = parsedMessage[0]
        from datetime import datetime
        incomingTime = datetime.strptime(parsedMessage[1],
                                         '%Y-%m-%d %H:%M:%S.%f')
        incomingBallot = ast.literal_eval(parsedMessage[2])
        incomingPrevHash = parsedMessage[4]
        blockToAdd = blockchain.Block(incomingId, incomingTime, incomingBallot,
                                      incomingPrevHash)
        index = len(blockchain.chain)
        if (blockToAdd.previous_hash == blockchain.chain[index - 1].hash):
            blockchain.append_block(blockToAdd)
            saveBlockchain(blockchain.chain, 'localBlockchain.pk1')
        else:
            print("invalid block")

        outgoing_message = MESSAGE_HEADER + "|" + "CONF" + "|" + incoming_message
        print(outgoing_message)
        connection.send(outgoing_message.encode("utf-8"))
    #---------------------------------------------------------------------------------------------------------------#
    #-------- Peer reveives confirmation that other peer has received new block and added it to blockchain ---------#

    elif command == "CONF":
        print("Confirmation to add block to blockchain")

        block_chain.append(incoming_message)
        print("Block added: " + incoming_message)
    # --------------------------------------------------------------------------------------------------------------#
#------------ Peer receives error message indicating something went wrong durring communication ----------------#
    elif command == "ERRO":
        print("error performing operation %s" % (ip_address))
    #---------------------------------------------------------------------------------------------------------------#
    # ------------------------------------------ Peer quits network -------------------------------------------------#
    elif command == "QUIT":
        outgoing_message = MESSAGE_HEADER + "|" + "DONE" + "|" + incoming_message
        connection.send(outgoing_message.encode("utf-8"))

        for i, p in enumerate(registered_peers):
            if (p.ipAddress == ipAddress) and (p.portNumber == port_number):
                print("Peer: %s signed off from network." % (p.machineID))
                del registered_peers[i]
    # -----------------------------------------------------------------------------------------------------------------#
    #------------------ Peer receives confirmation that it has disconnected from other peer ---------------------------#
    elif command == "DONE":
        print("Confirmed disconnection from peer")
    #------------------------------------------------------------------------------------------------------------------#
    elif command == "LEAD":
        global LEADER
        LEADER = True
        print("%s is now the leader" % (MACHINE_ID))

        time.sleep(10.0)
        LEADER = False
    #----------------------------- Peer receives unrecognized command to close socket ------------------------------#
    else:
        outgoing_message = MESSAGE_HEADER + "|" + "ERRO" + "|" + incoming_message

        print(outgoing_message)
        connection.send(outgoing_message.encode("utf-8"))
コード例 #30
0
# Unit tests for Blockchain class of blockchain.py
import blockchain
difficulty=16

block0 = blockchain.Block(0, '0', 'Genesis Block')
block0.search_hash(difficulty)
block1 = blockchain.Block(1, block0.hash, 'data1')
block1.search_hash(difficulty)
block2 = blockchain.Block(2, block1.hash, 'data2')
block2.search_hash(difficulty)


bchain = blockchain.Blockchain(difficulty)
assert bchain.validate(block2, block1)
assert bchain.validate(block1, block0)
assert bchain.validate(block0, "No_parent")
assert bchain.validate(block2, block0) == False

assert bchain.validate_chain()
assert bchain.add_block(block0)
assert bchain.validate_chain()
assert bchain.add_block(block1)
assert bchain.validate_chain()
assert bchain.add_block(block2)
assert bchain.validate_chain()