def fetchUpToDateBlockchain(self): if self.nodeCount > 0: chain = self.nodes[0].chain # return deep copy of a node's blockchain return copy.deepcopy(chain) else: return blockchain.BlockChain()
def nouvelle_chaine(): """ Une nouvelle chaine est creee """ global b b = bc.BlockChain() return "<h1>New Blockchain</h1><p>Successfully created new blockchain</p>"
def get_blockchain(): """ Blockの情報を取得する blockchainの情報は本来DBに入れる 今回はglobalに格納する See Also -------- cache : dict """ cached_blockchain = cache.get("blockchain") # 1度しか呼ばれない if not cached_blockchain: miners_wallet = wallet.Wallet() cache["blockchain"] = blockchain.BlockChain( blockchain_address=miners_wallet.blockchain_address, port=app.config["port"]) app.logger.warning({ "private_key": miners_wallet.private_key, "public_key": miners_wallet.public_key, "blockchain_address": miners_wallet.blockchain_address }) return cache["blockchain"]
def test_receive_blockchain(self): """ DOCSTRING """ bc = blockchain.BlockChain() old_bc_lengh = len(bc.blockchain_store) prev_block = unittest.mock.MagicMock() new_block = unittest.mock.MagicMock() with self.subTest('valid block should be added to blockchain'): new_block.has_valid_index = unittest.mock.MagicMock( return_value=True) new_block.has_valid_previous_hash = unittest.mock.MagicMock( return_value=True) new_block.has_valid_hash = unittest.mock.MagicMock( return_value=True) bc.blockchain_store = [prev_block] bc.receive_new_block(new_block) self.assertEqual(len(bc.blockchain_store) - old_bc_lengh, 1) with self.subTest('invalid block shoud not be added to blockchain'): new_block.has_valid_index = unittest.mock.MagicMock( return_value=False) new_block.has_valid_previous_hash = unittest.mock.MagicMock( return_value=False) new_block.has_valid_hash = unittest.mock.MagicMock( return_value=False) bc.blockchain_store = [prev_block] bc.receive_new_block(new_block) self.assertEqual(len(bc.blockchain_store) - old_bc_lengh, 0)
def add(mouvement): """ On dit au serveur qu'un nouveau mouvement a ete effectue. """ global b if b is None: b = bc.BlockChain() b.head().transactions.add("e4") return f"<h1>Ajout d'un mouvement</h1><p>Succesfully added new move {mouvement}</p>"
def __init__(self): self.server = conf["server"] self.calc_port = conf["calc_port"] self.add_port = conf["add_port"] self.signal_port = conf["signal_port"] self.client_num = conf["client_num"] self.chain = chain.BlockChain() print("服务器初始化的链id:%s" % id(self.chain)) self.ops_list = [] self.uncalc_ops = [] self.proof_list = []
def test_generate_new_block(self): """ DOCSTRING """ bc = blockchain.BlockChain() old_bc_length = len(bc.blockchain_store) data = 'this is new block' with self.subTest('add new block to blockchain'): bc.generate_next_block(data) self.assertEqual(len(bc.blockchain_store) - old_bc_length, 1) self.assertEqual(bc.latest_block().data, data)
def test_chain(self): ''' Basic chain test ''' print("Running basic chain test") _blockchain = blockchain.BlockChain() _blockchain.build_genesis() _blockchain.add_new_transaction({"sender": "miner007", "recipient": "kalle", "amount": 2}) _blockchain.mine("miner007") _blockchain.print_chain() #_blockchain.chain_to_file() self.assertTrue(_blockchain.check_chain_validity(_blockchain.chain))
def get_blockchain(): cached_blockchain = cache.get('blockchain') if not cached_blockchain: miners_wallet = wallet.Wallet() cache['blockchain'] = blockchain.BlockChain( blockchain_address=miners_wallet.blockchain_address, port=app.config['port']) app.logger.warning({ 'private_key': miners_wallet.private_key, 'public_key': miners_wallet.public_key, 'blockchain_address': miners_wallet.blockchain_address}) return cache['blockchain']
def test_balance(self): ''' Mine some blocks and verify account balance ''' print("\nRunning balance test") _blockchain = blockchain.BlockChain() _blockchain.build_genesis() _blockchain.add_new_transaction({"sender": "miner007", "recipient": "kalle", "amount": 1}) _blockchain.mine("miner007") _blockchain.add_new_transaction({"sender": "kalle", "recipient": "miner007", "amount": 2}) _blockchain.mine("miner007") self.assertEqual(_blockchain.calculate_balance("miner007"), 3) self.assertTrue(_blockchain.check_chain_validity(_blockchain.chain))
def split(self): # randomly select half the nodes to split newCommunityNodes = [] np.random.shuffle(self.nodes) for i in range(int(self.nodeCount / 2)): newCommunityNodes.append(self.nodes[i]) # Query all nodes in both communities to see if they want to split approved = 0 for node in self.nodes: if node.approveSplit(): approved += 1 if approved < self.nodeCount / 2: return False, None, None pubkeys = [] for newNode in newCommunityNodes: pubkeys.append(newNode.publicKey) self.nodes.remove(newNode) transaction, newTransaction = self.generateSplitTransactions(pubkeys) transaction = utils.Utils.serializeTransaction(transaction) newTransaction = utils.Utils.serializeTransaction(newTransaction) # add a new split block to remaining nodes blockchain serial = utils.Utils.serializeBlock( self.fetchUpToDateBlockchain().longestChain().block) splitBlock = buildingblocks.Block(transaction, H(str.encode(serial)).hexdigest(), isSplit=True) for node in self.nodes: node.chain.addBlock(splitBlock) # create a new blockchain for all nodes that are in the new community newBlock = buildingblocks.Block(newTransaction, None) for node in newCommunityNodes: newBlockChain = blockchain.BlockChain() newBlockChain.setGenesis(newBlock) node.setBlockChain(newBlockChain) community1 = Community(self.network, random.randint(0, 10**10), pool=self.pool, keys=None, nodeList=self.nodes) community2 = Community(self.network, random.randint(0, 10**10), pool=self.pool, keys=None, nodeList=newCommunityNodes) return True, community1, community2
def __init__(self, publicKey, privateKey, community): # public key address to reference node self.publicKey = publicKey # private key address to reference node signingKey = str.encode(privateKey) signingKey = nacl.signing.SigningKey(signingKey, encoder=nacl.encoding.HexEncoder) self.privateKey = signingKey # private reference to network this node is part of self.network = community.network # private reference to community node is part of self.community = community # node's stake in the system (for proof of stake) self.stake = 0 # reference node's blockchain self.chain = blockchain.BlockChain()
import argparse import sys from flask import Flask, jsonify, request, render_template from uuid import uuid4 sys.path.append('./') import blockchain as bc import requests import json, time app = Flask(__name__, template_folder='./', static_folder="", static_url_path="") node_id = str(uuid4()).replace('-', '') blockchain = bc.BlockChain() hash_list = [] @app.route('/mine', methods=['GET']) def mine(self, sender: str, recipient: str, timestart: str, timeend: str, data: str): last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.pow( last_proof) #long time to get the result depend on power # Deliver bonus blockchain.new_transaction( sender=sender, # From system recipient=recipient, timestart=timestart,
else: print('The block already exists') conn.close() print('****************************Connection closed') t = threading.Thread(target=waitForConnection) t.start() print('waiting for transaction...\n') while 1: transactions = txpool.find_one() if transactions != None: # if 检测到数据库里存在TX bc.CHECK_MINE_02 = 0 ##############################################################<<<<<<<<<< print('Found transaction, mining block...\n') blockchain_a = bc.BlockChain() new_block = blockchain_a.gen_block(transactions) # 对该TX挖矿 if new_block: # if 成功挖出来 if new_block['Nonce'] == 0: # 被阻断的Block time.sleep(1) print( 'Mining is stopped by receiving block from the other node.\n' ) elif checkHash(new_block['Hash']): # if 不存在于链上 print('Successfully mined a new block: ', new_block) col_bk.insert_one(new_block) # 推上DB 的主blockchain chain.insert_one({ 'Index': new_block['Index'], 'Hash': new_block['Hash'] }) for port in other_PORT: # broadcast
import threading import logging from flask import Flask from flask import g from flask import render_template from flask import request from flask import redirect import sqlite3 import pickle import transaction import blockchain logging.basicConfig(level=logging.DEBUG) blockchain_obj = blockchain.BlockChain() app = Flask(__name__) salt = b"12321" @app.route("/") def route_page(): return redirect("/signup") @app.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "POST": email = request.values["mail"]
def test_create_genesis_block(self): bc = blockchain.BlockChain() bc.create_first_block(bc) print(bc.last_block_hash)
def __init__(self): self.blockchain = blockchain.BlockChain() self.transactions = [] return
import blockchain import block import miner import os # Clear console def clear_window(): os.system('cls' if os.name == 'nt' else 'clear') in_command = "" print("Initializing blockchain...") bc = blockchain.BlockChain() print('Enter "list" for a list of commands') def list_commands(): clear_window() print("*****Commands List*****") print("Exit: ext") print("Mine for coins: mine") print("Make transaction: trans") print("Check balance: bal \n") def make_transaction(): clear_window() frm = input("Enter your ID: ")
import grpc import helloworld_pb2 import helloworld_pb2_grpc import time import blockchain import threading from global_variables import KNOWN_PEERS NODE = 'A' #from multiprocessing import Process _ONE_DAY_IN_SECONDS = 60 * 60 * 24 # start a blockchain handler/object. Initialize mempool for this client FULL_NODE_BLOCKCHAIN = blockchain.BlockChain() import socket hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) print("This is %s:" % NODE, " IP address", IPAddr) class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) def Handshake(self, request, context): # append the new node KNOWN_PEERS.append(request.addr_me)
) private_key_sign = private_key.sign(message) signature = private_key_sign.hex() return signature if __name__ == '__main__': wallet_M = Wallet() wallet_A = Wallet() wallet_B = Wallet() t = Transaction( wallet_A.private_key, wallet_A.public_key, wallet_A.blockchain_address, wallet_B.blockchain_address, 10.0) ####### Blockchain Node import blockchain block_chain = blockchain.BlockChain( blockchain_address=wallet_M.blockchain_address) is_added = block_chain.add_transaction( wallet_A.blockchain_address, wallet_B.blockchain_address, 10.0, wallet_A.public_key, t.generate_signature() ) print('Added?', is_added) block_chain.mining() utils.pprint(block_chain.chain) print('A', block_chain.calculate_total_amount(wallet_A.blockchain_address)) print('B', block_chain.calculate_total_amount(wallet_B.blockchain_address)) print('M', block_chain.calculate_total_amount(wallet_M.blockchain_address))
import blockchain import utils # Metrics names TRANSACTION_WAITING_TIME_BEFORE_COMPLETING = "Transactions waiting time (in blocks) before completing avg" TRANSACTION_SUCCESSFUL_COUNT = "Transactions successful count" TRANSACTION_AMOUNT_AVG = "Transaction amount sent avg" TOTAL_LOCKED_FUND_IN_EVERY_BLOCKS = "All (summation) locked fund in every block" LOCKED_FUND_PER_TRANSACTION = "Locked funds per passed received transaction" TRANSACTIONS_PASSED_THROUGH = "Transactions that passed through count" TRANSACTIONS_PASSED_SUCCESSFUL = "Transactions passed through resolved successful count" SEND_TRANSACTION = "Transactions tried to send count" PATH_LENGTH_AVG = "Transactions path length avg" NO_PATH_FOUND = "Path not found for a transaction count" TOTAL_FEE = "Total fee avg" ADD_CANCELLATION_CONTRACT_FAILED = "Failed transaction - could not add cancellation contract count" ADD_FORWARD_CONTRACT_FAILED = "Failed transaction - could not add forward contract count" TERMINATE_TRANSACTION = "Terminated transactions count" HONEST_NODE_BALANCE_AVG = "Honest node final balance avg" VICTIM_NODE_BALANCE_AVG = "Victim: node final balance avg" # singleton for all runs BLOCKCHAIN_INSTANCE: blockchain.BlockChain = blockchain.BlockChain() METRICS_COLLECTOR_INSTANCE: utils.MetricsCollector = utils.MetricsCollector() FUNCTION_COLLECTOR_INSTANCE: utils.FunctionCollector = utils.FunctionCollector( )