def undo(self, tid, note=None): t = Transaction() if note is not None: t.note(note) oids = self._begin_undos_vote(t, tid) self._storage.tpc_finish(t) return oids
class TestTransaction(unittest.TestCase): def setUp(self): Transaction.objects = {} self.transaction = Transaction(datetime(2014, 10, 4, 20, 0), 33.50) def test_initial_attributes(self): self.transaction.date |should| equal_to(datetime(2014, 10, 4, 20, 0)) self.transaction.month |should| equal_to(10) self.transaction.value |should| equal_to(33.50) self.transaction.id |should| equal_to(1) def test_persistence(self): Transaction.objects |should| equal_to({ 1: self.transaction }) def test_associate_credit_card(self): with Stub() as credit_card: credit_card.id >> 1 self.transaction.associate_credit_card(credit_card) self.transaction.credit_card_id |should| equal_to(credit_card.id) def test_associate_seller(self): with Stub() as seller: seller.id >> 1 self.transaction.associate_seller(seller) self.transaction.seller_id |should| equal_to(seller.id)
def checkUndoInvalidation(self): oid = self._storage.new_oid() revid = self._dostore(oid, data=MinPO(23)) revid = self._dostore(oid, revid=revid, data=MinPO(24)) revid = self._dostore(oid, revid=revid, data=MinPO(25)) info = self._storage.undoInfo() if not info: # Preserved this comment, but don't understand it: # "Perhaps we have an old storage implementation that # does do the negative nonsense." info = self._storage.undoInfo(0, 20) tid = info[0]['id'] # Now start an undo transaction t = Transaction() t.note('undo1') oids = self._begin_undos_vote(t, tid) # Make sure this doesn't load invalid data into the cache self._storage.load(oid, '') self._storage.tpc_finish(t) assert len(oids) == 1 assert oids[0] == oid data, revid = self._storage.load(oid, '') obj = zodb_unpickle(data) assert obj == MinPO(24)
def download(request): transaction = Transaction(request) transaction.set_current_step(Steps.DOWNLOAD) if transaction.current_step()['state'] in (State.DONE, State.DISABLED): return HttpResponseRedirect(transaction.next_step_url()) return render(request, 'download.html', {'transaction': transaction})
def config(request): """ configuration page """ transaction = Transaction(request) transaction.set_current_step(Steps.CONFIG) if transaction.current_step()['state'] in (State.DONE, State.DISABLED): return HttpResponseRedirect(transaction.next_step_url()) config = xmlrpc.call('get_config', transaction.modules_list) run_config = False skip_config = True for module in transaction.modules_info: if module["has_configuration"]: skip_config = False if module["has_configuration_script"]: run_config = True # modules don't have configuration scripts if not run_config: for module in transaction.modules_list: config_end(request, module) return render(request, 'config_no.html', {'transaction': transaction}) # some module have configuration elif not skip_config: return render(request, 'config.html', {'transaction': transaction, 'config': config}) else: return HttpResponseRedirect(reverse('config_valid'))
def __init__(self, size, manager): Transaction.__init__(self) self._trManager = manager self._size = size self._flush_count = 0 self.is_flushable = False
def all_unknown(self, message, *args, **kwargs): __callstack_var_tx__ = Transaction(name=self._transactionName) yield self.once.begin(self._transactionName) try: yield self.all.unknown(message, *args, **kwargs) yield __callstack_var_tx__.commit() except TransactionException: yield __callstack_var_tx__.rollback()
def preinst(request): """ preinst page """ transaction = Transaction(request) transaction.set_current_step(Steps.PREINST) if transaction.current_step()['state'] in (State.DONE, State.DISABLED): return HttpResponseRedirect(transaction.next_step_url()) return render(request, 'preinst.html', {'transaction': transaction})
def medias_auth(request): """ media auth page """ transaction = Transaction(request) transaction.set_current_step(Steps.MEDIAS_AUTH) if transaction.current_step()['state'] in (State.DONE, State.DISABLED): return HttpResponseRedirect(transaction.next_step_url()) return render(request, 'media_auth.html', {'transaction': transaction})
def undo(self, tid, note): t = Transaction() t.note(note) self._storage.tpc_begin(t) oids = self._storage.undo(tid, t) self._storage.tpc_vote(t) self._storage.tpc_finish(t) return oids
def end(request): transaction = Transaction(request) transaction.set_current_step(Steps.END) for module in transaction.modules_list: xmlrpc.call("end_config", module, 0, "") return render(request, "end.html", {"transaction": transaction})
def transfer_required_deposits(self): from transaction import Transaction transaction = Transaction() value = round(float(self.r*self.get_account("D")), 4) transaction.this_transaction("rD", self.identifier, -3, value, self.rb, 0, -1) self.accounts.append(transaction) return -1.0*value
def end(request): transaction = Transaction(request) transaction.set_current_step(Steps.END) for module in transaction.modules_list: xmlrpc.call('end_config', module, 0, "") return render(request, 'end.html', {'transaction': transaction})
def signtransaction(self, tx, privkey=None): """Sign a transaction. The wallet keys will be used unless a private key is provided.""" t = Transaction(tx) if privkey: pubkey = lbrycrd.public_key_from_private_key(privkey) t.sign({pubkey:privkey}) else: self.wallet.sign_transaction(t, self._password) return t.as_dict()
def __init__(self, size, manager): Transaction.__init__(self) self._trManager = manager self._size = size self._flush_count = 0 self._endpoint = 'https://example.com' self._api_key = 'a' * 32 self.is_flushable = False
def decode_transaction(self, document): assert document["_type"] == "transaction" transaction = Transaction(document['_id'], document["time"]) transaction.value_in = document['value_in'] transaction.value_out = document['value_out'] transaction.addressesValue_receving = document['addressesValue_receving'] transaction.addressesValue_sending = document['addressesValue_sending'] return transaction
def gettransaction(self, txid, deserialized=False): """Retrieve a transaction. """ tx = self.wallet.transactions.get(txid) if self.wallet else None if tx is None and self.network: raw = self.network.synchronous_get(('blockchain.transaction.get', [txid])) if raw: tx = Transaction(raw) else: raise BaseException("Unknown transaction") return tx.deserialize() if deserialized else tx
def signtransaction(self, tx, privkey=None): """Sign a transaction. The wallet keys will be used unless a private key is provided.""" t = Transaction(tx) t.deserialize() if privkey: pubkey = bitcoin.public_key_from_private_key(privkey) t.sign({pubkey:privkey}) else: self.wallet.sign_transaction(t, self.password) return t
def gettransaction(self, txid): """Retrieve a transaction. """ tx = self.wallet.transactions.get(txid) if self.wallet else None if tx is None and self.network: raw = self.network.synchronous_get(("blockchain.transaction.get", [txid])) if raw: tx = Transaction(raw) else: raise BaseException("Unknown transaction") return tx.as_dict()
def prepare(request): """ prepare the transaction """ if request.method == "POST": modules = [] for module, value in request.POST.items(): modules.append(module) transaction = Transaction(request, modules) return HttpResponseRedirect(transaction.first_step_url()) else: return HttpResponseRedirect(reverse('sections'))
def install(request): """ install page """ transaction = Transaction(request) transaction.set_current_step(Steps.INSTALL) if transaction.current_step()['state'] in (State.DONE, State.DISABLED): return HttpResponseRedirect(transaction.next_step_url()) # launch modules install xmlrpc.call('install_modules', transaction.modules_list) return render(request, 'install.html', {'transaction': transaction})
def __init__(self, data): self._data = data # Call after data has been set (size is computed in Transaction's init) Transaction.__init__(self) # Insert the transaction in the Manager self._trManager.append(self) logging.debug("Created transaction %d" % self.get_id()) self._trManager.flush()
def sum_obligations(messages, user_id): balances = defaultdict(float) errors = list() for m in messages: try: t = Transaction(m) value, party = t.obligation_to_user(user_id) balances[party] += value except TransactionParseError as err: errors.append(err) return balances, errors
def gettransaction(self, txid): """Retrieve a transaction. """ if self.wallet and txid in self.wallet.transactions: tx = self.wallet.transactions[txid] else: raw = self.network.synchronous_get(('blockchain.transaction.get', [txid])) if raw: tx = Transaction(raw) else: raise BaseException("Unknown transaction") return tx.as_dict()
def remove(self, t: Transaction): """Removes transaction from Transaction object collection in Account. Updates from removal """ assert t in self._ts, \ "account.Account.remove: {} not in self._ts".format(t) y,m = t.get_year(), t.get_month() self._ts.remove(t) self._budgets[y][m] = Budget( self.get_goal(y,m), self.get_reached(y,m) - (t.get_amount()), self.get_ts_amt(y,m) - 1)
def signtransaction(self, tx, privkey=None): """Sign a transaction. The wallet keys will be used unless a private key is provided.""" tx = Transaction(tx) if privkey: pubkey = bitcoin.public_key_from_private_key(privkey) h160 = bitcoin.hash_160(pubkey.decode('hex')) x_pubkey = 'fd' + (chr(0) + h160).encode('hex') tx.sign({x_pubkey:privkey}) else: self.wallet.sign_transaction(tx, self._password) return tx.as_dict()
def transfer_excess_reserves(self): from transaction import Transaction availableVolume = self.Q plannedVolume = self.gamma*(1.0-self.lamb)*self.V transactionVolume = round(min(plannedVolume, availableVolume), 4) self.Q = round(self.Q - transactionVolume, 4) if (self.Q < 0.0): logging.info("ERROR: Q negative in transfer_excess_reserves") transaction = Transaction() transaction.this_transaction("E", self.identifier, -2, transactionVolume, self.rb, 0, -1) self.accounts.append(transaction) del transaction
def any_unknown(self, message, *args, **kwargs): __callstack_var_tx__ = Transaction(name=self._transactionName) yield self.once.begin(name=self._transactionName) try: try: response = yield self.any.unknown(message, *args, **kwargs) except NoneOfTheObserversRespond: raise DeclineMessage yield __callstack_var_tx__.commit() raise StopIteration(response) except TransactionException: yield __callstack_var_tx__.rollback()
def sweep(self, privkey, to_address, fee = 0.0001): pubkey = public_key_from_private_key(privkey) address = address_from_private_key(privkey) pay_script = Transaction.pay_script(address) unspent = self.network.synchronous_get([ ('blockchain.address.listunspent',[address])])[0] if not unspent: return total = sum( map(lambda x:int(x.get('value')), unspent) ) - int(Decimal(fee)*100000000) inputs = map(lambda i: {'prevout_hash': i['tx_hash'], 'prevout_n':i['tx_pos'], 'scriptPubKey':pay_script, 'redeemPubkey':pubkey}, unspent) outputs = [(to_address, total)] tx = Transaction.from_io(inputs, outputs) tx.sign({ pubkey:privkey }) return tx
def checkCreationUndoneGetTid(self): # create an object oid = self._storage.new_oid() self._dostore(oid, data=MinPO(23)) # undo its creation info = self._storage.undoInfo() tid = info[0]['id'] t = Transaction() t.note('undo1') self._begin_undos_vote(t, tid) self._storage.tpc_finish(t) # Check that calling getTid on an uncreated object raises a KeyError # The current version of FileStorage fails this test self.assertRaises(KeyError, self._storage.getTid, oid)
def broadcast(self, tx): """Broadcast a transaction to the network. """ t = Transaction(tx) return self.network.synchronous_get( ('blockchain.transaction.broadcast', [str(t)]))
else: transaction = self.transactions[i] base_leafs.append(transaction.hash) leafs = [base_leafs] while len(leafs[-1]) > 1: next_leafs = [] for i in range(0, len(leafs[-1]), 2): combined_hashes = leafs[-1][i] + leafs[-1][i+1] next_hash = '0x'+hashlib.sha256(combined_hashes.encode('utf-8')).hexdigest() next_leafs.append(next_hash) leafs.append(next_leafs) self.leafs = leafs self.root = leafs[-1][-1] if __name__ == '__main__': from account import Account alice = Account() bob = Account() block = Block() # next block of transactions transaction = Transaction(bob.address, alice.address, 50) signature = bob.sign(transaction.hash) block.add_transaction(transaction, bob.pub_key, signature) print(block.serialize())
def __init__(self, transactions, public_key, private_key, version, index=None, force_time=None): self.version = BU.get_version_for_height(index) if force_time: self.time = str(int(force_time)) else: self.time = str(int(time.time())) blocks = BU.get_blocks() self.index = index if self.index == 0: self.prev_hash = '' else: self.prev_hash = BU.get_latest_block()['hash'] self.public_key = public_key self.private_key = private_key transaction_objs = [] fee_sum = 0.0 unspent_indexed = {} used_sigs = [] for txn in transactions: if isinstance(txn, Transaction): transaction_obj = txn else: transaction_obj = Transaction.from_dict(txn) if transaction_obj.transaction_signature in used_sigs: print 'duplicate transaction found and removed' continue used_sigs.append(transaction_obj.transaction_signature) transaction_obj.verify() #check double spend address = str( P2PKHBitcoinAddress.from_pubkey( transaction_obj.public_key.decode('hex'))) if address in unspent_indexed: unspent_ids = unspent_indexed[address] else: res = BU.get_wallet_unspent_transactions(address) unspent_ids = [x['id'] for x in res] unspent_indexed[address] = unspent_ids failed = False used_ids_in_this_txn = [] for x in transaction_obj.inputs: if x.id not in unspent_ids: failed = True if x.id in used_ids_in_this_txn: failed = True used_ids_in_this_txn.append(x.id) if not failed: transaction_objs.append(transaction_obj) fee_sum += float(transaction_obj.fee) block_reward = BU.get_block_reward() coinbase_txn_fctry = TransactionFactory( public_key=self.public_key, private_key=self.private_key, outputs=[ Output(value=block_reward + float(fee_sum), to=str( P2PKHBitcoinAddress.from_pubkey( self.public_key.decode('hex')))) ], coinbase=True) coinbase_txn = coinbase_txn_fctry.generate_transaction() transaction_objs.append(coinbase_txn) self.transactions = transaction_objs txn_hashes = self.get_transaction_hashes() self.set_merkle_root(txn_hashes) self.block = Block(version=self.version, block_time=self.time, block_index=self.index, prev_hash=self.prev_hash, transactions=self.transactions, merkle_root=self.merkle_root, public_key=self.public_key)
def handle_request(self, request=None): errors = [] if isinstance(request, socket.socket): signed = PaymentServerSkeleton.verify_signature(request) write = request.sendall if not signed: write(bytes('410', 'utf-8')) errors.append(410) return False pad_len = request.recv(struct.calcsize('B')) pad_len = struct.unpack('B', pad_len)[0] cipher = request.recv(1024) data = PaymentServerSkeleton._decrypt(cipher, pad_len) else: return False self.initialize_bases() self.update_bill() tr_type = Transaction.get_type(data) tr = None # ***** process payment transaction ***** if tr_type == 1: tr = PaymentTransaction.deserialize(data) if not self.check_valid_organization( tr.org_id): # if organization id not in database write(bytes('402', 'utf-8')) return False if self.send_pay(tr.org_id, tr.p_acc, tr.amount, tr.commission): write(bytes('200', 'utf-8')) else: write(bytes('404', 'utf-8')) errors.append(404) # **** process encashment transaction ***** elif tr_type == 2: tr = EncashmentTransaction.deserialize(data) if self.check_collector_requisites(tr.collector_id, tr.secret): self.bill += tr.amount write(bytes('200', 'utf-8')) else: write(bytes('406', 'utf-8')) errors.append('406') # **** process service transaction ***** elif tr_type == 0: tr = ServiceTransaction.deserialize(data) if tr.action == 0: # terminal power on # check terminal for registration in our database if self.check_terminal_registration(tr): write(bytes('200', 'utf-8')) else: write(bytes('401', 'utf-8')) errors.append('401') elif tr.action == 2: # terminal save config action (shutdown) self.write_terminal_config(tr) # save transaction in database if no errors occurred if not errors: self.save_transaction(tr) # TODO: log file instead of this print('Client says: {}'.format(data)) print('Deserialized data: {}'.format(tr))
from wallet import Wallet from transaction import Transaction import pdb sender_wallet = Wallet('eduardo', 'password') receiver_wallet = Wallet('matheus', 'password') transaction = Transaction(sender_wallet, receiver_wallet, 5) transaction.verify_signature() pdb.set_trace()
def decoderawtransaction(self, raw): tx = Transaction.deserialize(raw) return {'inputs': tx.inputs, 'outputs': tx.outputs}
def test_verify_real_transation(self): #print(self.transaction.__dict__) self.assertTrue(Transaction.verify_transaction(self.transaction))
def broadcast(self, tx, timeout=30): """Broadcast a transaction to the network. """ tx = Transaction(tx) return self.network.broadcast(tx, timeout)
def sweep(self, privkey, to_address, fee=0.0001): fee = int(Decimal(fee) * 100000000) return Transaction.sweep([privkey], self.network, to_address, fee)
import csv from ticker import Ticker from transaction import Transaction with open('data.csv', newline='') as csv_file: data = csv.reader(csv_file, delimiter=' ', quotechar='|') ticker_dict = {} #dict() for row in data: #row_length = len(row) #if row_length > 0: tran = Transaction(row) symbol = tran.symbol if tran.is_valid(): if symbol in ticker_dict: tick = ticker_dict[symbol] tick.add_transaction(tran) else: ticker_dict[symbol] = Ticker(symbol) # we will want to make this work with the raw csv from merrill edge, so we should detect row length etc if tran.description.startswith('Reinvestment Share(s)'): # this represents dividend reinvesting print('DIVIDEND\t for ' + symbol + ' amount: ' + tran.amount + ', quantity: ' + tran.quantity + ', price: ' + tran.price) # after
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")
def payJobAuth(): jobId = str(request.form['jobId']) tran = Transaction.getConfirmedTransaction(conn, jobId) return render_template("payment.html", line=tran)
def signrawtransaction(self, raw_tx, private_keys): tx = Transaction.deserialize(raw_tx) self.wallet.signrawtransaction(tx, private_keys, self.password) return tx
def sendrawtransaction(self, raw): tx = Transaction.deserialize(raw) return self.network.synchronous_get([ ('blockchain.transaction.broadcast', [str(tx)]) ])[0]
def deserialize(self, tx): """Deserialize a serialized transaction""" return Transaction(tx).deserialize()
def run_interface(self): #print_error("synchronizer: connected to", self.network.get_parameters()) requested_tx = [] missing_tx = [] requested_histories = {} # request any missing transactions for history in self.wallet.history.values(): if history == ['*']: continue for tx_hash, tx_height in history: if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx: missing_tx.append( (tx_hash, tx_height) ) if missing_tx: self.print_error("missing tx", missing_tx) # subscriptions self.subscribe_to_addresses(self.wallet.addresses(True)) while self.is_running(): # 1. create new addresses self.wallet.synchronize() # request missing addresses new_addresses = [] while True: try: addr = self.address_queue.get(block=False) except Queue.Empty: break new_addresses.append(addr) if new_addresses: self.subscribe_to_addresses(new_addresses) # request missing transactions for tx_hash, tx_height in missing_tx: if (tx_hash, tx_height) not in requested_tx: self.network.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], self.queue.put) requested_tx.append( (tx_hash, tx_height) ) missing_tx = [] # detect if situation has changed if self.network.is_up_to_date() and self.queue.empty(): if not self.wallet.is_up_to_date(): self.wallet.set_up_to_date(True) self.was_updated = True self.wallet.save_transactions() else: if self.wallet.is_up_to_date(): self.wallet.set_up_to_date(False) self.was_updated = True if self.was_updated: self.network.trigger_callback('updated') self.was_updated = False # 2. get a response try: r = self.queue.get(timeout=0.1) except Queue.Empty: continue # 3. process response method = r['method'] params = r['params'] result = r.get('result') error = r.get('error') if error: self.print_error("error", r) continue if method == 'blockchain.address.subscribe': addr = params[0] if self.wallet.get_status(self.wallet.get_address_history(addr)) != result: if requested_histories.get(addr) is None: self.network.send([('blockchain.address.get_history', [addr])], self.queue.put) requested_histories[addr] = result elif method == 'blockchain.address.get_history': addr = params[0] self.print_error("receiving history", addr, len(result)) hist = [] # check that txids are unique txids = [] for item in result: tx_hash = item['tx_hash'] if tx_hash not in txids: txids.append(tx_hash) hist.append( (tx_hash, item['height']) ) if len(hist) != len(result): raise Exception("error: server sent history with non-unique txid", result) # check that the status corresponds to what was announced rs = requested_histories.pop(addr) if self.wallet.get_status(hist) != rs: raise Exception("error: status mismatch: %s"%addr) # store received history self.wallet.receive_history_callback(addr, hist) # request transactions that we don't have for tx_hash, tx_height in hist: if self.wallet.transactions.get(tx_hash) is None: if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx: missing_tx.append( (tx_hash, tx_height) ) elif method == 'blockchain.transaction.get': tx_hash = params[0] tx_height = params[1] assert tx_hash == bitcoin.hash_encode(bitcoin.Hash(result.decode('hex'))) tx = Transaction(result) try: tx.deserialize() except Exception: self.print_msg("Warning: Cannot deserialize transactions. skipping") continue self.wallet.receive_tx_callback(tx_hash, tx, tx_height) self.was_updated = True requested_tx.remove( (tx_hash, tx_height) ) self.print_error("received tx:", tx_hash, len(tx.raw)) else: self.print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) ) if self.was_updated and not requested_tx: self.network.trigger_callback('updated') # Updated gets called too many times from other places as well; if we use that signal we get the notification three times self.network.trigger_callback("new_transaction") self.was_updated = False
def make_Bucket(desc, coins): size = sum(Transaction.estimated_input_size(coin) for coin in coins) value = sum(coin['value'] for coin in coins) return Bucket(desc, size, value, coins)
key = 92106429 + i keys.append(key) records[key] = [key, 0, 0, 0, 0] q = Query(grades_table) q.insert(*records[key]) # create TransactionWorkers transaction_workers = [] for i in range(num_threads): transaction_workers.append(TransactionWorker([])) # generates 10k random transactions # each transaction will increment the first column of a record 5 times for i in range(1000): k = randint(0, 2000 - 1) transaction = Transaction() for j in range(5): key = keys[k * 5 + j] q = Query(grades_table) transaction.add_query(q.select, key, 0, [1, 1, 1, 1, 1]) q = Query(grades_table) transaction.add_query(q.increment, key, 1) transaction_workers[i % num_threads].add_transaction(transaction) threads = [] for transaction_worker in transaction_workers: threads.append(threading.Thread(target = transaction_worker.run, args = ())) for i, thread in enumerate(threads): print('Thread', i, 'started') thread.start()
def test_verify_malicious_transation(self): self.transaction.outputs[0]['amount'] = 66 self.assertFalse(Transaction.verify_transaction(self.transaction))
def signtxwithwallet(self, raw_tx): tx = Transaction.deserialize(raw_tx) self.wallet.sign_transaction(tx, self.password) return tx
def test_amount_more_than_balance(self): transaction = Transaction.new_transaction(self.wallet, self.recipient, 700) self.assertFalse(transaction)
def handle_by_msg_type(self, data, tcp_client): """Handle client data based on msg_type""" msg_type = data[0].lower() if msg_type == "n": # updates on network nodes self.node.log("======= Receive updates on network nodes") nodes = json.loads(data[1:])["nodes"] self.node.set_peers(nodes) elif msg_type == "b": # new block self.node.log("======= Receive new block from peer") blk_json = json.loads(data[1:])["blk_json"] proof = json.loads(data[1:])["blk_proof"] # stop mining self.node.stop_mine.set() # verify it if all transactions inside the block are valid blk = Block.deserialize(blk_json) transactions = blk.transactions if self.node.check_final_balance(transactions): delta_previous = self.node.private_blockchain.length - self.node.blockchain.length success_add = self.node.blockchain.add(blk, proof) if delta_previous == 0: public_blks = self.node.blockchain.get_blks() self.node.private_blockchain = Blockchain.new(public_blks) self.node.privateBranchLen = 0 elif delta_previous == 1: self.node.broadcast_blk( self.node.private_blockchain.last_node.block, self.node.private_blockchain.last_node.block. compute_hash()) self.node.blockchain.add( self.node.private_blockchain.last_node.block, self.node.private_blockchain.last_node.block. compute_hash()) elif delta_previous == 2: blks = self.node.private_blockchain.get_blks() for i in range(self.node.privateBranchLen - 1, -1, -1): self.node.broadcast_blk(blks[i], blks[i].compute_hash()) self.node.blockchain.add(blks[i], blks[i].compute_hash()) self.privateBranchLen = 0 else: last_node = self.node.private_blockchain.last_node for i in range(self.node.privateBranchLen - 1): last_node = last_node.previous self.node.broadcast_blk(last_node.block, last_node.block.compute_hash()) self.node.blockchain.add(last_node.block, last_node.block.compute_hash()) for tx in transactions: if tx in self.node.unconfirmed_transactions: self.node.unconfirmed_transactions.remove(tx) self.node.log( f"Added a new block received: {success_add} with {len(transactions)} transactions" ) self.node.log("Public Blockchain") self.node.log(self.node.blockchain.print()) self.node.log("Private Blockchain") self.node.log(self.node.private_blockchain.print()) else: self.node.log( "Invalid transactions in the new block received! ") self.node.stop_mine.clear() elif msg_type == "t": # new transaction self.node.log("======= Receive new transaction from peer") tx_json = json.loads(data[1:])["tx_json"] self.node.add_transaction(Transaction.deserialize(tx_json)) elif msg_type == "r": # request for transaction proof self.node.log("======= Receive request for transaction proof") tx_json = json.loads(data[1:])["tx_json"] self.node.log(f"transaction = {tx_json}") proof, hash = self.node.get_transaction_proof(tx_json) self.node.log(f"blk_hash: {hash}") self.node.log(f"proof: {proof}") if proof is None: msg = "nil" else: msg = json.dumps({"merkle_path": proof, "blk_hash": str(hash)}) tcp_client.sendall(msg.encode()) self.node.log(f">>> Send proof to SPV") elif msg_type == "x": # request for headers by spvclient self.node.log("======= Receive request for headers (SPV)") headers = self.node.get_blk_headers() msg = json.dumps({"headers": headers}) tcp_client.sendall(msg.encode()) self.node.log(">>> Send headers to SPV") elif msg_type == "c": # request for nonce by spvclient self.node.log("======= Receive request for nonce (SPV)") identifier = json.loads(data[1:])["identifier"] msg = json.dumps(self.node.blockchain.get_nonce(identifier)) tcp_client.sendall(msg.encode()) self.node.log(f">>> Send nonce = {msg} to SPV") elif msg_type == "m": # request for balance by spvclient self.node.log("======= Receive request for balance (SPV)") identifier = json.loads(data[1:])["identifier"] msg = json.dumps(self.node.get_balance(identifier)) tcp_client.sendall(msg.encode()) self.node.log(f">>> Send balance = {msg} to SPV") tcp_client.close()
def __init__(self): # 初始化 data = pd.read_table( 'all-in-USD-trust-lines-2016-nov-7.txt', header=None, encoding='unicode-escape', delim_whitespace=True, names=['src', 'dst', 'lower_bound', 'balance', 'upper_bound']) gra = nx.Graph() # 先用一个无向图拿到节点列表 #for i in range(int(len(data['src']) / 20)): # 用 1/20的数据进行计算 for i in range(int(len(data['src']) / 5)): # 用1/5的数据进行计算 gra.add_edge(data['src'][i], data['dst'][i]) subset = max(nx.connected_components(gra), key=len) graph = gra.subgraph(subset) # 最大连通子图,无向图的拓扑结构 """ # 根据 json 文件拿到通道数据 with open('ripple_topology.json', 'r', encoding='utf8')as fp: json_data = json.load(fp) gra = nx.Graph() for i in range(len(json_data['links'])): gra.add_edge(json_data['links'][i]['source'], json_data['links'][i]['target']) graph = gra """ # ########实例化所有节点加入到 nodes 中 self.node_id = list(graph.nodes()) for i in range(len(self.node_id)): node1 = Node(self.node_id[i]) PCN.nodes[self.node_id[i]] = node1 # #######实例化所有交易类加入到 txs 中 # 同时构建双向拓扑图 self.dic_graph = nx.DiGraph() c = 0 for i in range(int(len(data['src']))): if (data['src'][i] in self.node_id) and (data['dst'][i] in self.node_id): c += 1 trans = Transaction(c, data['src'][i], data['dst'][i], data['balance'][i]) # 实例化交易类 trans.time_set(2000) self.dic_graph.add_weighted_edges_from([ (data['src'][i], data['dst'][i], 50.0), (data['dst'][i], data['src'][i], 50.0) ]) # 有向图添加边,金额平分 PCN.txs.append(trans) # 添加到交易列表中 PCN.nodes[data['src'][i]].channels_update( trans.receiver, 50.0) # 更新节点里的交易通道信息 #通道另一边也要增加 PCN.nodes[data['dst'][i]].channels_update(trans.sender, 50.0) #PCN.nodes[data['src'][i]].display_node() # ### """ for i in range(len(list(graph.edges()))): c += 1 trans = Transaction(c, list(graph.edges())[i][0], list(graph.edges())[i][1], 50) self.dic_graph.add_weighted_edges_from( [(list(graph.edges())[i][0], list(graph.edges())[i][1], 50), (list(graph.edges())[i][1], list(graph.edges())[i][0], 50)]) PCN.nodes[(list(graph.edges())[i][0])].channels_update(list(graph.edges())[i][1], 50) """ self.tx_count = 0 print(len(list(self.dic_graph.edges()))) print(len(list(self.dic_graph.nodes()))) print(len(PCN.nodes)) print(len(PCN.txs))
def deserialize(self, tx): """Deserialize a serialized transaction""" tx = Transaction(tx) return tx.deserialize()
def __init__(self, window, obj): tk.Frame.__init__(self, window) menu = Frame(self) self.sql = ms() self.mycursor = self.sql.mycursor self.db = self.sql.mydb l = Label(menu, text="Menu: ").pack(side=LEFT) bd = Button(menu, text="Dashboard", command=lambda: obj.display_page(obj.DashBoard)).pack(side = LEFT) bs = Button(menu, text="Sell", command=lambda: obj.display_page(obj.Sell)).pack(side = LEFT) bw = Button(menu, text="Watchlist", command=lambda: obj.display_page(obj.Watchlist)).pack(side = LEFT) menu.pack() self.mycursor.execute("select stock_name from Stocks ") stock_list=[] for row in self.mycursor.fetchall(): stock_list.append(row[0]) #print(stock_list) stock_frame = Frame(self) l2 = Label(stock_frame,text="Select stock you want to buy: ").pack(side = LEFT) stock_sel = StringVar() p = 0 def set_price(stock_sel): x = stock_sel.get() sql = "select pps,quantity,stock_id from stocks where stock_name = \"{}\" " self.mycursor.execute(sql.format(x)) qp = self.mycursor.fetchall()[0] global price global stock_id price= qp[0] p = price qty = qp[1] stock_id = qp[2] out1.delete(1.0, END) out1.insert(END, price) out2.delete(1.0, END) out2.insert(END, qty) self.sname = stock_sel.get() sel1 = ttk.Combobox(stock_frame,values = stock_list,textvariable = stock_sel).pack(side = LEFT) #print(stock_sel) price_frame = Frame(self) selb = Button(stock_frame,text = "Select",command = lambda : set_price(stock_sel)).pack(side = LEFT) l3 = Label(price_frame,text="Price of the stock: ").pack(side = LEFT) out1 = Text(price_frame,height = 2, width =15) out1.pack(side = LEFT) stock_frame.pack() price_frame.pack() qty_avail_frame = Frame(self) l3 = Label(qty_avail_frame, text="Quantity of the stock available: ").pack(side=LEFT) out2 = Text(qty_avail_frame, height=2, width=15) out2.pack(side=LEFT) qty_avail_frame.pack() buy_frame = Frame(self) l4 = Label(buy_frame,text = "How many stocks do you want to buy: ").pack(side = LEFT) quant = IntVar() qty = Entry(buy_frame,textvariable = quant).pack(side=LEFT) buy_frame.pack() confirm_frame = Frame(self) l5 = Label(confirm_frame,text = "Total ammount: ").pack(side = LEFT) out3 = Text(confirm_frame, height=2, width=15) out3.pack(side = LEFT) def confun(): out3.delete(1.0, END) out3.insert(END, (price * quant.get())) self.qty = quant.get() self.pps = price self.stock_id = stock_id conbut = Button(confirm_frame,text = "Total ammount",command = confun).pack() confirm_frame.pack() self.type = "B" self.mycursor.execute("select user_id from users where user_name = \"{}\"".format(obj.uname)) self.uid = self.mycursor.fetchone()[0] buy_button = Button(self,text=" BUY ",command=lambda: Transaction(self)).pack()
def signtxwithkey(self, raw_tx, sec): tx = Transaction.deserialize(raw_tx) pubkey = bitcoin.public_key_from_private_key(sec) tx.sign({pubkey: sec}) return tx
def do_payout_for_block(self, block): # check if we already paid out already_used = self.already_used(block.get_coinbase()) if already_used: return existing = self.mongo.db.share_payout.find_one({'index': block.index}) if existing: pending = self.mongo.db.miner_transactions.find_one({'inputs.id': block.get_coinbase().transaction_signature}) if pending: return else: # rebroadcast transaction = Transaction.from_dict(self.config, self.mongo, existing['txn']) TU.save(self.config, self.mongo, transaction) self.broadcast_transaction(transaction) return try: shares = self.get_share_list_for_height(block.index) except: return total_reward = block.get_coinbase() if total_reward.outputs[0].to != self.config.address: return pool_take = 0.01 total_pool_take = total_reward.outputs[0].value * pool_take total_payout = total_reward.outputs[0].value - total_pool_take outputs = [] for address, x in shares.iteritems(): exists = self.mongo.db.share_payout.find_one({'index': block.index, 'txn.outputs.to': address}) if exists: raise PartialPayoutException('this index has been partially paid out.') payout = total_payout * x['payout_share'] outputs.append(Output(to=address, value=payout)) try: transaction = TransactionFactory( self.config, self.mongo, fee=0.0001, public_key=self.config.public_key, private_key=self.config.private_key, inputs=[Input(total_reward.transaction_signature)], outputs=outputs ) except NotEnoughMoneyException as e: print "not enough money yet" return except Exception as e: print e try: transaction.transaction.verify() except: raise print 'faucet transaction failed' TU.save(self.config, self.mongo, transaction.transaction) self.mongo.db.share_payout.insert({'index': block.index, 'txn': transaction.transaction.to_dict()}) self.broadcast_transaction(transaction.transaction)
import pickle import time import sys sys.path.append('../src/') from transaction import Transaction from validator import Validator if __name__ == '__main__': Alice = Validator(port=1234) Bob = Validator(name="marshal-mbp.memphis.edu", addr="10.101.7.184", port=1234, bind=False) tx = pickle.dumps( Transaction(version=0.1, transaction_type='regular', tx_generator_address='0.0.0.0', inputs='', outputs='', lock_time=1234)) try: while True: # Send the serialized object to Bob #Alice.message(Bob, tx) Alice.receive() Alice.message(Bob, tx) time.sleep(1) except KeyboardInterrupt: Alice.close()
bar_str += "|" elif n < reach_int: bar_str += "-" else: bar_str += " " bar_str += '|]' if "|" not in bar_str else "]" return "{:>3}. {:20} {:65} {:8.2f} {:8.2f} {:8.2f} {:8.2f}/day".format( i, a.get_name(), bar_str, reached_total / 100, budget_total / 100, remain_total / 100, ideal_pace / 100) # Testing if __name__ == "__main__": from account import Budget t0 = Transaction(2015, 0, 12, "Fast Food", "Cash", "In-n-Out", 100) t1 = Transaction(2015, 1, 24, "Fast Food", "Cash", 'McDonald\'s', 200) t2 = Transaction(2015, 2, 24, "Fast Food", "Debit", "McDonald's", 300) t3 = Transaction(2015, 3, 24, "Fast Food", "Cash", "Wendy's", 400) t4 = Transaction(2015, 4, 23, "Fast Food", "Gifts", "Wendy's", 500) t5 = Transaction(2015, 5, 22, "Fast Food", "Savings", "Coffee", 600) t6 = Transaction(2015, 6, 12, "Fast Food", "Cash", "In-n-Out", 700) t7 = Transaction(2015, 7, 24, "Fast Food", "Cash", 'McDonald\'s', 800) t8 = Transaction(2015, 8, 24, "Fast Food", "Debit", "McDonald's", 900) t9 = Transaction(2015, 9, 24, "Fast Food", "Cash", "Wendy's", 1000) t10 = Transaction(2015, 10, 23, "Fast Food", "Gifts", "Wendy's", 1100) t11 = Transaction(2015, 11, 22, "Fast Food", "Savings", "Coffee", 1200) t12 = Transaction(2016, 11, 22, "Fast Food", "Savings", "Coffee", 1300) t13 = Transaction(2016, 10, 22, "Fast Food", "Savings", "Coffee", 1300) t14 = Transaction(2016, 10, 22, "Drinks", "Savings", "Coffee", 1200)
def createmultisig(self, num, pubkeys): assert isinstance(pubkeys, list) redeem_script = Transaction.multisig_script(pubkeys, num) address = hash_160_to_bc_address(hash_160(redeem_script.decode('hex')), 5) return {'address': address, 'redeemScript': redeem_script}