def produce_transactions(path, cnt=None): clients = {} transactions = [] with open(path) as fp: lines = fp.read().split("\n")[:-1] id = 0 for line in lines[1:]: print("Reading line:", line) id += 1 if cnt is not None and id > cnt: break fields = line.split('\t') trans_id = int(fields[0]) trans = Transaction(trans_id) outputs = {} for field in fields[1:]: if field.startswith("intput"): input_ip = int(field.split(':')[1]) add_client(clients, input_ip) elif field.startswith("outputindex"): output_index = int(field.split(':')[1]) elif field.startswith("output"): output_num = field.split(':')[0][6:] if output_num == "": output_num = 1 else: output_num = int(output_num) output_ip = int(field.split(':')[1]) add_client(clients, output_ip) if output_num in outputs: outputs[output_num] = (output_ip, outputs[output_num][1]) else: outputs[output_num] = (output_ip, None) elif field.startswith("value"): output_num = field.split(':')[0][5:] if output_num == "": output_num = 1 else: output_num = int(output_num) value = float(field.split(':')[1]) if output_num in outputs: outputs[output_num] = (outputs[output_num][0], value) else: outputs[output_num] = (None, value) for op in outputs.values(): trans.add_output(op) trans.add_input((input_ip, None)) transactions.append(trans) signature = clients[input_ip].private_key.sign( data=trans.__str__().encode('utf-8'), padding=padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), algorithm=hashes.SHA256()) # trans.add_signature(signature) return transactions, clients
def create_transaction(self, amount, recipient_address): """ the functions creates transaction which contains the amount of coins to send the recipient address, the function implements the transaction in the block chain :param amount: the amount to send :param recipient_address: the address to send the coins to :returns: true if there is enough money to the transaction and false otherwise """ # updates the balance self.update_balance() # checks weather there is enough money # to the transaction if amount > self.balance: self.logger.info(self.address + '- not enough money to send') return False # creates the new transaction new_transaction = Transaction([], []) sending_amount = 0 for unspent_output in self.unspent_outputs: # creating the proof data_to_sign = unspent_output.transaction_id data_to_sign += recipient_address data_to_sign = self.hash(data_to_sign).hexdigest() data_to_sign += str(amount) data_to_sign = self.hash(data_to_sign) signature = self.sign(data_to_sign) proof = (signature, self.public_key) new_transaction.add_input( Input(unspent_output.transaction_id, unspent_output.output_index, proof)) sending_amount += unspent_output.output.value if sending_amount >= amount: break new_transaction.add_output(Output(sending_amount, recipient_address)) # add change if it is needed if sending_amount > amount: change = sending_amount - amount new_transaction.add_output(Output(change, self.address)) # distributes the transaction self.logger.info(self.address + " is sending " + str(amount) + "LPC to " + recipient_address) self.distribute_transaction(new_transaction) return True
def minerServer(my_ip, wallet_list, my_public_key): tx_list = [] #Receive data from wallet server = socketUtils.newServerConnection(my_ip) # Get 2 Txs from wallets for iteration in range(10): newTx = socketUtils.recvObj(server) if isinstance(newTx, Tx): print("Tx {0} received".format(len(tx_list))) tx_list.append(newTx) if len(tx_list) >= 2: break # Add Txs to a new block newBlock = txBlock.TxBlock(findLongestBlockchain()) for transaction in tx_list: newBlock.addTx(transaction) # Compute and add mining reward to the block total_in, total_out = newBlock.count_totals() rewardTx = Tx() rewardTx.add_output(my_public_key, network_reward + total_in - total_out) newBlock.addTx(rewardTx) # Find nonce for i in range(10): print("Finding Nonce...") newBlock.find_nonce() if newBlock.good_nonce(): break if not newBlock.good_nonce(): print("Error. Couldn't find nonce") return False # Send new block to wallets for ip_addr in wallet_list: socketUtils.sendObj(ip_addr, newBlock, 5006) # Replace new block with previously longest block head_blocks.remove(newBlock.previousBlock) head_blocks.append(newBlock) print(head_blocks, "Everything done successfully in miner") # Open server connection # Rec'v 2 transactions # Collect them into block # Fine nonce # Send that block to wallet_list return False
def create_first_block(*pub_pri_keys): """产生一个创世区块""" # pre_hash设定为全0,索引为0 first_hash = "0" while len(first_hash) < 64: first_hash += "0" block = Block(0, first_hash) # 添加矿工奖励 reward = create_reward_trans(pub_pri_keys[0][0]) block.add_transactions(reward) # 初始的utxo for pub_str, pri_str in pub_pri_keys: trans = Transaction() trans.add_output(5000, address_key(pub_str)) trans.sign_transaction(pub_str, pri_str) trans_dict = trans.derive_transaction() block.add_transactions(trans_dict) block_dict = block.export_dict() block_dict = find_answer_for_block(block_dict) return block_dict
def make_standard_transaction(self, output_address, amount): tx_version = 1 assert isinstance(output_address, Address) assert amount >= Constants.DUST_THRESHOLD tx = Transaction(tx_version, [], [{ 'address': output_address, 'value': amount }], self.network.block_height) is_possible = False prvkeys = [] unlocked_funds = 0 for utxo in self.utxos: unlocked_funds += utxo['value'] address = None for i, a in enumerate(self.recv_addresses): if a == utxo['address']: address = a branch = 0 index = i break for i, a in enumerate(self.chng_addresses): if a == utxo['address']: address = a branch = 1 index = i break if not address: raise WalletError("UTXO address cannot be found") pubkeys = self.keystore.get_pubkeys(branch, index) prvkeys.extend(self.keystore.get_prvkeys(branch, index)) tx.add_input({ 'txid': utxo['txid'], 'index': utxo['index'], 'value': utxo['value'], 'address': address, 'pubkeys': pubkeys, 'nsigs': 1, 'sequence': Constants.SEQUENCE_NUMBER }) txsize = tx.estimate_size() fee = Constants.FEE_RATE * txsize r = unlocked_funds - amount - fee if r == 0: # no need for change address is_possible = True break txsize += 32 + 2 * (output_address.kind == Constants.CASH_P2PKH) fee = Constants.FEE_RATE * txsize r = unlocked_funds - amount - fee if r >= Constants.DUST_THRESHOLD: self.add_new_address(branch=1) tx.add_output({ 'address': self.chng_addresses[-1], 'value': unlocked_funds - amount - fee }) is_possible = True break if not is_possible: raise WalletError("cannot create transaction") tx.sign(prvkeys) rawtx = tx.serialize() txid = tx.txid() fee = tx.get_fee() return rawtx, txid, fee
return self.nonce return None if __name__ == '__main__': print("txBlock.py tests start here") private_key1, public_key1 = generate_keys() private_key2, public_key2 = generate_keys() private_key3, public_key3 = generate_keys() private_key4, public_key4 = generate_keys() Tx1 = Tx() Tx1.add_input(public_key1, 1) Tx1.add_output(public_key2, 1) Tx1.sign(private_key1) print('Tx{0} validation status before loading is: {1}'.format( 1, Tx1.is_valid())) savefile = open("save.dat", "wb") pickle.dump(Tx1, savefile) savefile.close() loadfile = open("save.dat", "rb") loadedTx = pickle.load(loadfile) loadfile.close() print('Tx{0} validation status after loading is: {1}'.format( 1, loadedTx.is_valid()))
import socketUtils from transaction import Transaction as Tx import signature head_blocks = [None] Tx1 = Tx() Tx2 = Tx() pr1, pu1 = signature.generate_keys() pr2, pu2 = signature.generate_keys() pr3, pu3 = signature.generate_keys() Tx1.add_input(pu1, 4.0) Tx1.add_input(pu2, 1.0) Tx1.add_output(pu3, 4.8) Tx2.add_input(pu3, 4.0) Tx2.add_output(pu2, 4.0) Tx2.add_required(pu1) Tx1.sign(pr1) Tx1.sign(pr2) Tx2.sign(pr3) Tx2.sign(pr1) try: socketUtils.sendObj('localhost', Tx1) print("Sent Tx1") socketUtils.sendObj('localhost', Tx2) print("Sent Tx2") except:
import socketUtils from txBlock import TxBlock as TxBlock from transaction import Transaction as Tx TCP_PORT = 5005 IP_ADDR = 'localhost' if __name__ == "__main__": print("client.py test start here") pr1, pu1 = signature.generate_keys() pr2, pu2 = signature.generate_keys() pr3, pu3 = signature.generate_keys() Tx1 = Tx() Tx1.add_input(pu1, 2.3) Tx1.add_output(pu2, 1.0) Tx1.add_output(pu3, 1.1) Tx1.sign(pr1) Tx2 = Tx() Tx2.add_input(pu3, 2.3) Tx2.add_input(pu2, 1.0) Tx2.add_output(pu1, 3.1) Tx2.sign(pr2) Tx2.sign(pr3) B1 = TxBlock(None) B1.addTx(Tx1) B1.addTx(Tx2) socketUtils.sendObj(IP_ADDR, B1)
# 发起交易的测试 from peer import Peer from transaction import Transaction from key import create_key, address_key p = Peer() p.add_friend("127.0.0.1:5000") p.sync_blockchain() pub_str, pri_str = create_key() trans = Transaction() trans.add_input(0, 0, 0) trans.add_output(15.3545, address_key(pub_str)) trans.set_cost(0.003) diff = trans.com_insum_outsum(p.get_blockchain()) file = open("pub.key", "r") pub_key = file.read() file.close() file = open("pri.key", "r") pri_key = file.read() file.close() trans.add_output(diff, address_key(pub_key)) # 余额 trans.sign_transaction(pub_key, pri_key) trans_dict = trans.derive_transaction() print(trans_dict["sign"]) if p.add_transaction(trans_dict): p.send_transaction(trans_dict)
from transaction import Transaction from account import Account from messages import TransactionMessage import ecdsa, hashlib, struct ref_txn_hash = "b93ba975d8cf7b71cfec5116f1ed83a187d2f3e840801fff6b57c119d0023d11" ref_txn_index = 0 sender_address = "1N4MvxDTrAi7rPQP2bZgcidiapTf9iJdU5" transfer_value = 80000 recipient_address = "3LZKm2PMEbv94kSboz5m1EGBW7sUDAhAFT" t = Transaction() t.add_input(sender_address, ref_txn_hash, ref_txn_index) t.add_output(transfer_value, recipient_address) t.add_op_return_output( raw="@bitaccess @iam5hravan Interested and I'm already liking it!") #t.add_op_return_output(file_path="./main.py") #t.add_op_return_output(data="this is getting better") #t.add_output(transfer_value,recipient_address) payload = t.get_real_transaction(Account("raw", create=True)) print "Raw-transaction:", payload.encode("hex") tx_msg = TransactionMessage(payload) print "Transaction on wire:", tx_msg.get_raw_msg().encode("hex")