Esempio n. 1
0
def add_transaction(to, amount):
    t = Transaction(
        address,
        to,
        amount,
        '',
        public_key.dumps(),
    )
    t.sign = sign_message(private_key.d, private_key.n, t.get_message())

    r = requests.post(b_url + '/add_transaction', json=t.to_dict())
    print(r.text)
 def copy_blocks(self, list_transactions):
     for transactions in list_transactions[1:]:
         self.pending_transactions = [
             Transaction(transactions[0]['name'], transactions[0]['cpf'])
         ]
         block = Block(self.pending_transactions, self.blockchain[-1].hash)
         self.pending_transactions = []
         self.blockchain.append(block)
Esempio n. 3
0
def add_block():
    t = get_transactions()
    t = [Transaction.from_dict(x) for x in t]
    last = get_last_block()
    b = Block(last['id'] + 1, str(datetime.now()), t, 0)
    for nonce in range(0, 1000000):
        b.nonce = nonce
        block_hash = b.get_hash(last['hash'])
        if block_hash.startswith('0' * 4):
            r = requests.post(b_url + '/add_block', json=b.to_dict())
            print(r, r.text)
Esempio n. 4
0
def test_doc():
    node = Node('matt')
    #import pdb;pdb.set_trace()
    gb, hash = node.process_txns([])
    assert hash[0] == '0'

    # Pay Fred .1
    txn = Transaction(
        [Amount(1, 'matt')],
        [Amount(.9, 'matt'), Amount(.1, 'fred')])
    b2, h2 = node.process_txns([txn])
    assert h2[0] == '0'  #.startswith('1')
    def build_block(self):
        if len(self.pending_transactions) == 0:
            raise Exception(
                'build_block: no transactions to build a block from')

        if uniform(0, 1) > PROBABILITY_TO_CORRUPT:
            block = Block(self.pending_transactions, self.blockchain[-1].hash)
            self.pending_transactions = []
            self.blockchain.append(block)
        else:
            self.pending_transactions = [
                Transaction('corrupted package', 'no id')
            ]
            block = Block(self.pending_transactions, '0' * 64)
            self.pending_transactions = []
            self.blockchain.append(block)
Esempio n. 6
0
    def run(self, sim):
        # The node that this event is running on
        me = sim.nodes[self.node_id]

        # Generate a random amount not greater than current node's balance
        trans_amt = me.coins * random.uniform(0, 1)

        # Find a random receiver who will receive the coins in the transaction
        all_but_me = list(set(sim.nodes) - set([me]))
        receiver = random.choice(all_but_me)

        # Update the coins of both sender & receiver
        me.coins -= trans_amt
        receiver.coins += trans_amt

        # Add transaction to current node's transaction list
        new_trans = Transaction(
            sim.trans_id,
            me.id,
            receiver.id,
            trans_amt
        )

        sim.trans_id += 1
        me.transactions[new_trans.id] = new_trans

        # Create a next transaction event for this node
        sim.events.put(TransactionGenerate(
            me.id,
            me.id,
            self.run_at,
            self.run_at + sim.transaction_delay()
        ))

        # Create next transaction events for neighbours
        for peer in me.peers:
            t = sim.latency(me, peer, msg_type="transaction")

            sim.events.put(TransactionReceive(
                new_trans,
                peer.id,
                me.id,
                self.run_at,
                self.run_at + t
            ))
Esempio n. 7
0
def processInput(data):
    dataList = data.split(',')
    if dataList[0] == 'transfer':
        # Update getBalance to get balance
        receiver = int(dataList[1])
        amount = int(dataList[2])
        amountBefore = getBalance(PID)
        if amountBefore >= amount and PID != receiver:
            transaction_log.append(Transaction(PID, receiver, amount))
            print("SUCCESS")
            print("Balance before: $" + str(amountBefore))
            print("Balance after: $" + str(amountBefore - amount))
        else:
            # Run Paxos
            sendPrepare()

    elif dataList[0] == 'balance':
        if len(dataList) == 1:
            dataList.append(str(PID))
        print("Balance: $" + str(getBalance(int(dataList[1]))))
Esempio n. 8
0
 def new_transaction(self, sender, recipient, amount):
     self.current_transactions.append(Transaction(sender, recipient,
                                                  amount))
     block_index = 1 if self.last_block is None else self.last_block.index + 1
     return block_index
Esempio n. 9
0
def processMessage(pid, data):
    global BALLOT_NUM
    global ACCEPT_NUM
    global ACCEPT_VAL
    global MAX_ACK_NUM
    global MAX_ACK_VAL
    global ACK_COUNT
    global ACCEPT_COUNT
    print('Message from client ' + str(pid))
    data = json.loads(data)
    if data['type'] == 'prepare':
        ballotNum = BallotNum.load(data['ballot'])
        if ballotNum.isHigher(BALLOT_NUM):
            BALLOT_NUM = ballotNum
            val = []
            for aval in ACCEPT_VAL:
                val.append(aval.toJSON())
            data = {
                'type': 'ack',
                'ballot': BALLOT_NUM.toJSON(),
                'seq_num': chain.getLastSeqNum(),
                'accept_ballot': ACCEPT_NUM.toJSON(),
                'accept_val': val
            }
            message = json.dumps(data)
            threading.Thread(target=sendMessage,
                             args=(
                                 message,
                                 pidConn[pid],
                             )).start()
            print('Ack message sent to client ' + str(pid))

    elif data['type'] == 'ack':
        #  check for majority and send accept to followers
        incrementAckCount()
        acceptBallot = BallotNum.load(data['accept_ballot'])
        acceptVal = data['accept_val']
        if len(acceptVal) != 0 and acceptBallot.isHigher(MAX_ACK_NUM):
            MAX_ACK_NUM = acceptBallot
            MAX_ACK_VAL = acceptVal[:]

        time.sleep(5)
        if ACK_COUNT >= MAJORITY:
            log = []
            if len(MAX_ACK_VAL) != 0:
                log = MAX_ACK_VAL[:]
            else:
                for val in transaction_log:
                    log.append(val.toJSON())

            data = {
                'type': 'accept',
                'ballot': BALLOT_NUM.toJSON(),
                'seq_num': SEQ_NUM,
                'value': log
            }
            message = json.dumps(data)
            # for client in CLIENTS:
            threading.Thread(target=sendMessage,
                             args=(
                                 message,
                                 pidConn[pid],
                             )).start()
            print('Accept message sent to followers')
            ACK_COUNT = 0

    elif data['type'] == 'accept':
        ballotNum = BallotNum.load(data['ballot'])
        if ballotNum.isHigher(BALLOT_NUM):
            BALLOT_NUM = ballotNum
            ACCEPT_NUM = ballotNum
            val = []
            for aval in transaction_log:
                val.append(aval.toJSON())
            ACCEPT_VAL = [Transaction.load(val) for val in data['value']]
            data = {
                'type': 'accepted',
                'ballot': BALLOT_NUM.toJSON(),
                'seq_num': chain.getLastSeqNum(),
                'value': val
            }
            message = json.dumps(data)
            threading.Thread(target=sendMessage,
                             args=(
                                 message,
                                 pidConn[pid],
                             )).start()
            print('Accepted message sent to client ' + str(pid))

    elif data['type'] == 'accepted':
        # do stuff and relay message to leader
        incrementAcceptCount()
        for aval in data['value']:
            transaction_log.append(Transaction.load(aval))

        time.sleep(5)
        if ACCEPT_COUNT >= MAJORITY:
            val = []
            for aval in transaction_log:
                val.append(aval.toJSON())
            data = {
                'type': 'commit',
                'ballot': BALLOT_NUM.toJSON(),
                'seq_num': SEQ_NUM,
                'value': val
            }
            message = json.dumps(data)
            # for client in CLIENTS:
            threading.Thread(target=sendMessage,
                             args=(
                                 message,
                                 pidConn[pid],
                             )).start()
            print('Decide message sent to followers')
            ACCEPT_COUNT = 0
            chain.printChain()

    elif data['type'] == 'commit':
        print('Decide message from leader')
        val = []
        for aval in data['value']:
            val.append(Transaction.load(aval))
        chain.append(data['seq_num'], val)
        transaction_log.clear()
        chain.printChain()
Esempio n. 10
0
from block import Block, Transaction
from blockchain import Blockchain

bc = Blockchain(difficulty=4)

bc.add_pending(Transaction('my_address', 'your_address', 5.0))
bc.add_pending(Transaction('your_address', 'my_address', 2.0))
bc.add_pending(Transaction('your_address', 'other_address', 3.0))

bc.build_block()

for block in bc.blockchain:
    print(block)

for address in ['my_address', 'your_address', 'other_address']:
    print(address, bc.check_balance(address))
Esempio n. 11
0
 def add_vote(self, vote):
     candidate_position = self.candidate_number[vote['candidate']]
     transaction = Transaction(vote['name'], vote['cpf'])
     self.blockchain_candidates[candidate_position].add_pending(transaction)
     self.blockchain_candidates[candidate_position].build_block()
Esempio n. 12
0
def add_transaction():
    data = request.json
    t = Transaction.from_dict(data)
    transaction_pool.append(t)
    return "OK"
Esempio n. 13
0
     "-------------------Simple Bank Transaction Block Chain-----------------------------"
 )
 bank = BlockChain()
 while (True):
     print("1. Send Money")
     print("2. Mine Now")
     print("3. Check Account")
     print("4. All Transaction.")
     print("5. Exits")
     try:
         choice = int(input())
         if choice == 1:
             from_add = input("Enter your account/address. ")
             to_add = input("Enter account whom you want to send money. ")
             ammount = int(input("Enter the ammount: "))
             bank.createTransaction(Transaction(from_add, to_add, ammount))
             print("Thank you. Your Transaction is created..")
             print("__________________________________")
         elif choice == 2:
             your_add = input("Enter your account/address. ")
             bank.minePendingTransatin(your_add)
             print("Thankyou you will get credted for mining reward soon..")
             print("___________________________________")
         elif choice == 3:
             your_add = input("Enter your account/address. ")
             print(your_add, " current balance is ",
                   bank.getBalance(your_add))
             print("___________________________________")
         elif choice == 4:
             bank.transactionHistory()
         elif choice == 5:
Esempio n. 14
0
 def transction(self, sender, receiver, amount):
     """交易"""
     transaction = Transaction(sender, receiver, amount)
     return self._new_block([transaction])
Esempio n. 15
0
def test_transaction():
    t = Transaction([Amount('matt', 5)],
                    [Amount('matt', 1),
                     Amount('fred', 4)])
    assert t.todict() == {'inputs': [{'amount': 5, 'uuid': 'matt'}],
          'outputs': [{'amount': 1, 'uuid': 'matt'}, {'amount': 4, 'uuid': 'fred'}]}