def __init__(self): self.id = uuid4() self.blockchain = Blockchain(self.id)
def __init__(self, ip, port=0, genisus_node=False, is_committee_node=False): self.ip = ip self.port = port self.node_id = self.__random_id() self.address = (self.ip, self.port) self.buckets = KBucketSet(self.node_id) self.is_committee = is_committee_node self.startflag = False #是否开始出块 self.receivealltx_last = 0 self.receivealltx = 0 self.txinblock = 0 self.maxTime = 0 self.view = 0 #轮次 self.is_primary = genisus_node self.committee_member = [] # self.prepareMessages = [] self.commitMessages = [] self.blockcache = Block(0, 0, 0, 0, 0, 4) self.primary_node_address = self.address self.replyMessage = 0 self.GST = 10 self.replyflag = False # self.finishingflag = True self.receiveblock = True self.failhash = [] # 每个消息都有一个唯一的rpc_id,用于标识节点之间的通信(该rpc_id由发起方生成,并由接收方返回), # 这样可以避免节点收到多个从同一个节点发送的消息时无法区分 self.rpc_ids = {} # rpc_ids被多个线程共享,需要加锁 self.lock = threading.Lock( ) # 备注,由于blockchain数据被多个线程共享使用(矿工线程、消息处理线程),需要加锁 self.server = Server(self.address, ProcessMessages) self.port = self.server.server_address[1] self.client = Node(self.ip, self.port, self.node_id) self.data = {} self.alive_nodes = {} # {"xxxx":"2018-03-12 22:00:00",....} self.server.node_manager = self self.blockchain = Blockchain(genisus_node) self.numSeedNode = 0 # 消息处理 self.processmessages_thread = threading.Thread( target=self.server.serve_forever) self.processmessages_thread.daemon = True self.processmessages_thread.start() # 消息发送 TODO # self.sendmessages_thread = threading.Thread(target=self.sendmessages) # self.sendmessages_thread.daemon = True # self.sendmessages_thread.start() # 矿工线程 if is_committee_node: self.minner_thread = threading.Thread(target=self.minner) self.minner_thread.daemon = True self.minner_thread.start() print '[Info] start new node', self.ip, self.port, self.node_id
def __init__(self, config=None): if config is None: config = {} # Do not use mutables as default values! util.DaemonThread.__init__(self) self.config = SimpleConfig(config) if type(config) == type( {}) else config self.num_server = 8 if not self.config.get('oneserver') else 0 self.blockchains = {0: Blockchain(self.config, 0)} for x in os.listdir(self.config.path): if x.startswith('blockchain_fork_'): n = int(x[16:]) b = Blockchain(self.config, n) self.blockchains[n] = b self.print_error("blockchains", self.blockchains.keys()) self.blockchain_index = config.get('blockchain_index', 0) if self.blockchain_index not in self.blockchains.keys(): self.blockchain_index = 0 # Server for addresses and transactions self.default_server = self.config.get('server') # Sanitize default server try: deserialize_server(self.default_server) except: self.default_server = None if not self.default_server: self.default_server = pick_random_server() self.lock = threading.Lock() self.pending_sends = [] self.message_id = 0 self.debug = False self.irc_servers = {} # returned by interface (list from irc) self.recent_servers = self.read_recent_servers() self.banner = '' self.donation_address = '' self.relay_fee = None self.headers = {} # callbacks passed with subscriptions self.subscriptions = defaultdict(list) self.sub_cache = {} # callbacks set by the GUI self.callbacks = defaultdict(list) dir_path = os.path.join(self.config.path, 'certs') if not os.path.exists(dir_path): os.mkdir(dir_path) # subscriptions and requests self.subscribed_addresses = set() # Requests from client we've not seen a response to self.unanswered_requests = {} # retry times self.server_retry_time = time.time() self.nodes_retry_time = time.time() # kick off the network. interface is the main server we are currently # communicating with. interfaces is the set of servers we are connecting # to or have an ongoing connection with self.interface = None self.interfaces = {} self.auto_connect = self.config.get('auto_connect', True) self.connecting = set() self.socket_queue = Queue.Queue() self.start_network( deserialize_server(self.default_server)[2], deserialize_proxy(self.config.get('proxy')))
# -*- coding: utf-8 -*- from flask import Flask, jsonify, request from uuid import uuid4 from blockchain import Blockchain app = Flask(__name__) node_identifier = str(uuid4()).replace('-', '') blockchain = Blockchain() @app.route('/mine', methods=['GET']) def mine(): # We run the proof of work algorithm to get the next proof... last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) # We must receive a reward for finding the proof. # The sender is "0" to signify that this node has mined a new coin. blockchain.new_transaction( sender="0", recipient=node_identifier, amount=1, ) # Forge the new Block by adding it to the chain previous_hash = blockchain.hash(last_block) block = blockchain.new_block(proof, previous_hash)
def to_array(self): return { 'serial': self.serial, 'employee': self.employee, 'timestamp': self.timestamp } @staticmethod def from_array(data: dict): return TestProductEntry(data['serial'], data['employee'], data['timestamp']) difficulty = 4 block_size = 10 blockchain = Blockchain(difficulty, block_size) for i in range(123): entry = TestProductEntry('60125-0-%s-1' % i, 'Employee name', int(time.time() - 1500000 + (3600 * i))) print(' [+] Add entry %s' % entry.get_hash()) blockchain.add_entry(entry) blockchain.save('blockchain.db') blockchain = Blockchain.from_file('blockchain.db', TestProductEntry) print(' [+] Blockchain contain %s blocks' % blockchain.get_block_count()) print(' [+] Blockchain contain %s entry' % blockchain.get_entry_count()) print(' [+] Blockchain is valid' if blockchain.validate( ) else print(' [-] Blockchain is not valid'))
def test_malformed_nodes(self): blockchain = Blockchain() blockchain.register_node('http//192.168.0.1:5000') self.assertNotIn('192.168.0.1:5000', blockchain.nodes)
from uuid import uuid4 import requests from flask import Flask, jsonify, request from blockchain import Blockchain # Instantiate the node app = Flask(__name__) # Generate the address for this node node_identifier = str(uuid4()).replace('-', '') # Instantiate the blockchain justchain = Blockchain() @app.route('/mine', methods=['GET']) def mine(): # Run the proof of work to get the next proof and mine the block last_block = justchain.last_block last_proof = last_block['proof'] proof = justchain.proof_of_work(last_proof) # With the proof we can make a new transaction justchain.new_transaction(sender="0", recipient=node_identifier, amount=1) # Forge the new block and add a new one to the chain previous_hash = justchain.hash(last_block) block = justchain.create_new_block(proof, previous_hash)
from ecdsa import SECP256k1, SigningKey from blockchain import Blockchain, Transaction if __name__ == "__main__": if len(sys.argv) == 1: raise Exception("Missing private key!") private_key = sys.argv[1] my_sk = SigningKey.from_string( bytes.fromhex(private_key), curve=SECP256k1, ) my_vk = my_sk.verifying_key.to_string().hex() cycoin = Blockchain() tx_1 = Transaction(my_vk, "public key goes here", 10) tx_1.sign_transaction(my_sk) cycoin.add_transaction(tx_1) print("START MINING") cycoin.mine_pending_transactions(my_vk) print("DONE MINING") print("my balance: ", cycoin.get_balance_of_address(my_vk)) cycoin.print_chain()
def listen_for_input(self): waiting_for_input = True # A while loop for the user input interface # It's a loop that exits once waiting_for_input becomes False or when break is called while waiting_for_input: print('Please choose') print('1: Add a new transaction 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 keys') print('q: Quit') user_choice = self.get_user_choice() if user_choice == '1': tx_data = self.get_transaction_value() recipient, amount = tx_data # Add the transaction amount to the blockchain signature = self.wallet.sign_transaction( self.wallet.public_key, recipient, amount) if self.blockchain.add_transaction(recipient, self.wallet.public_key, signature, amount=amount): 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_elements() 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': self.wallet.save_keys() elif user_choice == 'q': # This will lead to the loop to exist because it's running condition becomes False waiting_for_input = False else: print('Input was invalid, please pick a value from the list!') if not Verification.verify_chain(self.blockchain.chain): self.print_blockchain_elements() print('Invalid blockchain!') # Break out of the loop break print('Balance of {}: {:6.2f}'.format( self.wallet.public_key, self.blockchain.get_balance())) else: print('User left!') print('Done!')
def listen_for_input(self): waiting_for_input = True while waiting_for_input: print('Please choose: ') print('1: Add a new transaction.') 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 keys') print('q: Quit') user_choice = self.get_user_choice() if user_choice == '1': tx_data = self.get_transection_value() recipient, amount = tx_data # pull out the elements of tuple # Add the transaction amount to the blockchain signature = self.wallet.sign_transaction( self.wallet.public_key, recipient, amount) if self.blockchain.add_transaction(recipient, self.wallet.public_key, signature, amount=amount): print('Added transaction! {}'.format( self.blockchain.get_open_transactions())) else: print('Transaction failed!') elif user_choice == '2': if not self.blockchain.mine_block(): print('Mining failed. Got no wallet?') elif user_choice == '3': # Output the blockchain list to the console self.print_blockchain_elements() 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': self.wallet.save_keys() elif user_choice == 'q': waiting_for_input = False else: print('Input was invalid. Please pick a value from the above!') if not Verification.verify_chain(self.blockchain.chain): print('Invalid blockchain!') self.print_blockchain_elements() break print('Balance of {}: {:6.2f}'.format( self.wallet.public_key, self.blockchain.get_balance())) else: print('User left!') print('Done!')
def main(): from blockchain import Blockchain blockchain = Blockchain() blockchain.addToChain(Block().make_block2(blockchain)) # Genesis block created here """ # Making our own blocks. n = 3 for _ in range(0, n): data = {'Place': 'Place_{}'.format(_+1), 'Time': 'Time of the event:{}'.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')), 'Seat': 'E{}'.format(random.randint(1,999)), 'Price': 'AUD {}'.format(random.randint(1,99999)) } block = Block().make_block2(blockchain, data) blockchain.addToChain(block) # Add the new block to the chain #prev_block = blockchain.getLastBlock() # Update the previous block pointer. generate_qrcode(block) # Generate the QR Code of new block. generate_pdf(block) # Generate the PDF of new block. print_to_file(blockchain) """ # Before making the block, I need to get POW from users to make a block. # Assume we have user 1 attempting to verify himself.. from user import User u1 = User("FirstNameBob","LastNameDoe","Account0123-ABC-321") # Creating a user u2 = User("SecondNameJane","Doe","Acc1987-ZXC") u3 = User("ThirdNameJosh","Burrows","901-999-231") userList = [] userList.append(u1) userList.append(u2) userList.append(u3) # Need to make data list. placeList = [] priceSeatDict = {} dateList = [] placeList.append("Belmont Park") placeList.append("New Era Field") placeList.append("Yankee Stadium") priceSeatDict["C"] = "109" priceSeatDict["D"] = "129" priceSeatDict["E"] = "139" # Input is %d - %m - %Y %I:%M %p # Date - Month - Year Hour:Minute AM/PM dateList.append("27 - 11 - 2017 11:00 pm") dateList.append("09 - 12 - 2017 11:00 pm") dateList.append("19 - 01 - 2018 11:00 pm") numOfTicket = 3 i = numOfTicket totalPrice = 0 approvalList = [] # Only for paypal. Cannot use this atm. pdfList = [] # List of PDF file made this time. from myPayment import MyPayment paymentClass = MyPayment() thisPDF = [] # PDF generated based on tickets. # looping down the ticket. while i>0: # a, b, c = main2(blockchain, userList, placeList, dateList, priceSeatDict, paymentClass) # Paypal payment a, pdfName = main2(blockchain, userList, placeList, dateList, priceSeatDict, paymentClass) # Stripe payment totalPrice += a thisPDF.append(pdfName) # paymentIDList.append(b) # paypal payment # approvalList.append(c) # paypal payment i -= 1 check_user(userList) paymentID = sPayment.createCharge(totalPrice*100) # Converting to $ because Stripe will start from c .. checkDuplicate(paymentIDList,paymentID) # To prevent duplicate payment_id print("Total Price:{}. PaymentID:{}.\nTickets:\n{}\n".format(totalPrice,paymentID, '\n'.join(thisPDF))) """ for i in thisPDF: import subprocess subprocess.Popen([i], shell=True) """ """
import pandas as pd if len(sys.argv) == 1: print("Nodetracker and port number not passed") exit() if len(sys.argv) == 2: print("Port number not passed") exit() # Instantiate our Node app = Flask(__name__, template_folder='templates') node = str('http://0.0.0.0:' + sys.argv[2] + '/node') # Instantiate the Blockchain blockchain = Blockchain(node) pokedex = pd.read_csv('Kanto.csv', index_col='Nat') def pokemonname(index): return pokedex['Pokemon'][index] def regnode(): sleep(1) #Let tracker know about presence of this node print("Node registration attempted") url = str('http://0.0.0.0:' + sys.argv[1] + '/nodes') payload = {'Node': str('http://0.0.0.0:' + sys.argv[2] + '/node')} requests.post(url, data=json.dumps(payload)) print("Node registration completed")
def __init__(self, address): """ Initialization method for Client class Convention: 0x10 - New Transaction 0x11 - New peers 0x12 - New mined block 0x13 - Blockchain """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Make the connection self.socket.connect((address, 5000)) self.byte_size = 1024 self.peers = [] print('==> Connected to server.') self.generate_key_pair() client_listener_thread = threading.Thread(target=self.send_message) client_listener_thread.start() while True: try: data = self.receive_message() if data[0:1] == '\x11': print('==> Got peers.') update_peers(data[1:]) elif data[0:1] == '\x10': print('==> New transaction.') print(data[1:]) elif data[0:1] == '\x13': print('==> Blockchain downloaded.') blockchain_info = data[1:] self.blockchain = Blockchain(serialization=blockchain_info) update_blockchain_file(self.blockchain.serialize()) elif data[0:1] == '\x12': print('==> New mined block.') block_info = data[1:] new_block = Block(serialization=block_info) in_blockchain = False for block in self.blockchain.blocks: if new_block.equal_blocks(block): print( "==> This block is already mined and is in your blockchain. It will not be added" ) in_blockchain = True break if not in_blockchain: print("\t", new_block.__dict__) print("\tNew Block Hash:", new_block.get_hash()) self.blockchain.add_block(new_block) update_blockchain_file(self.blockchain.serialize()) elif data != "": print("[#] " + data) except ConnectionError as error: print("==> Server disconnected. ") print('\t--' + str(error)) break
def test_two_round(crstype): numr1players = 6 numr2players = 6 numpolys = 3 crslen = 5 n = numr1players + numr2players + 1 numplayers = n - 1 sends, recvs = get_routing(n) bcfuncs = gen_blockchain_funcs(sends, recvs) loop = asyncio.get_event_loop() public = {} if crstype == "BabySNARK": #generate a random alpha, gamma for each party trapdoors1 = [[random_fp() for j in range(2)] for i in range(numr1players + 1)] #generate a random beta for round 2 players trapdoors2 = [random_fp() for i in range(numr2players)] trapdoors = trapdoors1 + trapdoors2 polys = [ Poly([random_fp() for j in range(crslen)]) for i in range(numpolys) ] public['polys'] = polys crs = init_babysnark(trapdoors[0], crslen) TestPlayer1 = BabySNARKr1Player TestPlayer2 = BabySNARKr2Player bc = Blockchain(sends[0], recvs[0], beacon=beacon_babysnark) #A proof is unnecessary for the first block as trapdoors are public pi = None #set the original CRS sends[0](0, ["SET_NOWAIT", [pi, crs]]) bctask = loop.create_task(bc.run()) mysleep = loop.create_task(asyncio.sleep(.5)) loop.run_until_complete(mysleep) options = [{'roles': ['contributor']} for i in range(numplayers)] players = [None] * numplayers r1players = [ TestPlayer1(i, trapdoors[i], sends[i], recvs[i], bcfuncs[i], options[i - 1]) for i in range(1, numr1players + 1) ] r2players = [ TestPlayer2(i, trapdoors[i], sends[i], recvs[i], bcfuncs[i], options[i - 1], public) for i in range(numr1players + 1, numplayers + 1) ] r1players[numr1players // 2].roles += ["validator"] r2players[numr2players // 2].roles += ["validator"] r2players[0].roles += ["roundstarter"] r1players[-1].roles += ["roundender"] r2players[-1].roles += ["roundender"] players = r1players + r2players for i in range(3, numplayers, 3): players[i].roles += ["checkpoint"] #send starting message to first player sends[0](1, ["INC", None, crs]) playertasks = [loop.create_task(player.run()) for player in players] for task in [bctask] + playertasks: task.add_done_callback(print_exception_callback) loop.run_until_complete(playertasks[-1]) get_block = bcfuncs[1][1] mytask = loop.create_task(get_block("ALL")) blocks = loop.run_until_complete(mytask) assert TestPlayer2.verify_chain(blocks, public) bctask.cancel()
def setUp(self): self.blockchain = Blockchain()
def __init__(self): #self.wallet.public_key=str(uuid4()) self.wallet = Wallet() self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key)
def test_valid_nodes(self): blockchain = Blockchain() blockchain.register_node('http://192.168.0.1:5000') self.assertIn('192.168.0.1:5000', blockchain.nodes)
def run_miner(): """Run the main miner loop. """ global blockchain global public global private new_reward = REWARD while True: # Load transaction queue and blockchain from server. new = [] blockchain = Blockchain() blockchain.add_block( Block( timestamp=datetime.datetime.now(), transactions=[], previous_hash=get_genisis().hash_block(), nonce=12834 ), cheat=True ) server = load_blockchain() txns = load_transactions() # Is this _the_ new block? # or did the server swoop us :( new_chain = load_blockchain() num_blocks = 1333 + server.head.height for i in range (num_blocks): reward = Transaction( id = gen_uuid(), owner = "mined", receiver = public, coins = REWARD, signature = None ) reward.signature = sign(reward.comp(), private) txns = [reward] b = Block( timestamp = datetime.datetime.now(), transactions = txns, previous_hash = blockchain.head.hash_block() ) blockchain.add_block(b, cheat=True) # Let's mine this block. reward = Transaction( id = gen_uuid(), owner = "mined", receiver = public, coins = REWARD, signature = None ) reward.signature = sign(reward.comp(), private) txns = [reward] # Construct a new block. b = Block( timestamp = datetime.datetime.now(), transactions = txns, previous_hash = b.hash_block() ) print(blockchain.head.height) mine_till_found(b) # WE MINED THIS BLOCK YAY. # AND WE WIN. resp = get_route('add', data=str(b)) if resp['success']: print "Block added!" delete_queue(txns) else: print "Couldn't add block:", resp['message']
from blockchain import Blockchain block_one_transactions = {"sender": "Alice", "receiver": "Bob", "amount": "50"} block_two_transactions = {"sender": "Bob", "receiver": "Cole", "amount": "25"} block_three_transactions = { "sender": "Alice", "receiver": "Cole", "amount": "35" } fake_transactions = { "sender": "Bob", "receiver": "Cole, Alice", "amount": "25" } local_blockchain = Blockchain() print(local_blockchain.print_blocks()) #Returns Block 0 and details. print("\n") local_blockchain.add_block(block_one_transactions) local_blockchain.add_block(block_two_transactions) local_blockchain.add_block(block_three_transactions) print(local_blockchain.print_blocks()) #Returns Block 0, 1, 2, 3 and details. print("\n") local_blockchain.chain[2].transactions = fake_transactions print(local_blockchain.print_blocks() ) #Returns Block 0, 1, Fake2, 3 and details. local_blockchain.validate_chain( ) #Returns Current Hash does not equal generated hash.
create_model(), my_x_train[i], my_new_y_train, my_x_test[i], my_y_test[i], equally_fully_connected(id, ids), policy_update_model_weights_name="equal", policy_update_model_weights_func= my_policy_update_model_weights)) # set blockchain genesis_transaction = Transaction(nodes[0].id, int(time.time()), flmodel=nodes[0].get_model()) # node 0 blockchain = Blockchain( genesis_transaction, policy_update_txs_weight_name="heaviest", policy_update_txs_weight_func=my_policy_update_txs_weight) # blockchain.print() # round # TODO: GPU # TODO: websocket elapsed_times = list() for r in range(num_round): start_time = time.time() print("Round", r) rNum = rNum + 1 # train for node in nodes: #if int(node.id) < 30:
from blockchain import Blockchain bc = Blockchain() bi_1 = bc.new_transaction('Sender 1', 'Recipient 1', 12) print("Current Transactions:", bc.current_transactions) print("Block index:", bi_1) print("Blockchain:", bc.chain) # input() pw_1 = bc.proof_of_work(0) print("Proof of Work 1:", pw_1) print("Previous Hash for Block 1:", bc.chain[0]['previous_hash']) nb_1 = bc.new_block(pw_1) # bc.chain[0]['previous_hash'] print("New block 1:", nb_1) print("Blockchain:", bc.chain) # input() bi_2 = bc.new_transaction('Sender 2', 'Recipient 2', 6) print("Current Transactions:", bc.current_transactions) print("Block index:", bi_2) print("Blockchain:", bc.chain) # input() pw_2 = bc.proof_of_work(pw_1) print("Proof of Work 2:", pw_2) print("Previous Hash for Block 2:", nb_1['previous_hash']) nb_2 = bc.new_block(pw_2) # nb_1['previous_hash']
def test1(): bc = Blockchain() hash_chains = {'url1': ['b1', 'b2', 'b3'], 'url2': ['b1', 'b2', 'b3']} assert (len(hash_chains[bc.consensus(hash_chains)]) == 3)
def loadBlockIndex(): blockchain = Blockchain() utils.logg('Loading BlockIndex') # # Load block index # for block in reversed(list(blockchain.blocks)): # add to index ctx.mapBlockIndex[block.hash] = block ctx.BestHeight = ctx.BestHeight + 1 ctx.bestBlockHash = block.hash ctx.mapBlockHeight[block.hash] = ctx.BestHeight # # Init with genesis block # if len(ctx.mapBlockIndex) == 0: txnew = Transaction() # Transaction # inputs txnew.vin[0].tx_id = '' txnew.vin[0].vout = -1 txnew.vin[ 0].public_key = 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks' # output txnew.vout[0].value = 50 * COIN txnew.vout[0].address = '1F6kc25HfrXcn9b4brsNzCiTDWuqsDzAmx' txnew.set_id() # Transaction(id='12c86ae42baf87e9186cd2fabae575e5534ee0bb82a61a8d0d5616d3ec9bf029', # vin=[TXInput(tx_id=b'', vout=-1, signature=None, public_key='The Times 03/Jan/2009 Chancellor on brink of second bailout for banks')], # vout=[TXOutput(address='1F6kc25HfrXcn9b4brsNzCiTDWuqsDzAmx', value=5000000000, public_key_hash='9aa83d479c33c697cd727fc87d753d2d7f2daf19')]) # Block block = Block([txnew]) block.prev_block_hash = '' block.timestamp = 1607965519 block.bits = 0x1e0fffff block.nonce = 1484712 #Block(timestamp=b'1607965519', tx_lst=[Transaction(id='12c86ae42baf87e9186cd2fabae575e5534ee0bb82a61a8d0d5616d3ec9bf029', #vin=[TXInput(tx_id=b'', vout=-1, signature=None, public_key='The Times 03/Jan/2009 Chancellor on brink of second bailout for banks')], #vout=[TXOutput(address='1F6kc25HfrXcn9b4brsNzCiTDWuqsDzAmx', value=5000000000, public_key_hash='9aa83d479c33c697cd727fc87d753d2d7f2daf19')])], #prev_block_hash=b'', hash=None, nonce=1484712, bits=504365055) assert ( block.getHash() == '0000054bd29593ff231e77f7005a9e288e162bbda8cb8962077d57d9be8f87c0') blockchain._block_put(block) utxo_set = UTXOSet(blockchain) utxo_set.reindex() utils.logg('Genesis block added to database') # add to index ctx.mapBlockIndex[block.hash] = block ctx.mapBlockHeight[block.hash] = 1 ctx.BestHeight = ctx.BestHeight + 1 ctx.bestBlockHash = block.hash # Miner ''' target = utils.bits2target(block.bits) i = 0 while 1: block.nonce = i hash_hex = block.getHash() hash_int = int(hash_hex, 16) if hash_int < target: print (hash_hex, block.nonce, block.timestamp) i +=1 ''' return True
import requests from flask import Flask, jsonify, request, render_template from blockchain import Blockchain import webbrowser ROOT = '127.0.0.1:5000' app = Flask(__name__) blockchain = Blockchain() # 实例化类 blockchain.ip = input() @app.route('/', methods=['GET']) def web_index(): return render_template('index.html', chain=blockchain.chain) @app.route('/wallet', methods=['GET']) def wallet(): pubk = str(blockchain.public_key) sk = str(blockchain.private_key) amount = blockchain.amount return render_template('index2.html', pubk=pubk, sk=sk, amount=amount) # 交互返回界面类 @app.route('/get_map', methods=['GET']) def get_map(): if blockchain.ip == ROOT: log = '这是根节点'
from flask import Flask, jsonify, request, send_from_directory from flask_cors import CORS from wallet import Wallet from blockchain import Blockchain app = Flask(__name__) wallet = Wallet() blockchain = Blockchain(wallet.public_key) CORS(app) @app.route('/', methods=['GET']) def get_ui(): return send_from_directory('ui', 'node.html') @app.route('/wallet', methods=['POST']) def create_keys(): wallet.create_keys() if wallet.save_keys(): global blockchain blockchain = Blockchain(wallet.public_key) response = { 'public_key': wallet.public_key, 'private_key': wallet.private_key, 'funds': blockchain.get_balance() } return jsonify(response), 201 else: response = {'message': 'Saving the keys failed.'}
def __init__(self, ip="127.0.0.1", port=9000, neighbor_list=[], account=Account(), blockchain=Blockchain(), authorization_pool=[] , data_path='./database'): self._ip = ip self._port = port self._neighborList = neighbor_list self._account = account self._blockchain = blockchain self._authorizationPool = authorization_pool self._database = [] self._dataPath = data_path self.app = Flask(__name__) """ @self.app.route('/') def hello_world(): return render_template('entry.html') @self.app.route('/', methods=['POST']) def my_form_post(): text = request.form['text'] print(type(text)) processed_text = text.upper() return processed_text """ @self.app.route('/neighbor/add') def submit_neighbor(): return render_template('submit_neighbor.html') @self.app.route('/neighbor/add', methods=['POST']) def add_neighbor(): neighbors = request.form['text'] print('add neighbors') print(neighbors) neighbors = json.loads(neighbors) if neighbors is None: return "Error: Please supply a valid list of neighbors", 400 response = [] for neighbor in neighbors: if not node.add_neighbor(neighbor): info = neighbor + ' is invalid address, address should be like x.x.x.x:port' response.append(info) response += list(node.get_neighbors()) return jsonify(list(response)), 201 @self.app.route('/neighbor/list', methods=['GET']) def list_neighbors(): neighbors = node.get_neighbors() response = { 'neighbors': list(neighbors) } return jsonify(response), 200 @self.app.route('/blockchain', methods=['GET']) def list_blockchain(): response = self.get_blockchain().to_json() return jsonify(response), 200 @self.app.route('/authorization/pool', methods=['GET']) def list_authorizations(): response = self.get_authorization_pool() return jsonify(list(response)), 200 @self.app.route('/authorization/add', methods=['POST']) def add_authorization(): get_json = json.loads(request) required = ['inputs', 'outputs', 'duration', 'timestamp'] if not all(k in get_json for k in required): return 'Missing values', 400 # Create a new Transaction authorization = Authorization(get_json['inputs'], get_json['outputs'], get_json['duration'], get_json['timestamp']) node.add_authorization(authorization) response = authorization.to_json() return jsonify(response), 201 @self.app.route('/authorization/receive', methods=['POST']) def receive_authorization(): get_json = request.get_json() required = ['inputs', 'outputs', 'duration', 'timestamp'] if not all(k in get_json for k in required): return 'Missing values', 400 get_authorization = json.load(get_json) # Create a new Transaction authorization = Authorization(get_authorization['inputs'], get_authorization['outputs'], get_authorization['duration'], get_authorization['timestamp']) node.add_authorization(authorization) response = authorization.to_json() return jsonify(response), 201 @self.app.route('/mine', methods=['GET']) def mine(): new_block = self.new_block() response = new_block.to_json() return jsonify(response), 200 @self.app.route('/block/add') def submit_block(): return render_template('submit_block.html') @self.app.route('/block/add', methods=['POST']) def add_block(): get_json = request.form['text'] return get_json @self.app.route('/block/receive', methods=['POST']) def receive_block(): return render_template('submit_block.html') # some functions to solve data @self.app.route('/data/upload', methods=['POST']) def upload_data(): # check if got enough values get_json = request.get_json() print(get_json) print(type(get_json)) required = ['public_key', 'data', 'timestamp', 'op', 'signature'] if not all(k in get_json for k in required): return 'Missing values', 400 public_key = get_json['public_key'] data = get_json['data'] timestamp = get_json['timestamp'] op = get_json['op'] hash = hashlib.sha256((str(data) + str(timestamp) + str(0)).encode()).hexdigest() signature = get_json['signature'] # check if op is upload operation if op != 0: return 'op is not matched!', 400 # check if there is enough room if len(self._database) + len(get_json['data']) >= MAX_DATA_RANGE: return 'no enough storage', 400 # check if timestamp is not expired if timestamp + 600 < time.time(): return 'Request expired', 400 # check if signature is matched print(signature) print(type(signature)) if not verify_signature(public_key, hash, eval(signature)): return 'Signature unmatched', 400 # everything is fine then store data into database if type(data) is 'list': self._database += data else: self._database.append(data) # generate a new authorization input = Input(0, 0, 0) if type(data) is 'list': data_url = DataURL(len(self._database) - len(data), len(self._database)) else: data_url = DataURL(len(self._database) - 1, len(self._database)) output = Output(recipient=public_key, data_url=data_url, limit=Limit(7)) authorization = Authorization(inputs=[input], outputs=[output], duration=Duration(), timestamp=time.time()) # sign this authorization input.add_signature(self._account.sign_message(authorization.calc_hash())) # store this authorization and broadcast it auth_number = self.add_authorization(authorization) print(auth_number) # return the position of authorization to client response = { 'block_number': self._blockchain.get_height(), 'auth_number': auth_number, 'output_number': 0 } return jsonify(response), 201 # receive delete request @self.app.route('/data/delete', methods=['POST']) def delete_data(): # check if got enough values get_json = request.get_json() required = ['public_key', 'data_url', 'timestamp', 'output_position', 'op', 'signature'] if not all(k in get_json for k in required): return 'Missing values', 400 public_key = get_json['public_key'] data_url = get_json['data_url'] timestamp = get_json['timestamp'] output_position = get_json['output_position'] op = get_json['op'] hash = hashlib.sha256((str(data_url) + str(timestamp) + str(output_position) + str(1)).encode()).hexdigest() signature = get_json['signature'] # check if op is delete operation if op != 1: return 'op is not matched!', 400 # get output from the output_position and check the limit and data_url output = self._blockchain.get_output(output_position['block_number'], output_position['authorization_number'], output_position['output_number']) if not output.valid_limit(4): return 'error: limit out of range', 400 if not output.data_url_contains(data_url.get_start(), data_url.get_end()): return 'error: data_url out of range', 400 # check if timestamp is not expired if timestamp + 600 < time.time(): return 'Request expired', 400 # check if signature is matched if not verify_signature(public_key, hash, signature): return 'Signature unmatched', 400 # if everything is fine then delete the data in data_url start = data_url['start'] end = data_url['end'] for i in range(start, end): self._database[i] = 0 # return the delete information to client return 'delete successfully!', 201 @self.app.route('/data/update', methods=['POST']) def update_data(): # check if got enough values get_json = request.get_json() required = ['public_key', 'data', 'data_url', 'timestamp', 'output_position', 'op', 'signature'] if not all(k in get_json for k in required): return 'Missing values', 400 public_key = get_json['public_key'] data = get_json['data'] data_url = get_json['data_url'] timestamp = get_json['timestamp'] output_position = get_json['output_position'] op = get_json['op'] hash = hashlib.sha256((str(data_url) + str(timestamp) + str(output_position) + str(1)).encode()).hexdigest() signature = get_json['signature'] # check if op is update operation if op != 2: return 'op is not matched!', 400 # get output from the output_position and check the limit and data_url output = self._blockchain.get_output(output_position['block_number'], output_position['authorization_number'], output_position['output_number']) if not output.valid_limit(4): return 'error: limit out of range', 400 if not output.data_url_contains(data_url.get_start(), data_url.get_end()): return 'error: data_url out of range', 400 # check if timestamp is not expired if timestamp + 600 < time.time(): return 'Request expired', 400 # check if signature is matched if not verify_signature(public_key, hash, signature): return 'Signature unmatched', 400 # check if there is enough room start = data_url['start'] end = data_url['end'] if isinstance(data, list) and len(data) > start - end: return 'no enough storage', 400 # if everything is fine then update the data in data_url if isinstance(data, list): for i in range(start, start+len(data)): self._database[i] = data[i-len(data)] for i in range(start+len(data), end): self._database[i] = 0 else: self._database[start] = data for i in range(start+1, end): self._database[i] = 0 # return the update information to client return 'update successfully!', 201 @self.app.route('/data/read', methods=['POST']) def read_data(): # check if got enough values get_json = request.get_json() required = ['public_key', 'data_url', 'timestamp', 'output_position', 'op', 'signature'] if not all(k in get_json for k in required): return 'Missing values', 400 public_key = get_json['public_key'] data_url = get_json['data_url'] timestamp = get_json['timestamp'] output_position = get_json['output_position'] op = get_json['op'] hash = hashlib.sha256((str(data_url) + str(timestamp) + str(output_position) + str(1)).encode()).hexdigest() signature = get_json['signature'] # check if op is read operation if op != 3: return 'op is not matched!', 400 # get output from the output_position and check the limit and dataurl output = self._blockchain.get_output(output_position['block_number'], output_position['authorization_number'], output_position['output_number']) if not output.valid_limit(4): return 'error: limit out of range', 400 if not output.valid_dataURL(get_json['data_url']): return 'error: data_url out of range', 400 # check if timestamp is not expired if timestamp + 600 < time.time(): return 'Request expired', 400 # check if signature is matched if not verify_signature(public_key, hash, signature): return 'Signature unmatched', 400 # if everything is fine then return the data in data_url start = data_url['start'] end = data_url['end'] return self._database[start:end], 201 @self.app.route('/outputs/update', methods=['POST']) def update_outputs(): # check if got enough values get_json = request.get_json() required = ['public_key', 'data_url', 'timestamp', 'output_position', 'op', 'signature'] if not all(k in get_json for k in required): return 'Missing values', 400 return
@app.route('/node/<node_url>', methods=['DELETE']) def remove_node(node_url): if node_url == '' or node_url is None: response = { 'message': 'Node is not found.' } return jsonify(response), 400 blockchain.remove_peer_node(node_url) response = { 'message': 'Node is removed successfully.', 'all_nodes': blockchain.get_peer_nodes() } return jsonify(response), 200 @app.route('/nodes', methods=['GET']) def get_nodes(): nodes = blockchain.get_peer_nodes() response = { 'all_nodes': nodes } return jsonify(response), 200 if __name__ == '__main__': wallet = Wallet() blockchain = Blockchain(prt) app.run(host='0.0.0.0', port=prt)
def __init__(self, config=None): if config is None: config = {} # Do not use mutables as default values! util.DaemonThread.__init__(self) self.config = SimpleConfig(config) if type(config) == type({}) else config self.num_server = 8 if not self.config.get('oneserver') else 0 self.blockchain = Blockchain(self.config, self) # A deque of interface header requests, processed left-to-right self.bc_requests = deque() # Server for addresses and transactions self.default_server = self.config.get('server') # Sanitize default server try: deserialize_server(self.default_server) except: self.default_server = None if not self.default_server: default_servers = self.config.get('default_servers') if not default_servers: raise ValueError('No servers have been specified') self.default_server = pick_random_server(default_servers) self.lock = Lock() self.pending_sends = [] self.message_id = 0 self.debug = False self.irc_servers = {} # returned by interface (list from irc) self.recent_servers = self.read_recent_servers() self.banner = '' self.fee = None self.relay_fee = None self.heights = {} self.merkle_roots = {} self.utxo_roots = {} # catchup counter, used to track catchup progress before chain is verified and headers saved self.catchup_progress = 0 # callbacks passed with subscriptions self.subscriptions = defaultdict(list) self.sub_cache = {} # callbacks set by the GUI self.callbacks = defaultdict(list) dir_path = os.path.join( self.config.path, 'certs') if not os.path.exists(dir_path): os.mkdir(dir_path) # subscriptions and requests self.subscribed_addresses = set() # Requests from client we've not seen a response to self.unanswered_requests = {} # retry times self.server_retry_time = time.time() self.nodes_retry_time = time.time() # kick off the network. interface is the main server we are currently # communicating with. interfaces is the set of servers we are connecting # to or have an ongoing connection with self.interface = None self.interfaces = {} self.auto_connect = self.config.get('auto_connect', False) self.connecting = set() self.socket_queue = Queue.Queue() self.online_servers = {} self._set_online_servers() self.start_network(deserialize_server(self.default_server)[2], deserialize_proxy(self.config.get('proxy')))
def on_header(self, interface, header): height = header.get('block_height') if interface.mode == 'checkpoint': b = self.get_blockchain(header) if b: interface.mode = 'default' interface.blockchain = b #interface.print_error('passed checkpoint', b.filename) self.queue_request('blockchain.headers.subscribe', [], interface) else: interface.print_error("checkpoint failed") self.connection_down(interface.server) interface.request = None return can_connect = self.can_connect(header) if interface.mode == 'backward': if can_connect: interface.good = height interface.mode = 'binary' interface.print_error("binary search") next_height = (interface.bad + interface.good) // 2 else: interface.bad = height delta = interface.tip - height next_height = interface.tip - 2 * delta if next_height < 0: interface.print_error( "header didn't connect, dismissing interface") self.connection_down(interface.server) elif interface.mode == 'binary': if can_connect: interface.good = height else: interface.bad = height if interface.bad != interface.good + 1: next_height = (interface.bad + interface.good) // 2 else: interface.print_error("found connection at %d" % interface.good) delta1 = interface.blockchain.height() - interface.good delta2 = interface.tip - interface.good if delta1 > 10 and delta2 > 10: interface.print_error("chain split detected: %d (%d %d)" % (interface.good, delta1, delta2)) interface.blockchain.fork(interface.bad) interface.blockchain = Blockchain(self.config, interface.bad) self.blockchains[interface.bad] = interface.blockchain if interface.blockchain.catch_up is None: interface.blockchain.catch_up = interface.server interface.print_error("catching up") interface.mode = 'catch_up' next_height = interface.good else: # todo: if current catch_up is too slow, queue others next_height = None elif interface.mode == 'catch_up': if can_connect: interface.blockchain.save_header(header) self.notify('updated') next_height = height + 1 if height < interface.tip else None else: next_height = None if next_height is None: # exit catch_up state interface.request = None interface.mode = 'default' interface.print_error('catch up done', interface.blockchain.catch_up) interface.blockchain.catch_up = None elif interface.mode == 'default': assert not can_connect interface.print_error("cannot connect %d" % height) interface.mode = 'backward' interface.bad = height # save height where we failed interface.blockchain_height = interface.blockchain.height() next_height = height - 1 else: raise BaseException(interface.mode) # If not finished, get the next header if next_height: if interface.mode == 'catch_up' and interface.tip > next_height + 50: self.request_chunk(interface, next_height // 2016) else: self.request_header(interface, next_height)
def __init__(self): self.user = User() self.ledger = Blockchain()