コード例 #1
0
def listcoins():
    newBlockChain = BlockChain()
    newBlockChain.FileTo()
    AccountName = '66053664cae16a575ea087ce17c2b400326c366d64580818f14db15b27dbdf86'
    coinList = AccountAllCoins(AccountName=AccountName, BlockChain=newBlockChain)
    for coin in coinList:
        print(coin)
コード例 #2
0
def listtarns():
    AccountName = '66053664cae16a575ea087ce17c2b400326c366d64580818f14db15b27dbdf86'
    newBlockChain = BlockChain()
    newBlockChain.FileTo()
    tranList = AccountAllTrans(AccountName, newBlockChain)
    for tran in tranList:
        print(tran)
コード例 #3
0
def MingBlock(AccountName):
    blockChainObject = BlockChain()
    blockChainObject.FileTo()
    God = CreateAccount()
    God.FileTo()
    ex_mesg = ""
    global newBlock
    global flag
    flag = 1
    newBlock = MiningOneBlock(AccountName, blockChainObject, God, ex_mesg)
    print("new block succeed!!")
    flag = 0
コード例 #4
0
def miner():
    AccountName = miner[0]
    while True:
        newblockChain = BlockChain()
        newblockChain.FileTo()
        God = CreateAccount()
        God.FileTo()
        ex_mesg = ""
        newBlock = MiningOneBlock(AccountName, newblockChain, God, ex_mesg)
        newblockChain.AddBlockToChain(tx_list=[], newBlock=newBlock)
        newblockChain.ToFile()
        print('已完成')
コード例 #5
0
def create_chain_from_dump(chain_dump):
    """
        Uses a chain dump to (re)create a BlockChain instance
    """
    chain = BlockChain()
    for idx, block_data in enumerate(chain_dump):
        block = Block(block_data["index"], block_data["transactions"],
                      block_data["timestamp"], block_data["previous_hash"])
        proof = block_data["hash"]
        if idx > 0:
            # not the genesis block, so pls verify
            added = chain.add_block(block, proof)
            if not added:
                raise Exception("Tampered blockchain dump!")
        else:
            # genesis block, just add
            chain.chain.append(block)

    return chain
コード例 #6
0
def DomMining(accountname):
    global flag
    flag = 1
    while True:
        ThreadMining = threading.Thread(target=MingBlock, args=(accountname,))
        ThreadPool = threading.Thread(target=TransPool)
        ThreadMining.start()
        ThreadPool.start()
        ThreadPool.join()
        newBlock.insertTrans(tx_list=pool)
        BlockChain().AddBlockToChain(newBlock=newBlock)
        print('connect to chain')
コード例 #7
0
def main():
    for i in range(9):
        blk = mine_a_block(BlockChain.get_last_block())
        print(str(blk))
        BlockChain.add_block(blk)
        broadcast_block(blk)
コード例 #8
0
ファイル: interfaces.py プロジェクト: govind11/blockchain
'''
@author: Govind Karmakar
@date: 3 Jun'18
'''
from block import BlockChain as BlockChain
from flask import Flask, request
import requests
import time

app = Flask(__name__)

# The node's copy of blockchain
blockChain = BlockChain()


@app.route('/newTransaction', methods=['POST'])
def new_transaction():
    txData = request.get_json()
    requiredFields = ['author', 'content']
    for field in requiredFields:
        if not txData.get(field):
            return 'Invalid transaction data.', 404
    txData['timestamp'] = time.time()
    blockChain.add_new_transaction(txData)
    return 'Succss', 201


@app.route('/chain', methods=['GET'])
def get_chain():
    chainData = []
    for block in blockChain.chain:
コード例 #9
0
if __name__ == "__main__":
    # Reading the client configurations
    f = open(sys.argv[2], 'r')
    configList = f.readlines()
    config = configList[PID - 1].strip('\n').split(',')
    if len(config) != 3:
        print("Incorrect configuration")
        sys.exit()
    IP = config[0]
    PORT = int(config[1])
    BALANCE = int(config[2])

    # Creating server to listen for connections
    server_thread = threading.Thread(target=createServer, args=(PID, ))
    server_thread.start()

    # Connect to existing clients
    for i in range(1, PID):
        clientConfig = configList[i - 1].strip('\n').split(',')
        connectToClient(i, clientConfig[0], int(clientConfig[1]))
    print("#clients connected: ", len(CLIENTS))
    print("Balance: $" + str(BALANCE))

    # Listen for client inputs
    chain = BlockChain(BALANCE)

    while True:
        message = input()
        processInput(message)
コード例 #10
0
class Peer(object):

    UTXO = []  #unspent txn pool
    sim_time = time.time()  #this is the global time in seconds
    pij = np.random.uniform(10,
                            500)  #fixed prop delay, choosen from uniform dist.
    dij = 96 * 1000  #bits
    genesisBlock = Block([], None)  #initialize a genesis block for the nw
    genesisBlock.blkid = '00000000000000000000000000000000'
    globalChain = BlockChain(
        genesisBlock)  #initialize a blockchain with genesis block
    all_peers = []  #list of all the peers in nw
    txn_interval_mean = 10  #avg. time bw two txns in ms
    mean_Tk = 3000  #from my observation of 3 sec avg. prop delay on nw
    AVG_BLK_ARR_TIME = len(all_peers) * mean_Tk  #no. of peers*max_delay

    def __init__(self, name, peer_type, env):
        self.name = name
        self.type = peer_type
        self.unspentTransactions = []
        self.balance = 100
        self.lasttransactiontime = self.sim_time
        self.listofBlocks = [self.genesisBlock]
        self.lastBlockHeard = self.genesisBlock  #default time of genesis block
        self.lastBlockArrTime = self.sim_time
        self.localChain = self.globalChain
        self.Tk_mean = float(np.random.poisson(
            self.AVG_BLK_ARR_TIME,
            1)[0])  #average arrival time of a block proportion to cpu power
        self.env = env
        self.connections = dict()
        self.txn_queue = {}
        self.blk_queue = {'00000000000000000000000000000000': self.sim_time}

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, self.name)

    def connect(self, other):
        if not self.is_connected(other):
            print "%r connecting to %r" % (self, other)
            self.connections[other] = Connection(self.env, self, other)
            if not other.is_connected(self):
                other.connect(self)

    def is_connected(self, other):
        return other in self.connections

    def computeDelay(self, other, msg):
        size = 0
        if isinstance(msg, Block):
            size = 8 * pow(10, 6)  #bits

        delay = self.pij
        cij = 5 * pow(10, 3)  #link speed bits per ms

        if self.type == other.type == 'fast':
            cij = 100 * pow(10, 3)

        prop = float(size) / cij
        queing = np.random.exponential((float(self.dij) / cij), 1)[0]

        delay += prop + queing  #in ms
        return float(delay) / 1000

    def broadcast(self, msg, delay):  #broadcast msg to all other peer
        #ensure there are no loops by checking that the msg has not already been received

        #broadcast rules if a msg is a txn
        if isinstance(msg, Transaction):
            for other in self.connections:
                if not (other == self):
                    if msg.txid not in other.txn_queue.keys():
                        other.unspentTransactions.append(msg)
                        arrival_time = delay + self.computeDelay(other, msg)
                        #other.lasttransactiontime = arrival_time
                        other.txn_queue[msg.txid] = arrival_time
                        other.broadcast(msg, arrival_time)

        #broadcast a block
        else:
            for other in self.connections:
                if not (other == self):
                    if msg.blkid not in other.blk_queue.keys():
                        #adding any block heard by a peer
                        print "sending block.. " + str(
                            msg.blkid) + " to " + str(other) + str(
                                other.blk_queue.keys())
                        arrival_time = delay + self.computeDelay(other, msg)
                        other.blk_queue[msg.blkid] = arrival_time

                        #detect fork here by checking the arrival time and lastblock time
                        flag = other.detectFork(msg, arrival_time)  #boolean
                        if not flag:
                            other.updateChain(msg, arrival_time)
                            other.broadcast(msg, arrival_time)

                        if other.name == 'p1':
                            print "Block heard by p1"
                            print other.blk_queue
                            print "----------Local Chain for p1--------"
                            #print other.unspentTransactions
                            other.localChain.displayChain()
        return

    def detectFork(self, msg, arrival_time):
        print "Two new blocks received...detecting fork.."
        #same parentlink with different arrival times, different block, resolve fork with latest

        if (msg.parentlink == self.localChain.getLast().parentlink) and (
                msg.blkid != self.localChain.getLast().blkid):
            print "Fork detected....at peer: " + str(self.name)

            if arrival_time > self.lastBlockArrTime:
                self.listofBlocks.append(
                    msg)  #select the chain with first arrived block
                self.lastBlockHeard = msg
                self.lastBlockArrTime = arrival_time
                self.broadcast(msg, arrival_time)
                return True  #just add the new block to the list and broadcast
            else:
                self.resolveFork(msg, arrival_time)  #extend with msg block
                self.listofBlocks.append(
                    msg)  #select the chain with first arrived block
                self.broadcast(msg, arrival_time)

        return False

    def resolveFork(self, msg, arrival_time):
        #here we remove the last block from the localchain and add msg
        self.localChain.removeLast()
        self.localChain.addBlock(msg)
        return

    def updateChain(self, newBlock, arrival_time):
        if newBlock == self.localChain.getLast():
            return
        newBlock.parentlink = self.localChain.getLast().blkid
        self.listofBlocks.append(newBlock)
        self.localChain.addBlock(newBlock)
        self.lastBlockArrTime = arrival_time
        return

    def generateTransaction(self):
        receiver = self
        for other in self.connections:
            #select a random peer to whom to pay the coins
            if random.randint(0, 1) and other.name != 'PeerServer':
                receiver = other
                break

        sender = self.name

        if self.balance < 1:
            print "insufficient balance"
            return

        coins = random.randint(1, self.balance)
        #update balance

        tx = Transaction(self.name, receiver, coins)
        self.lasttransactiontime = time.time()
        #add the new transaction to the unspent pool
        self.UTXO.append(tx)
        self.unspentTransactions.append(tx)

        self.broadcast(tx, tx.timestamp)
        return

    def updateUTXO(self):
        # we need to make all the transactions in the chain marked spend in UTXO, local txn list
        # update the balance for all the nodes
        return

    def createBlock(self):
        #check to see if it has number of unspent transactions >= required block size
        #select the transactions sorted on timestamp
        self.updateUTXO()

        if len(self.unspentTransactions) == 0:
            #check in the UTXO
            self.unspentTransactions.extend(self.UTXO)
            if len(self.unspentTransactions) == 0:
                #print 'There are no unspent transactions'
                return
        #add the transactions to the block, max 10

        lisofTransactions = self.unspentTransactions[:10]
        self.unspentTransactions = self.unspentTransactions[10:]

        newBlock = Block(lisofTransactions, self)
        newBlock.parentlink = self.lastBlockHeard.blkid
        for i in self.listofBlocks:
            if newBlock.blkid == i.blkid:
                self.unspentTransactions.extend(newBlock.transactions)
                #print "mining a block already present"
                return

        print str(self) + " is mining...."
        self.listofBlocks.append(newBlock)
        self.blk_queue[newBlock.blkid] = newBlock.timestamp
        self.localChain.addBlock(newBlock)
        self.lastBlockArrTime = newBlock.timestamp
        print "block successfully created by " + str(self) + " " + str(
            newBlock)
        print "linked to " + str(newBlock.parentlink)
        self.broadcast(newBlock, newBlock.timestamp)

        return
コード例 #11
0
ファイル: web.py プロジェクト: jnovikov/mini_blockchain_42
from flask import Flask, jsonify, request
from datetime import datetime

from block import BlockChain, Block, Transaction

app = Flask(__name__)

genesis = Block(0, str(datetime.now()), [], 0)
genesis.hash = 128 * '0'
blockchain = BlockChain([
    genesis,
])
transaction_pool = []


@app.route('/')
def index():
    return jsonify(blockchain.to_dict())


@app.route('/last_block')
def get_last_block():
    return jsonify(blockchain.last_block.to_dict())


@app.route('/add_transaction', methods=["POST"])
def add_transaction():
    data = request.json
    t = Transaction.from_dict(data)
    transaction_pool.append(t)
    return "OK"
コード例 #12
0
from block import Block
from block import BlockChain
from block import Transaction

if __name__ == "__main__":
    print(
        "-------------------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. ")
コード例 #13
0
# miner id generation ===========================================================
app = Flask(__name__)
myport = sys.argv[1]       # we save the port num from the command line
myaddr = "http://127.0.0.1:" + myport
myname = genName()
print("***** NODE init, I am miner {} *****".format(myname))
if (len(sys.argv) > 2):
    SEED_ADDRESS = sys.argv[2]
    print("seed is " + SEED_ADDRESS)

# global vars, together with their locks ========================================
# Very Important
# TODO currently all operation is LOCK FREE, need add lock in the future
bc_lock = Lock()
mychain = BlockChain(myname)

pool_lock = Lock()
mypool = ModelPool()            # candidate local models

peers_lock = Lock()
peers = set()

status_lock = Lock()
mystatus = False

intr = Intrpt()

mypara = None
seedWeight = None
コード例 #14
0
def msg_handler(msg, data=None):
    if msg == EnumMsgType.NEW_BLK:
        BlockChain.add_block(data)