示例#1
0
def newBlockchain(address):
    if Blockchain().getBestHeight >= 0:
        print("Error: Blockchain already exists")
        return

    if not wallet.validateAddress(address.encode()):
        print("Error: Address is not valid")
        return

    miner = Miner(address.encode())
    miner.mine_block()
    print("New blockchain created")
示例#2
0
def handleVersion(msg):
    # print("Handling version")
    version = decodeMsg(msg)
    print(version)
    localBestHeight = Blockchain().getBestHeight()
    remoteBestHeight = version['bestHeight']
    if localBestHeight < remoteBestHeight:
        sendGetBlocks(version['addrFrom'])
    elif localBestHeight > remoteBestHeight:
        sendVersion(version['addrFrom'])

    if version['addrFrom'] not in knownNodes:
        knownNodes.append(version['addrFrom'])
        sendAddr(version['addrFrom'])
示例#3
0
def handleGetData(msg):
    getdata = decodeMsg(msg)
    # print("Handling getdata from %s" % getdata['addrFrom'])

    if getdata['type'] == b'block':
        block = Blockchain().getBlock(getdata['id'])
        if not block: return

        sendBlock(getdata['addrFrom'], block)

    elif getdata['type'] == b'tx':
        txID = getdata['id']
        if txID not in miner.mempool: return

        sendTX(getdata['addrFrom'], miner.mempool[txID])
示例#4
0
def handleBlock(msg):
    blc = decodeMsg(msg)
    # print("Handling block from %s" % blc['addrFrom'])
    block = decodeBlock(blc['block'])
    addrFrom = blc['addrFrom']

    if addrFrom in blocksInTransit:
        try:
            blocksInTransit[addrFrom].remove(block.hash)
        except ValueError:
            print("Got block that wasn't requested.")
            return
    else:
        print("Got block that wasn't requested")
        return

    Blockchain().addBlock(block)
    print("Added block %s" % block.hash.hex()[:14])

    if len(blocksInTransit[addrFrom]) > 0:
        sendGetData(addrFrom, b'block', blocksInTransit[addrFrom][0])
    else:
        del blocksInTransit[addrFrom]
        UTXOSet().reindex()
示例#5
0
文件: app.py 项目: parksWill/pychain
import hashlib
from time import time
from textwrap import dedent
from flask import Flask, jsonify, request
import logging
import logging.config
from pychain.blockchain import Blockchain

# Instantiate our Node
app = Flask(__name__)

# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace("-", "")

# Instantiate the Blockchain
blockchain = Blockchain()


# Instantiate Logger
def setup_logging(default_path="../res/logging.yaml",
                  default_level=logging.INFO,
                  env_key="LOG_CFG"):
    path = default_path
    value = os.getenv(env_key, None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path, "rt") as f:
            try:
                config = yaml.safe_load(f.read())
                logging.config.dictConfig(config)
示例#6
0
def pc():
    return Blockchain()
示例#7
0
def sendVersion(address):
    # print("Sending version")
    command = b'version'
    version = p2p.version(nodeAddress, nodeVersion,
                          Blockchain().getBestHeight())
    sendPayload(address, command, version)
示例#8
0
def startServer(mineAddr):
    global knownNodes, miner
    print("My host: %s" % nodeAddress)
    miner = Miner(mineAddr)

    print("My mining address %s" % toStr(miner.address))

    nodes = discoverNodes()
    for name in nodes:
        address = gethostbyname(name)
        if address != nodeAddress:
            knownNodes.append(address)

    print("Known nodes: %s" % str(knownNodes))

    sr = p2p.SocketReader(nodeAddress)
    sr.setMsgHandlers(msgHandlers)
    sr.start()
    bc = Blockchain()

    #done = False
    #while not done:
    while 1:
        start = time.time()
        bestHeight = bc.getBestHeight()
        # generate empty blocks to seed the miners' wallets
        if bestHeight < 5:
            new_block = miner.mine_block()
            broadcast_block(new_block)
        # for blocks 5-10, generate random txs. These will get broadcast
        # across the network (randomly) and eventually fill the mempool.
        # A full mempool will trigger the mining of a new block.
        elif bestHeight < 10:
            if bestHeight == 5:
                print("My balance after 5 blocks: %3.3f" %
                      UTXOSet().get_balance(address=miner.address))
            # Produce a tx every ~2-3 seconds
            time.sleep(random.random() + 2)
            rand_tx = create_random_tx()
            if rand_tx:
                miner.add_txs([rand_tx])
                broadcast_tx(rand_tx)

            # NOTE: We DO want to mine blocks in the miner's thread
            if len(miner.mempool) >= 2:
                # HACK: For testing, gives the other nodes a chance to
                # win the next block
                time.sleep(1.5)
                new_block = miner.mine_transactions()
                broadcast_block(new_block)
                print_balances()
        else:
            pubKeyHash = base58.decode(miner.address)[1:-4]
            for i, block in enumerate(BlockExplorer().iter_blocks()):
                proof = pow.ProofOfWork(block)
                if not proof.validate():
                    print("Error! This block could not be validated")
                #print(json.dumps(block.toDict(), indent=2)
                mined_block = ' no'
                for tx in block.transactions:
                    if tx.isCoinbase() and tx.outDict[0].isLockedWithKey(
                            pubKeyHash):
                        mined_block = ' yes'
                print(block.hash.hex()[:14] + mined_block)
            # pubKeyHash = base58.decode(miner.address)[1:-4]
            # print("My unspent outputs from UTXOSet:")
            # for txOutput in UTXOSet().findUTXO(pubKeyHash):
            #     print(txOutput.toDict())
            #
            # print("My unspent outputs from BlockExplorer:")
            # for txId, txOutputs in BlockExplorer().findUTXO().items():
            #     for txOutput in txOutputs:
            #         if txOutput.isLockedWithKey(pubKeyHash):
            #             print("TXID: %s" % txId.hex())
            #             print(txOutput.toDict())
            sr.stop()
            break
示例#9
0
def handleGetBlocks(msg):
    getblocks = decodeMsg(msg)
    # print("Handling getblocks from %s" % getblocks['addrFrom'])
    sendInv(getblocks['addrFrom'], b'block', Blockchain().getBlockHashes())