コード例 #1
0
    def listen_for_input(self):
        waiting_for_input = True
        while waiting_for_input:
            print("Please Choose")
            print("1: Add a new trasaction value")
            print("2: Mine a new block ")
            print("3: Output the blockchain blocks")
            print("4: Check transaction validity")
            print("5: Create wallet")
            print("6: Load wallet")
            print("7: save wallet keys ")
            print("q: Quit")
            user_choice = self.get_user_choice()
            if user_choice == "1":
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data
                signature = self.wallet.sign_transactions(self.wallet.public_key, recipient, amount)
                if self.blockchain.add_transaction(recipient, self.wallet.public_key, amount, signature):
                    print('Added Transaction')
                else:
                    print('Transaction Failed')
                print(self.blockchain.get_open_transactions())

            elif user_choice == "2":
                if not self.blockchain.mine_block():
                    print('Mining failed. Got no wallet')

            elif user_choice == "3":
                self.print_blockchain_element()

            elif user_choice == "4":
                if Verification.verify_transactions(self.blockchain.get_open_transactions(), self.blockchain.get_balance):
                    print("All transactions are valid")
                else:
                    print("There are invalid transactions")
            elif user_choice == "5":
                self.wallet.create_keys()
                self.blockchain = BlockChain(self.wallet.public_key)
            elif user_choice == "6":
                self.wallet.load_keys()
                self.blockchain = BlockChain(self.wallet.public_key)

            elif user_choice == "7":
                if self.wallet.public_key != None and self.wallet.private_key != None:
                    self.wallet.save_keys()
            elif user_choice == "q":
                waiting_for_input = False

            else:
                print("Invalid input. Please select a value from the list")
            if not Verification.verify_chain(self.blockchain.get_chain()):
                print("Invalid blockchain")
                break
            print(
                f'Balance of {self.wallet.public_key}: {self.blockchain.get_balance():6.2f}')
        else:
            print("User left")

        print('Done')
コード例 #2
0
def block_recieve(broadcast_message, payload):

    print()
    print ("NEW BLOCK RECIEVED")

    block_json = payload['data']

    try:
        block = Block.from_json(block_json)

        if (block.valid_block() == True):
            temp_blocks = copy.copy(blockchain.blocks)

            temp_blocks.append(block)
            temp_block_chain = BlockChain(temp_blocks)

            print (temp_block_chain)

            if (temp_block_chain.validate_chain() == True):
                print ("valid new blockchain")
                blockchain.blocks.append(block)
            else:
                print("invalid chain. Not updated")
        else:
            print ("invalid block")
    except json.decoder.JSONDecodeError:
        print ("invalid block")

    blockchain.save_blockchain('./blockchain/blockchain.json')

    print ()

    sys.stdout.write(prompt_string())
    sys.stdout.flush()
コード例 #3
0
ファイル: test_blockchain.py プロジェクト: alexraskin/pychain
    def test_idempotency(self):
        blockchain = BlockChain()

        blockchain.register_node('http://192.168.0.1:5000')
        blockchain.register_node('http://192.168.0.1:5000')

        assert len(blockchain.nodes) == 1
コード例 #4
0
 def __init__(self, users):
     self.__private_key, self.public_key = gen_keys()
     self.blockchain = BlockChain()
     self.users = users
     self.current_building_block = Block()
     self.last_block = None
     self.init()
コード例 #5
0
ファイル: pool.py プロジェクト: PabloG6/SimpleChain
    def __init__(self):
        # create genesis block
        first_hash = hashlib.md5(str(time.time()).encode())
        # no wallets currently exist for
        self.GENESIS_BLOCK = BlockChain(0, first_hash)

        pass
コード例 #6
0
def test_blockchain():
    bc = BlockChain()
    for _ in range(2):
        bc.new_block()
    pprint(bc.chain)
    for i, block in enumerate(bc.chain):
        print(i, bc.hash(block))
    assert bc.valid_chain(bc.chain)
コード例 #7
0
ファイル: cli.py プロジェクト: ray-qwer/pseudo_bitcoin
def cli_print_block_chain():
    blk_chain = BlockChain()
    if not blk_chain.Verify_Block_Chain():
        print("Your database may be damaged. Cannot open this database.")
        return
    print(blk_chain)
    for i in range(blk_chain.get_length()):
        print(blk_chain.get_block(i))
コード例 #8
0
    def _create_validator_chain(self):
        '''
            Create a chain with the same genesis block. Blocks from the test chain will be added to this chain by verifying the validity of the chain.

        '''

        self.validator_chain_ = BlockChain(
            chain=[self.blockchain_.genesis_block])
コード例 #9
0
ファイル: miner.py プロジェクト: dedeswim/com-402-hw
    def __init__(self, addr: Address, miners: List[Address], genesis: bool):
        self._addr = addr
        self._miners = miners

        if genesis:
            genesis_data = 'Hello, world!'.encode('utf-8')
            genesis_block = Block.genesis_block(genesis_data)
            self._blockchain = BlockChain(genesis_block)
コード例 #10
0
def add_block():
    block_dict = request.values.to_dict()
    block = Block(**block_dict)
    chain = BlockChain()
    last_block = chain.get_last_block()
    if ProofOfWork(block, last_block).is_block_valid():
        chain.add_block(block)

    return jsonify(received=True)
コード例 #11
0
def get_balance_by_address(args):
    blockchain = BlockChain()
    utxo_set = UTXOSet(blockchain)
    balance, utxos = utxo_set.find_utxo_by_address(args.address)

    print('balance: {}'.format(balance))
    print('transaction ID with spendable money:')
    for utxo in utxos:
        print(utxo)
コード例 #12
0
 def add_blocks(self):
     while True:
         block = self.queue.get()
         print(block.hash())
         if self.blockchain == None:
             self.blockchain = BlockChain(block)
         else:
             self.blockchain.append(block)
         print(self.blockchain.chain[-1].hash())
コード例 #13
0
    def __init__(self):
        self.chain = BlockChain()  # 初始情况,默认先查看本地文件
        self.neighbors = set()  # 邻接点
        self.transactions = []  # 交易的集合
        self.new_block = None  # 新的区块,用于挖矿
        self.pk, self.sk = self.get_key()  # 产生结点的公钥和私钥
        self.port = None

        self.add_neighbors()  # 初始化邻居节点
コード例 #14
0
def mine_block(args):
    blockchain = BlockChain()
    utxo_set = UTXOSet(blockchain)

    utxo_tx = UTXOTx(args.From, args.to, args.amount, utxo_set)
    coin_base_tx = CoinBaseTx(blockchain.address)
    blockchain.add_block([coin_base_tx, utxo_tx])
    utxo_set.update(blockchain.last_block)

    print('Done!')
コード例 #15
0
def load_keys():
    if wallet.load_keys():
        global blockchain
        blockchain = BlockChain(wallet.public_key, port)
        response = {'public_key': wallet.public_key, 'private_key': wallet.private_key,
                    'funds': blockchain.get_balance()}
        return jsonify(response), 201
    else:
        response = {'message': 'Loading keys failed'}
        return jsonify(response), 500
コード例 #16
0
ファイル: cli.py プロジェクト: ray-qwer/pseudo_bitcoin
def cli_check_balance(Addr):
    blk_chain = BlockChain()
    if not blk_chain.Verify_Block_Chain():
        print("Your database may be damaged. Cannot open this file.")
        return
    ws = WS.wallets()
    wallet = ws.get_wallet_by_addr(Addr)

    amount = blk_chain.FindBalance(wallet._hashPublicKey)
    print("Address: {addr}\nAmount: {a}".format(addr=Addr, a=amount))
コード例 #17
0
ファイル: main.py プロジェクト: mattjegan/matecoin
def main():
    my_wallet = '9733fe2ede889ea39c077b3aed5485e22f4919755bcd1cb46c245a3b0293d93f3af40bd8c6644cd22c07df8a0b270a54086e060e44f79be301b0a1c73de624f4'
    bc = BlockChain()

    try:
        for i in range(1000):
            bc.mineBlock(my_wallet)
    except KeyboardInterrupt:
        pass
    bc.save()
コード例 #18
0
ファイル: miner_client.py プロジェクト: Mechasparrow/Sparkles
def block_fanagle(ws, transaction):
    print ("BLOCK FANAGLE")
    global blockchain

    while True:

        blockchain_length = len(blockchain)

        prev_block = blockchain.find_by_index(str(blockchain_length - 1))

        print (prev_block)

        try:
            prev_blk_data = json.loads(prev_block.data)
            prev_blk_transaction = Transaction.from_json(prev_blk_data[0])

            if (prev_blk_transaction == transaction):
                print ("SAME TRANSACTION. CANCEL MINING")
                break
            else:
                print ("ITS Fine we can still keep going")

        except json.decoder.JSONDecodeError:
            print ("weird block")


        block_return = [None]

        block_thread = Thread(target=create_block, args = (block_return, transaction))
        block_thread.start()

        block_thread.join()

        print (block_return[0])

        block = block_return[0]

        blockchain_blocks = list(blockchain.blocks)

        if (blockchain_length < len(blockchain)):
            print ("NEW BLOCK WAS RECIEVED!")

        blockchain_blocks.append(block)

        alt_blockchain = BlockChain(blockchain_blocks)

        if (alt_blockchain.validate_chain() == True):
            print ("done mining. Sending block...")
            block_message_json = block_message(block)

            ws.send(block_message_json)
            break
        else:
            print ("REMINE")
            continue
コード例 #19
0
ファイル: miner_client.py プロジェクト: Mechasparrow/Sparkles
def on_message(ws, message):
    message_decoded = json.loads(message)

    global blockchain

    if (message_decoded['message_type'] == 'transaction'):
        transaction_json = message_decoded['data']
        transaction = Transaction.from_json(transaction_json)

        if (transaction.validate_transaction() == True):
            block_f = Thread(target=block_fanagle, args = (ws, transaction))
            block_f.start()

    elif (message_decoded['message_type'] == "sync_request"):
        print ("blockchain requested")

        ws.send(blockchain_upload_message())

    elif (message_decoded['message_type'] == "blockchain_upload"):
        recieved_blockchain = BlockChain.from_json(message_decoded['blockchain'])

        new_blockchain = BlockChain.sync_blockchain(blockchain, recieved_blockchain)

        blockchain = new_blockchain

        blockchain.save_blockchain('./blockchain/blockchain.json')

        print ()

    elif (message_decoded['message_type'] == 'new_block'):
        print ("new block!")

        block_json = message_decoded['block']
        try:
            block = Block.from_json(block_json)

            if (block.valid_block() == True):

                temp_blocks = copy.copy(blockchain.blocks)

                temp_blocks.append(block)
                temp_block_chain = BlockChain(temp_blocks)

                if (temp_block_chain.validate_chain() == True):
                    print ("valid new blockchain")
                    blockchain.blocks.append(block)
                else:
                    print("invalid chain. Not updated")
            else:
                print ("invalid block")
        except json.decoder.JSONDecodeError:
            print ("invalid block")

        blockchain.save_blockchain('./blockchain/blockchain.json')
コード例 #20
0
ファイル: main.py プロジェクト: czhc/blockchain-100
def main():
    blockchain = BlockChain()
    blockchain.generateBlock("Hello World!")
    blockchain.generateBlock(3)
    blockchain.generateBlock({"account": 123123, "mount": 100})

    print(blockchain.printBlockChain())
    print("Chain valid?" + str(blockchain.isChainValid()))
    blockchain.save()

    blockchain.chain[1].data = "Corrupt data"
    print(blockchain.printBlockChain())
    print("Chain valid?" + str(blockchain.isChainValid()))
    blockchain.save()

    test = BlockChain()
    test.open()
    print(test.printBlockChain())
    print("Chain valid? " + str(test.isChainValid()))
    test.save()
コード例 #21
0
def postjson():

    block = {}
    if len(blockchain) != 0:

        name = request.form['name']
        content = request.form['content']
        name = request.form['name']
        content = request.form['content']
        block = BlockChain(blockchain[len(blockchain) - 1]['hash'], name,
                           content, blockchain)
    else:

        name = request.form['name']
        content = request.form['content']
        #Bloco Genesis
        block = BlockChain(0, name, content, blockchain)

    blockchain.append(block)
    return jsonify(block)
コード例 #22
0
ファイル: miner_client.py プロジェクト: Mechasparrow/Sparkles
def load_blockchain():

    try:
        blockchain = BlockChain.load_blockchain('./blockchain/blockchain.json')
    except FileNotFoundError:
        blocks = []
        genesis_block = Block.load_from_file('./genesis_block/genesis_block.json')
        blocks.append(genesis_block)
        blockchain = BlockChain(blocks)

    return blockchain
コード例 #23
0
ファイル: cli.py プロジェクト: ray-qwer/pseudo_bitcoin
def cli_sending(From, To, amount):
    blk_chain = BlockChain()
    if not blk_chain.Verify_Block_Chain():
        print("Your database may be damaged. Cannot open this database.")
        return
    tx = transaction.NewUTXOTransaction(From, To, amount, blk_chain)
    if tx == None:
        print("Error: not enough funds")
        return
    blk_chain.add_block(tx)
    print("From: {f}\nTo: {t}\nAmount: {a}".format(f=From, t=To, a=amount))
コード例 #24
0
    def __init__(self):
        self.blockchain = BlockChain(consts.difficulty)
        self.blockchain.create_genesis_block()

        self.private_key = rsa.generate_private_key(public_exponent=consts.rsa_public_exponent,
                                                    key_size=consts.rsa_key_size, backend=default_backend())
        # Storing public key as serialized string
        self.public_key = self.private_key.public_key().public_bytes(encoding=serialization.Encoding.PEM,
                                                                     format=serialization.PublicFormat.SubjectPublicKeyInfo).decode(
            'ascii')
        self._peers = {}
        self.host = ''
コード例 #25
0
class Main:
    if __name__ == '__main__':
        chain = BlockChain()
        chain.add_new_transaction(["Hamdaan ", 45, "Jason"])
        chain.mine()
        chain.add_new_transaction(["Jason", 45, "Jackson"])
        chain.mine()
        chain.add_new_transaction(["Missi", 45, "ssippi"])
        chain.mine()

        for i in chain.chain:
            print(i.data, i.timestamp)
コード例 #26
0
ファイル: main.py プロジェクト: ShantnuS/MiniBlockchain
def main():
    print("Creating Block...")
    blockchain = BlockChain()
    blockchain.add_to_chain("Hello!")
    blockchain.add_to_chain("Bye!")

    for block in blockchain.chain:
        print(
            str(block.index) + ": " + block.data + " --- " +
            str(block.block_hash) + " --- " + str(block.previous_hash))

    print(blockchain.verify_chain())
コード例 #27
0
def getblance(args):
    args_dict = vars(args)
    account = args_dict['account']

    bc = BlockChain()
    utxos = bc.find_utxo(account)
    blance = 0

    for out in utxos:
        blance += out.amount

    print('Blance of "{}": {}'.format(account, blance))
コード例 #28
0
def load_blockchain(): ## Function for loading the blockchain from local copy
    try:
        blockchain = BlockChain.load_blockchain('./blockchain/blockchain.json')
        if (blockchain.validate_chain()):
            print ("BlockChain is valid")
    except FileNotFoundError:
        blocks = []
        genesis_block = Block.load_from_file('./genesis_block/genesis_block.json')
        blocks.append(genesis_block)
        blockchain = BlockChain(blocks)

    return blockchain
コード例 #29
0
ファイル: miner.py プロジェクト: ahmedrachid/BlockChain
def main():

    global bc
    global PORT

    if len(sys.argv)!=3:
        print("Usage: python miner.py port miner_port")

    else:
        try:
            bc = BlockChain()
            print("blockcain",bc)

            PORT = int(sys.argv[1])
            PARENT_PORT = int(sys.argv[2])
            PEERS = {PORT:None}


            print('Launching miner node with port {}'.format(PORT))
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((HOST, PORT))

            ps = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # We do have a parent node, establish connection
            if PARENT_PORT != PORT :
                print('Connecting to parent node with port {}'.format(PARENT_PORT))

                ps = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                ps.connect((HOST, PARENT_PORT))

                send_mining_port(ps, PORT)
                PEERS[PARENT_PORT] = ps



            print('Waiting for incoming connections from child miners')
            c = 1
            s.listen(5)

            while True:
                conn, addr = s.accept()
                #import pdb;pdb.set_trace()
                message = read_message(conn)
                #handle_message(PEERS, PORT, message)
                threading.Thread(target=handle_message(PEERS, PORT, message,conn))
                c = c + 1

        except KeyboardInterrupt:
            print('Interrupt signal received, closing connections and freeing resources')
            s.close()
            if ps is not None:
                ps.close()
            sys.exit()
コード例 #30
0
def send(args):
    args_dict = vars(args)
    from_account = args_dict['from']
    to_account = args_dict['to']
    amount = int(args_dict['amount'])

    bc = BlockChain()
    tx = UTXOTransaction(from_account, to_account, amount, bc)
    cb_tx = CoinbaseTx(from_account)
    tx_list = [cb_tx, tx]
    bc.mine_block(tx_list)
    print('Success!')