def load_data(self): try: with open('blockchain.p', mode='rb') as file: data = pickle.loads(file.read()) temp_chain = [] for i in data['blockchain']: block_obj = Block(i['index'], i['previous_hash'], [ Transaction(tx['_Transaction__sender'], tx['_Transaction__recipient'], tx['_Transaction__amount']) for tx in i['transactions'] ], i['proof'], i['timestamp']) temp_chain.append(block_obj) self.chain = temp_chain for i in data['open_txns']: txn = Transaction( i['_Transaction__sender'], i['_Transaction__recipient'], i['_Transaction__amount'], ) self.__open_transactions.append(txn) except (IOError, EOFError): pass
def main(): k_m = KeyManager() um = UTXOManager(k_m.my_address()) i_k_m = KeyManager() u_k_m = KeyManager() t1 = CoinbaseTransaction(k_m.my_address()) t2 = CoinbaseTransaction(k_m.my_address()) t3 = CoinbaseTransaction(k_m.my_address()) t4 = Transaction([TransactionInput(t1.to_dict(), 0)], [ TransactionOutput(u_k_m.my_address(), 10.0), TransactionOutput(i_k_m.my_address(), 20.0) ]) transactions = [] transactions.append(t1.to_dict()) transactions.append(t2.to_dict()) transactions.append(t3.to_dict()) transactions.append(t4.to_dict()) um.extract_utxos(transactions) balance = um.my_balance print(balance)
def test_loadedBlock(self): # load the generated block from the file with open('test_txn_one.dat', 'rb') as f: version = f.read(4) size_in_bytes = f.read(4) content_size = struct.unpack('I', size_in_bytes)[0] content = f.read(content_size) read_block = bytearray() read_block.extend(version) read_block.extend(size_in_bytes) read_block.extend(content) # Convert the read in block to a transaction object txn_in = Transaction() txn_in.parseFromBytes(read_block) # Get the content and convert to a string loadedContent = txn_in.getContent() loadedString = loadedContent.decode('utf-8') # Make sure it matches the original input self.assertEqual( loadedString, self.original_content, 'Content not correctly loaded')
def new_transaction(self, from_addr, to_addr, amount, fee): inputs = [] outputs = [] ifname = 'ens33' # enp2s0 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ip = socket.inet_ntoa( fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', bytes(ifname[:15], 'utf-8')))[20:24]) wallets = Wallets() from_wallet = wallets[from_addr] pub_key = from_wallet.public_key acc, valid_outpus = self._find_spendable_outputs(from_addr, amount) # if acc < amount + fee: # change # raise NotEnoughAmountError(u'not enough coin') for fout in valid_outpus: index = fout.index txid = fout.txid input = TXInput(txid, index, pub_key) inputs.append(input) output = TXOutput(amount, to_addr) outputs.append(output) if acc > amount + fee: # change # a change outputs.append(TXOutput(acc - amount - fee, from_addr)) # change tx = Transaction(inputs, outputs, fee, ip) # change tx.set_id() self.sign_transaction(tx, from_wallet.private_key) return tx
def mktx(nonce, gasprice, startgas, to, value, data): """Assemble an unsigned transaction. The result is the hex representation of the transaction in RLP encoding. """ tx = Transaction(nonce, gasprice, startgas, to, value, str(data)) click.echo(tx.hex_serialize(False))
def load_data(self): try: with open('blockchain.txt', mode='r') as f: # file_content = pickle.loads(f.read()) file_content = f.readlines() #print(file_content) blockchain = json.loads(file_content[0][:-1]) updated_blockchain = [] for block in blockchain: converted_tx = [ Transaction(tx['sender'], tx['recipient'], tx['amount']) for tx in block['transaction'] ] updated_block = Block(block['index'], block['previous_hash'], converted_tx, block['proof'], block['timestamp']) updated_blockchain.append(updated_block) self.chain = updated_blockchain open_transaction = json.loads(file_content[1]) updated_transactions = [] for tx in open_transaction: updated_transaction = Transaction(tx['sender'], tx['recipient'], tx['amount']) updated_transactions.append(updated_transaction) self.open_transaction = updated_transactions except (IOError, IndexError): pass finally: print("cleanup!")
def load_data(self): try: with open('blockchain.txt', mode='r') as f: ## file_content = pickle.loads(f.read()) file_content = f.readlines() ## blockchain = file_content['chain'] ## open_transactions = file_content['ot'] blockchain = json.loads(file_content[0][:-1]) updated_blockchain = [] for block in blockchain: # les blocks sont maintenant des objets block, et non plus des dictionnaires converted_tx = [Transaction(tx['sender'],tx['recipient'],tx['amount']) for tx in block['transactions']] updated_block = Block(block['index'], block['previous_hash'], converted_tx, block['proof'], block['timestamp']) updated_blockchain.append(updated_block) self.chain = updated_blockchain open_transactions = json.loads(file_content[1]) updated_transactions = [] for tx in open_transactions: updated_transaction = Transaction(tx['sender'],tx['recipient'],tx['amount']) updated_transactions.append(updated_transaction) self.__open_transactions = updated_transactions except (IOError, IndexError): pass finally: print('Cleanup!')
def createTransaction(self, sender, recipient, amount): """ Creates a transaction to go into the next block """ transaction = Transaction(sender, recipient, amount) if transaction.validate(): self.__currentTransactionsList.append(transaction) return transaction, True return None, False
def quicktx(client, gasprice, startgas, to, value, data, key): """Create and finalize a transaction. This command is a shortcut that chains getnonce, mktx, signtx, and applytx. It returns the server's response. """ encoded_key = encode_privkey(key, 'hex') nonce = int(client.getaccount(utils.privtoaddr(encoded_key))['nonce']) tx = Transaction(nonce, gasprice, startgas, to, value, str(data)) tx.sign(encode_privkey(key, 'hex')) pecho(client.applytx(tx))
def test_signing_simple_transaction(self): inputs = [ ('b0ff74bb0dd894797153ccb862c9f9a488e657452647ada440fe1006ece95c78', 0), ] outputs = [ ('115MDLurYMiExVwfTU7R4kE43zrdVoC2pz', 50000000), ] tx = Transaction(inputs, outputs) txCopy = tx.generate_signing_form(0, self.key)
def setUp(self): inputs = [ ('b0ff74bb0dd894797153ccb862c9f9a488e657452647ada440fe1006ece95c78', 0), ('683d180645632d45f23baf2fb2897241321c1af779f3064ebd24aa517bae6a22', 0), ] outputs = [ ('1EL3y9j8rzZwa8Hxmx2scatb3bh8KKFK6v', 1000), ('115MDLurYMiExVwfTU7R4kE43zrdVoC2pz', 49585000), ] self.tx = Transaction(inputs, outputs)
def main(): genesis_transaction = Transaction("Logan", "Dorian", 3) # initialize genesis genesis_block = Block("wow you're cool if you find this message...", genesis_transaction) second_transaction = Transaction("Terry", "Bob", 42) second_block = Block(genesis_block.hash, second_transaction) print(genesis_block.hash) print(second_block.hash)
def new_transaction(self, sender, recipient, energy_amount, price, bid_type, electric_hash): """ Creates a new transaction to go into the next mined Block :param sender: Address of the Sender :param recipient: Address of the Recipient :param amount: Amount :return: The index of the Block that will hold this transaction """ tr = Transaction(bid_id=len(self.current_transactions), # this may be repeated but it is only used to print seller_id=sender, buyer_id=recipient, energy_amount=energy_amount, price=price, bid_type=bid_type, bid_hash=electric_hash) # self.current_transactions.append({ # 'sender': sender, # 'recipient': recipient, # 'energy_amount': energy_amount, # 'price': price, # 'bid_type': bid_type, # 'electric_hash': electric_hash # }) self.current_transactions.append(tr) return self.last_block['index'] + 1
async def commit_messages_from_backlog(self): """ Validates a block send from the leader and appends it to the local blockchain. :return: """ while not self._backlog.empty(): message = self._backlog.get() term = message.get('term') broadcasted_message = json.loads( self.messages_to_save[message['uuid']]['data']) data = json.loads(message['data']) message_integrity = broadcasted_message == data if message_integrity: new_transaction = Transaction( **json.loads(data['pending_messages'][0])) data['pending_messages'] = [new_transaction] new_block = Block(**data) self.blockchain.add_block(new_block) self.blockchain.save() await self.broadcast_to_clients({ 'type': 'client_commit_confirm', 'source_term': term }) else: await self.start_election()
def parseTransactionsInAccount(account): account_transactions = [] for transactions in account['data']: date_acquired = "-" date_sold = "-" if "buy" == transactions["type"]: date_acquired = transactions["updated_at"] elif "sell" == transactions["type"]: date_sold = transactions["updated_at"] else: continue description = transactions["details"]["title"] crypto_currency = transactions["amount"]["currency"] crypto_amount = transactions["amount"]["amount"] proceeds = transactions["native_amount"]["amount"] currency = transactions["native_amount"]["currency"] current_transaction = Transaction(description, crypto_currency, crypto_amount, date_acquired, date_sold, proceeds, currency) account_transactions.append(current_transaction) return account_transactions
def remote_transactions_received_handler(sender, transactions, peer, **kwargs): "receives rlp.decoded serialized" txl = [Transaction.deserialize(rlp.encode(tx)) for tx in transactions] log_api.debug('remote_transactions_received', count=len(txl), remote_id=peer) for tx in txl: peermanager.txfilter.add(tx, peer) # FIXME chain_manager.add_transaction(tx)
def __init__(self, data=None): if not data: return if re.match('^[0-9a-fA-F]*$', data): data = data.decode('hex') header, transaction_list, self.uncles = rlp.decode(data) [ self.number, self.prevhash, self.uncles_root, self.coinbase, state_root, self.transactions_root, self.difficulty, self.timestamp, self.nonce, self.extra ] = header self.transactions = [Transaction(x) for x in transaction_list] self.state = Trie('statedb', state_root) self.reward = 0 # Verifications if self.state.root != '' and self.state.db.get(self.state.root) == '': raise Exception("State Merkle root not found in database!") if bin_sha256(rlp.encode(transaction_list)) != self.transactions_root: raise Exception("Transaction list root hash does not match!") if bin_sha256(rlp.encode(self.uncles)) != self.uncles_root: raise Exception("Uncle root hash does not match!")
def add_transaction(self, sender, recipient, signature, amount, broadcast=False): # if self.node is None: # return False transaction = Transaction(sender, recipient, signature, amount) if Wallet.verify_signture(transaction): if Verification.verify_transaction(transaction, sender, self.get_balance): self.open_transactions.append(transaction) FileHandler.save_j_chain(self) if not broadcast: for node in self.__peer_nodes: url = "http://{}/broadcast-transaction".format(node) try: response = requests.post(url, json={"sender":sender, "recipient":recipient, "amount":amount, "signature":signature}) if response.status_code == 400 or response.status_code == 500: print("Transaction declined, needs resolving") return False except requests.exceptions.ConnectionError: continue return True else: print("This Transaction is not possible, as it exceeds your balance!") return False else: print("The Signature of this transaction is not valid") return False return True
def get_transaction(self, txhash): "return (tx, block)" blockhash, tx_num_enc = rlp.decode(self.db.get(txhash)) blk = blocks.get_block(blockhash) num = utils.decode_int(tx_num_enc) tx_data, msr, gas = blk.get_transaction(num) return Transaction.create(tx_data), blk
def mine_block(self): if self.node is None: return None last_block = self.get_last_entry() hash_value = hash_util.hash_block(last_block) proof = self.proof_of_work(hash_value) mining_transaction = Transaction("MINING", self.node, "", self.MINING_REWARD) self.open_transactions.append(mining_transaction) block = JBlock(len(self.chain), hash_value, self.open_transactions, proof) if self.transaction_signature_is_valid(block): self.__chain.append(block) self.open_transactions = [] FileHandler.save_j_chain(self) for node in self.__peer_nodes: url = "http://{}/broadcast-block".format(node) try: converted_block = block.__dict__.copy() converted_block["transactions"] = [transaction.__dict__ for transaction in converted_block["transactions"]] response = requests.post(url, json={"block": converted_block}) if response.status_code == 400 or response.status_code == 500: print("block declined, needs resolving") if response.status_code == 409: self.resolve_conflicts = True except requests.exceptions.ConnectionError: continue return block else: print("Fehler: Die Transactionen wurden geändert") return None
def add_transaction(self, recipient, sender, amount = 1.0): """Append a new value as well as the last blockchain value to the blockchain Arguments: :Sender : the sender of the coins :Recipient : the recipient of the coins :Amount : the amount of coins sent (default = 1 coin) """ #transaction = { # 'Sender': sender, # 'Recipient': recipient, # 'Amount': amount #} transaction = Transaction(sender, recipient, amount) if Verification.verify_transaction(transaction, self.get_balance): self.__open_transactions.append(transaction) self.save_data() return True return False
def resolve(self): winner_chain = self.chain replace = False for node in self.__peer_nodes: url = "http://{}/chain".format(node) try: response = requests.get(url) node_chain = response.json() node_chain = [JBlock(block["index"], block["previous_hash"], [Transaction(transaction["sender"], transaction["recipient"], transaction["signature"], transaction["amount"]) for transaction in block["transactions"]], block["proof"], block["timestamp"]) for block in node_chain] node_chain_lenght = len(node_chain) local_chain_lenght = len(self.chain) if node_chain_lenght > local_chain_lenght and Verification.validate_j_chain(node_chain): winner_chain = node_chain replace = True except requests.exceptions.ConnectionError: continue self.resolve_conflicts = False self.chain = winner_chain if replace: self.open_transactions = [] FileHandler.save_j_chain(self) return replace
def trans_generator(env): ''' 1. Generates transaction in a random time derived from Mean Transaction generation time and its Standard Deviation. 2. Assigns the transaction to a node radomly from the list of transactions. ''' # Use a global ID for transaction global txID txID = 2300 while True: # Generate random transaction size and gas TX_SIZE = random.gauss(config['mean_tx_size'], config['sd_tx_size']) TX_GAS = random.gauss(config['mean_tx_gas'], config['sd_tx_gas']) txID += 1 transaction = Transaction(TX_GAS, TX_SIZE, txID) # Choose a node randomly from the nodelist #node = random.choice(nodelist) # choose a node manually node = 100 # select a sealer # Assign the task to the node; Find the node object with the nodeID for i in node_map: if i.nodeID == node: #print("%d, %d, Appended, Transaction, %d"%(env.now,i.nodeID,txID)) logger.debug("%d, %d,Appended, Transaction, %d" % (env.now, i.nodeID, txID)) i.add_transaction(transaction) yield env.timeout( random.gauss(config['mean_tx_generation'], config['sd_tx_generation']))
def receive(obj): d = rlp.decode(obj) # Is transaction if len(d) == 8: tx = Transaction(obj) if mainblk.get_balance(tx.sender) < tx.value + tx.fee: return if mainblk.get_nonce(tx.sender) != tx.nonce: return txpool[bin_sha256(blk)] = blk broadcast(blk) # Is message elif len(d) == 2: if d[0] == 'getobj': try: return db.Get(d[1][0]) except: try: return mainblk.state.db.get(d[1][0]) except: return None elif d[0] == 'getbalance': try: return mainblk.state.get_balance(d[1][0]) except: return None elif d[0] == 'getcontractroot': try: return mainblk.state.get_contract(d[1][0]).root except: return None elif d[0] == 'getcontractsize': try: return mainblk.state.get_contract(d[1][0]).get_size() except: return None elif d[0] == 'getcontractstate': try: return mainblk.state.get_contract(d[1][0]).get(d[1][1]) except: return None # Is block elif len(d) == 3: blk = Block(obj) p = block.prevhash try: parent = Block(db.Get(p)) except: return uncles = block.uncles for s in uncles: try: sib = db.Get(s) except: return processblock.eval(parent, blk.transactions, blk.timestamp, blk.coinbase) if parent.state.root != blk.state.root: return if parent.difficulty != blk.difficulty: return if parent.number != blk.number: return db.Put(blk.hash(), blk.serialize())
def new_transaction(): values = request.get_json() # Check that the required fields are in the POST'ed data required = ['sender', 'recipient', 'amount'] if not all(k in values for k in required): return 'Missing values', 400 # Create a new Transaction transaction = Transaction(values['sender'], values['recipient'], values['amount']) index = transaction.addToLocalDB() #index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = {'message': f'Transaction will be added to Block {index-1}'} return jsonify(response), 201
def deserialize(cls, data): block_header_dict = data['block_header'] block_header = BlockHeader.deserialize(block_header_dict) transactions = data["transactions"] txs = [] for transaction in transactions: txs.append(Transaction.deserialize(transaction)) return cls(block_header, txs)
class TestTransaction(unittest.TestCase): def setUp(self): self.a = Client(1, "IVan", 10, "None", "*****@*****.**") self.b = Client(2, "Muhamed", 15, "None", "*****@*****.**") self.t = Transaction(self.a) def test_deposit(self): self.t.deposit(100) self.assertEqual(self.a.get_balance(), 110) def test_withdraw(self): self.assertFalse(self.t.withdraw(100)) self.t.withdraw(10) self.assertEqual(self.a.get_balance(), 0) def test_show_balance(self): self.assertEqual(str(self.t), "Client: IVan has 10$ in his account.")
def generateGenesisBlock(self): transaction_0 = Transaction(type='Root', timestamp=self.get_time(), message='Genesis Block') local_transaction = [transaction_0] genesis = Block(0, self.get_time(), local_transaction, 0, 0) genesis.hash = '000' return genesis
def handle_transaction(self, msg): data = msg.get("data", {}) tx = Transaction.deserialize(data) tx_pool = TxPool() tx_pool.add(tx) if tx_pool.is_full(): bc.add_block(tx_pool.txs) log.info("mined a block") tx_pool.clear()
def load_data(j_chain, open_transactions, peer_nodes, port): try: with open("blockchain-{}.txt".format(port), mode="r") as f: file_content = f.readlines() blockchain = json.loads(file_content[0][:-1]) updated_j_chain = [] for block in blockchain: previous_hash = block["previous_hash"] index = block["index"] proof = block["proof"] timestamp = block["timestamp"] transactions = [ Transaction(transaction["sender"], transaction["recipient"], transaction["signature"], transaction["amount"]) for transaction in block["transactions"] ] updated_block = JBlock(index, previous_hash, transactions, proof, timestamp) updated_j_chain.append(updated_block) open_transactions = json.loads(file_content[1][:-1]) updated_transactions = [] for transaction in open_transactions: updated_transaction = Transaction(transaction["sender"], transaction["recipient"], transaction["signature"], transaction["amount"]) updated_transactions.append(updated_transaction) j_chain = updated_j_chain open_transactions = updated_transactions peer_nodes = set(json.loads(file_content[2])) except (IOError, IndexError): print("File not found: Make file") f = open("blockchain-{}.txt".format(port), mode="w+") f.close() return j_chain, open_transactions, peer_nodes
def applytx(client, transaction): """Absorb a transaction into the next block. This command sends a transaction to the server, which will presumably validate it, include it in its memory pool, and further announce it to the network. The server's response will be returned. TRANSACTION must a signed transaction in hex-encoding. """ tx = Transaction.deserialize(str(transaction)) pecho(client.applytx(tx))
def test_newTransaction(self): # Create a new transaction txn = Transaction() txn.setContent(self.byte_content) digest = txn.getDigest() # Verify the header digest from farming to # the expected one self.assertEqual( digest.hex(), self.expected_transaction_digest, 'Wrong transaction digest') # Check the contents of the full block against # the expected content inBytes = txn.toBytes() self.assertEqual(inBytes.hex(), self.expected_full_transaction, 'Wrong full transaction content') with open('test_txn_one.dat', 'wb') as f: f.write(inBytes)
def signtx(transaction, key): """Sign a previously created transaction. TRANSACTION must be the hex encoded transaction, as for instance created using mktx or mkcontract. If it has already been signed before, its signature will be replaced. KEY must be the private key to sign with, in hexadecimal encoding or WIF. The signed transaction will be printed in hex encoding. """ try: tx = Transaction.deserialize(str(transaction)) except AssertionError: raise click.BadParameter('Unable to deserialize TRANSACTION.') tx.sign(encode_privkey(key, 'hex')) click.echo(tx.hex_serialize(True))
def update_database(data): print('updating db') # start upload text if int(data['rows_saved']) > 0: if 'saved' in data: saved = data['saved'] if 'addresses' in saved: for addresses in saved['addresses']: address = Address() where = {'id': addresses['id']} data = {'address_id': addresses['address_id']} address.put(where=where, data=data) if 'colors' in saved: for colors in saved['colors']: color = Colored() where = {'id': colors['id']} data = {'color_id': colors['color_id']} color.put(where=where, data=data) if 'cards' in saved: for cards in saved['cards']: card = Card() where = {'id': cards['id']} data = {'card_id': cards['card_id']} card.put(where=where, data=data) if 'credits' in saved: for credit in saved['credits']: credits = Credit() where = {'id': credit['id']} data = {'credit_id': credit['credit_id']} credits.put(where=where, data=data) if 'companies' in saved: for companies in saved['companies']: company = Company() where = {'id': companies['id']} data = {'company_id': companies['company_id']} company.put(where=where, data=data) if 'custids' in saved: for custids in saved['custids']: custid = Custid() where = {'id': custids['id']} data = {'cust_id': custids['cust_id']} custid.put(where=where, data=data) if 'deliveries' in saved: for deliveries in saved['deliveries']: delivery = Delivery() where = {'id': deliveries['id']} data = {'delivery_id': deliveries['delivery_id']} delivery.put(where=where, data=data) if 'discounts' in saved: for discounts in saved['discounts']: discount = Discount() where = {'id': discounts['id']} data = {'discount_id': discounts['discount_id']} discount.put(where=where, data=data) if 'inventories' in saved: for inventories in saved['inventories']: inventory = Inventory() where = {'id': inventories['id']} data = {'inventory_id': inventories['inventory_id']} inventory.put(where=where, data=data) if 'inventory_items' in saved: for inventory_items in saved['inventory_items']: inventory_item = InventoryItem() where = {'id': inventory_items['id']} data = {'item_id': inventory_items['item_id']} inventory_item.put(where=where, data=data) if 'invoices' in saved: for invoices in saved['invoices']: invoice = Invoice() where = {'id': invoices['id']} data = {'invoice_id': invoices['invoice_id']} invoice.put(where=where, data=data) if 'invoice_items' in saved: for invoice_items in saved['invoice_items']: invoice_item = InvoiceItem() where = {'id': invoice_items['id']} data = {'invoice_items_id': invoice_items['invoice_items_id']} invoice_item.put(where=where, data=data) if 'memos' in saved: for memos in saved['memos']: memo = Memo() where = {'id': memos['id']} data = {'memo_id': memos['memo_id']} memo.put(where=where, data=data) if 'printers' in saved: for printers in saved['printers']: printer = Printer() where = {'id': printers['id']} data = {'printer_id': printers['printer_id']} printer.put(where=where, data=data) if 'profiles' in saved: for profiles in saved['profiles']: profile = Profile() where = {'id': profiles['id']} data = {'p_id': profiles['p_id']} profile.put(where=where, data=data) if 'reward_transactions' in saved: for reward_transactions in saved['reward_transactions']: reward_transaction = RewardTransaction() where = {'id': reward_transactions['id']} data = {'reward_id': reward_transactions['reward_id']} reward_transaction.put(where=where, data=data) if 'rewards' in saved: for rewards in saved['rewards']: reward = Reward() where = {'id': rewards['id']} data = {'reward_id': rewards['reward_id']} reward.put(where=where, data=data) if 'schedules' in saved: for schedules in saved['schedules']: schedule = Schedule() where = {'id': schedules['id']} data = {'schedule_id': schedules['schedule_id']} schedule.put(where=where, data=data) if 'taxes' in saved: for taxes in saved['taxes']: tax = Tax() where = {'id': taxes['id']} data = {'tax_id': taxes['tax_id']} tax.put(where=where, data=data) if 'transactions' in saved: for transactions in saved['transactions']: transaction = Transaction() where = {'id': transactions['id']} data = {'trans_id': transactions['trans_id']} transaction.put(where=where, data=data) if 'users' in saved: for users in saved['users']: user = User() where = {'id': users['id']} data = {'user_id': users['user_id']} user.put(where=where, data=data) if 'zipcodes' in saved: for zipcodes in saved['zipcodes']: zipcode = Zipcode() where = {'id': zipcodes['id']} data = {'zipcode_id': zipcodes['zipcode_id']} zipcode.put(where=where, data=data)
def sync_from_server(data): # print('sync from server') # start upload text # print(data) # print(data['rows_to_create']) if int(data['rows_to_create']) > 0: updates = data['updates'] if 'addresses' in updates: for addresses in updates['addresses']: address = Address() address.address_id = addresses['id'] address.user_id = addresses['user_id'] address.name = addresses['name'] address.street = addresses['street'] address.suite = addresses['suite'] address.city = addresses['city'] address.state = addresses['state'] address.zipcode = addresses['zipcode'] address.primary_address = addresses['primary_address'] address.concierge_name = addresses['concierge_name'] address.concierge_number = addresses['concierge_number'] address.status = addresses['status'] address.deleted_at = addresses['deleted_at'] address.created_at = addresses['created_at'] address.updated_at = addresses['updated_at'] # check to see if color_id already exists and update count_address = address.where({'address_id': address.address_id}) if len(count_address) > 0 or address.deleted_at: for data in count_address: address.id = data['id'] if address.deleted_at: address.delete() else: address.update_special() else: address.add_special() address.close_connection() if 'cards' in updates: for cards in updates['cards']: card = Card() card.card_id = cards['id'] card.company_id = cards['company_id'] card.user_id = cards['user_id'] card.profile_id = cards['profile_id'] card.payment_id = cards['payment_id'] card.root_payment_id = cards['root_payment_id'] card.street = cards['street'] card.suite = cards['suite'] card.city = cards['city'] card.state = cards['state'] card.zipcode = cards['zipcode'] card.exp_month = cards['exp_month'] card.exp_year = cards['exp_year'] card.status = cards['status'] card.deleted_at = cards['deleted_at'] card.created_at = cards['created_at'] card.updated_at = cards['updated_at'] # check to see if color_id already exists and update count_card = card.where({'card_id': card.card_id}) if len(count_card) > 0 or card.deleted_at: for data in count_card: card.id = data['id'] if card.deleted_at: card.delete() else: card.update_special() else: card.add_special() card.close_connection() if 'colors' in updates: for colors in updates['colors']: color = Colored() color.color_id = colors['id'] color.company_id = colors['company_id'] color.color = colors['color'] color.name = colors['name'] color.ordered = colors['ordered'] color.status = colors['status'] color.deleted_at = colors['deleted_at'] color.created_at = colors['created_at'] color.updated_at = colors['updated_at'] # check to see if color_id already exists and update count_color = color.where({'color_id': color.color_id}) if len(count_color) > 0 or color.deleted_at: for data in count_color: color.id = data['id'] if color.deleted_at: color.delete() else: color.update_special() else: color.add_special() color.close_connection() if 'companies' in updates: for companies in updates['companies']: company = Company() company.company_id = companies['id'] company.name = companies['name'] company.street = companies['street'] company.city = companies['city'] company.state = companies['state'] company.zip = companies['zip'] company.email = companies['email'] company.phone = companies['phone'] company.store_hours = companies['store_hours'] company.turn_around = companies['turn_around'] company.api_token = companies['api_token'] company.payment_gateway_id = companies['payment_gateway_id'] company.payment_api_login = companies['payment_api_login'] company.deleted_at = companies['deleted_at'] company.created_at = companies['created_at'] company.updated_at = companies['updated_at'] company.server_at = now count_company = company.where({'company_id': company.company_id}) if len(count_company) > 0 or company.deleted_at: for data in count_company: company.id = data['id'] if company.deleted_at: company.delete() else: company.update_special() else: company.add_special() company.close_connection() if 'credits' in updates: for credits in updates['credits']: credit = Credit() credit.credit_id = credits['id'] credit.employee_id = credits['employee_id'] credit.customer_id = credits['customer_id'] credit.amount = credits['amount'] credit.reason = credits['reason'] credit.status = credits['status'] credit.deleted_at = credits['deleted_at'] credit.created_at = credits['created_at'] credit.updated_at = credits['updated_at'] # check to see already exists and update count_credit = credit.where({'credit_id': credit.credit_id}) if len(count_credit) > 0 or credit.deleted_at: for data in count_credit: credit.id = data['id'] if credit.deleted_at: credit.delete() else: credit.update_special() else: credit.add_special() credit.close_connection() if 'custids' in updates: for custids in updates['custids']: custid = Custid() custid.cust_id = custids['id'] custid.customer_id = custids['customer_id'] custid.company_id = custids['company_id'] custid.mark = custids['mark'] custid.status = custids['status'] custid.deleted_at = custids['deleted_at'] custid.created_at = custids['created_at'] custid.updated_at = custids['updated_at'] count_custid = custid.where({'cust_id': custids['id']}) if len(count_custid) > 0 or custid.deleted_at: for data in count_custid: custid.id = data['id'] if custid.deleted_at: custid.delete() else: custid.update_special() else: custid.add_special() custid.close_connection() if 'deliveries' in updates: for deliveries in updates['deliveries']: delivery = Delivery() delivery.delivery_id = deliveries['id'] delivery.company_id = deliveries['company_id'] delivery.route_name = deliveries['route_name'] delivery.day = deliveries['day'] delivery.delivery_limit = deliveries['limit'] delivery.start_time = deliveries['start_time'] delivery.end_time = deliveries['end_time'] delivery.zipcode = deliveries['zipcode'] delivery.blackout = deliveries['blackout'] delivery.status = deliveries['status'] delivery.deleted_at = deliveries['deleted_at'] delivery.created_at = deliveries['created_at'] delivery.updated_at = deliveries['updated_at'] count_delivery = delivery.where({'delivery_id': delivery.delivery_id}) if len(count_delivery) > 0 or delivery.deleted_at: for data in count_delivery: delivery.id = data['id'] if delivery.deleted_at: delivery.delete() else: delivery.update_special() else: delivery.add_special() delivery.close_connection() if 'discounts' in updates: for discounts in updates['discounts']: discount = Discount() discount.discount_id = discounts['id'] discount.company_id = discounts['company_id'] discount.inventory_id = discounts['inventory_id'] discount.inventory_item_id = discounts['inventory_item_id'] discount.name = discounts['name'] discount.type = discounts['type'] discount.discount = discounts['discount'] discount.rate = discounts['rate'] discount.end_time = discounts['end_time'] discount.start_date = discounts['start_date'] discount.end_date = discounts['end_date'] discount.status = discounts['status'] discount.deleted_at = discounts['deleted_at'] discount.created_at = discounts['created_at'] discount.updated_at = discounts['updated_at'] count_discount = discount.where({'discount_id': discount.discount_id}) if len(count_discount) > 0 or discount.deleted_at: for data in count_discount: discount.id = data['id'] if discount.deleted_at: discount.delete() else: discount.update_special() else: discount.add_special() discount.close_connection() if 'inventories' in updates: for inventories in updates['inventories']: inventory = Inventory() inventory.inventory_id = inventories['id'] inventory.company_id = inventories['company_id'] inventory.name = inventories['name'] inventory.description = inventories['description'] inventory.ordered = inventories['ordered'] inventory.laundry = inventories['laundry'] inventory.status = inventories['status'] inventory.deleted_at = inventories['deleted_at'] inventory.create_at = inventories['created_at'] inventory.updated_at = inventories['updated_at'] count_inventory = inventory.where({'inventory_id': inventory.inventory_id}) if len(count_inventory) > 0 or inventory.deleted_at: for data in count_inventory: inventory.id = data['id'] if inventory.deleted_at: inventory.delete() else: inventory.update_special() else: inventory.add_special() inventory.close_connection() if 'inventory_items' in updates: for inventory_items in updates['inventory_items']: inventory_item = InventoryItem() inventory_item.item_id = inventory_items['id'] inventory_item.inventory_id = inventory_items['inventory_id'] inventory_item.company_id = inventory_items['company_id'] inventory_item.name = inventory_items['name'] inventory_item.description = inventory_items['description'] inventory_item.tags = inventory_items['tags'] inventory_item.quantity = inventory_items['quantity'] inventory_item.ordered = inventory_items['ordered'] inventory_item.price = inventory_items['price'] inventory_item.image = inventory_items['image'] inventory_item.status = inventory_items['status'] inventory_item.deleted_at = inventory_items['deleted_at'] inventory_item.created_at = inventory_items['created_at'] inventory_item.updated_at = inventory_items['updated_at'] count_inventory_item = inventory_item.where({'item_id': inventory_item.item_id}) if len(count_inventory_item) > 0 or inventory_item.deleted_at: for data in count_inventory_item: inventory_item.id = data['id'] if inventory_item.deleted_at: inventory_item.delete() else: inventory_item.update_special() else: inventory_item.add_special() inventory_item.close_connection() # if 'invoice_items' in updates: # for invoice_items in updates['invoice_items']: # invoice_item = InvoiceItem() # invoice_item.invoice_items_id = invoice_items['id'] # invoice_item.invoice_id = invoice_items['invoice_id'] # invoice_item.item_id = invoice_items['item_id'] # invoice_item.inventory_id = invoice_items['inventory_id'] # invoice_item.company_id = invoice_items['company_id'] # invoice_item.customer_id = invoice_items['customer_id'] # invoice_item.quantity = invoice_items['quantity'] # invoice_item.color = invoice_items['color'] # invoice_item.memo = invoice_items['memo'] # invoice_item.pretax = invoice_items['pretax'] # invoice_item.tax = invoice_items['tax'] # invoice_item.total = invoice_items['total'] # invoice_item.status = invoice_items['status'] # invoice_item.deleted_at = invoice_items['deleted_at'] # invoice_item.created_at = invoice_items['created_at'] # invoice_item.updated_at = invoice_items['updated_at'] # count_invoice_item = invoice_item.where({'invoice_items_id': invoice_item.invoice_items_id}) # if len(count_invoice_item) > 0 or invoice_item.deleted_at: # for data in count_invoice_item: # invoice_item.id = data['id'] # if invoice_item.deleted_at: # invoice_item.delete() # else: # invoice_item.update_special() # else: # invoice_item.add_special() # invoice_item.close_connection() # # if 'invoices' in updates: # # for invoices in updates['invoices']: # invoice = Invoice() # invoice.invoice_id = invoices['id'] # invoice.company_id = invoices['company_id'] # invoice.customer_id = invoices['customer_id'] # invoice.quantity = invoices['quantity'] # invoice.pretax = invoices['pretax'] # invoice.tax = invoices['tax'] # invoice.reward_id = invoices['reward_id'] # invoice.discount_id = invoices['discount_id'] # invoice.total = invoices['total'] # invoice.rack = invoices['rack'] # invoice.rack_date = invoices['rack_date'] # invoice.due_date = invoices['due_date'] # invoice.memo = invoices['memo'] # invoice.transaction_id = invoices['transaction_id'] # invoice.schedule_id = invoices['schedule_id'] # invoice.status = invoices['status'] # invoice.deleted_at = invoices['deleted_at'] # invoice.created_at = invoices['created_at'] # invoice.updated_at = invoices['updated_at'] # # # extra loop through invoice items to delete or check for data # if 'invoice_items' in invoices: # # iitems = invoices['invoice_items'] # if len(iitems) > 0: # for iitem in iitems: # invoice_item = InvoiceItem() # invoice_item.invoice_items_id = iitem['id'] # invoice_item.invoice_id = iitem['invoice_id'] # invoice_item.item_id = iitem['item_id'] # invoice_item.inventory_id = iitem['inventory_id'] # invoice_item.company_id = iitem['company_id'] # invoice_item.customer_id = iitem['customer_id'] # invoice_item.quantity = iitem['quantity'] # invoice_item.color = iitem['color'] # invoice_item.memo = iitem['memo'] # invoice_item.pretax = iitem['pretax'] # invoice_item.tax = iitem['tax'] # invoice_item.total = iitem['total'] # invoice_item.status = iitem['status'] # invoice_item.deleted_at = iitem['deleted_at'] # invoice_item.created_at = iitem['created_at'] # invoice_item.updated_at = iitem['updated_at'] # count_invoice_item = invoice_item.where({'invoice_items_id': invoice_item.invoice_items_id}) # if len(count_invoice_item) > 0 or invoice_item.deleted_at: # for data in count_invoice_item: # invoice_item.id = data['id'] # if invoice_item.deleted_at: # invoice_item.delete() # else: # invoice_item.update_special() # # count_invoice = invoice.where({'invoice_id': invoice.invoice_id}) # if len(count_invoice) > 0 or invoice.deleted_at: # for data in count_invoice: # invoice.id = data['id'] # if invoice.deleted_at: # invoice.delete() # else: # invoice.update_special() # else: # invoice.add_special() # invoice.close_connection() if 'memos' in updates: for memos in updates['memos']: memo = Memo() memo.memo_id = memos['id'] memo.company_id = memos['company_id'] memo.memo = memos['memo'] memo.ordered = memos['ordered'] memo.status = memos['status'] memo.deleted_at = memos['deleted_at'] memo.created_at = memos['created_at'] memo.updated_at = memos['updated_at'] count_memo = memo.where({'memo_id': memo.memo_id}) if len(count_memo) > 0 or memo.deleted_at: for data in count_memo: memo.id = data['id'] if memo.deleted_at: memo.delete() else: memo.update_special() else: memo.add_special() memo.close_connection() # if 'printers' in updates: # for printers in updates['printers']: # printer = Printer() # printer.printer_id = printers['id'] # printer.company_id = printers['company_id'] # printer.name = printers['name'] # printer.model = printers['model'] # printer.nick_name = printers['nick_name'] # printer.type = printers['type'] # printer.vendor_id = printers['vendor_id'] # printer.product_id = printers['product_id'] # printer.status = printers['status'] # printer.deleted_at = printers['deleted_at'] # printer.created_at = printers['created_at'] # printer.updated_at = printers['updated_at'] # count_printer = printer.where({'printer_id': printer.printer_id}) # if len(count_printer) > 0 or printer.deleted_at: # for data in count_printer: # printer.id = data['id'] # if printer.deleted_at: # printer.delete() # else: # printer.update_special() # else: # printer.add_special() # printer.close_connection() if 'profiles' in updates: for profiles in updates['profiles']: profile = Profile() profile.p_id = profiles['id'] profile.company_id = profiles['company_id'] profile.user_id = profiles['user_id'] profile.profile_id = profiles['profile_id'] profile.status = profiles['status'] profile.deleted_at = profiles['deleted_at'] profile.created_at = profiles['created_at'] profile.updated_at = profiles['updated_at'] count_profile = profile.where({'p_id': profile.p_id}) if len(count_profile) > 0 or profile.deleted_at: for data in count_profile: profile.id = data['id'] if profile.deleted_at: profile.delete() else: profile.update_special() else: profile.add_special() profile.close_connection() if 'reward_transactions' in updates: for reward_transactions in updates['reward_transactions']: reward_transaction = RewardTransaction() reward_transaction.reward_id = reward_transactions['reward_id'] reward_transaction.transaction_id = reward_transactions['transaction_id'] reward_transaction.customer_id = reward_transactions['customer_id'] reward_transaction.employee_id = reward_transactions['employee_id'] reward_transaction.company_id = reward_transactions['company_id'] reward_transaction.type = reward_transactions['type'] reward_transaction.points = reward_transactions['points'] reward_transaction.credited = reward_transactions['credited'] reward_transaction.reduced = reward_transactions['reduced'] reward_transaction.running_total = reward_transactions['running_total'] reward_transaction.reason = reward_transactions['reason'] reward_transaction.name = reward_transactions['name'] reward_transaction.status = reward_transactions['status'] reward_transaction.deleted_at = reward_transactions['deleted_at'] reward_transaction.created_at = reward_transactions['created_at'] reward_transaction.updated_at = reward_transactions['updated_at'] count_reward_transaction = reward_transaction.where({'reward_id': reward_transaction.reward_id}) if len(count_reward_transaction) > 0 or reward_transaction.deleted_at: for data in count_reward_transaction: reward_transaction.id = data['id'] if reward_transaction.deleted_at: reward_transaction.delete() else: reward_transaction.update_special() else: reward_transaction.add_special() reward_transaction.close_connection() if 'rewards' in updates: for rewards in updates['rewards']: reward = Reward() reward.reward_id = rewards['id'] reward.company_id = rewards['company_id'] reward.name = rewards['name'] reward.points = rewards['points'] reward.discount = rewards['discount'] reward.status = rewards['status'] reward.deleted_at = rewards['deleted_at'] reward.created_at = rewards['created_at'] reward.updated_at = rewards['updated_at'] count_reward = reward.where({'reward_id': reward.reward_id}) if len(count_reward) > 0 or reward.deleted_at: for data in count_reward: reward.id = data['id'] if reward.deleted_at: reward.delete() else: reward.update_special() else: reward.add_special() reward.close_connection() if 'schedules' in updates: for schedules in updates['schedules']: schedule = Schedule() schedule.schedule_id = schedules['id'] schedule.company_id = schedules['company_id'] schedule.customer_id = schedules['customer_id'] schedule.card_id = schedules['card_id'] schedule.pickup_delivery_id = schedules['pickup_delivery_id'] schedule.pickup_address = schedules['pickup_address'] schedule.pickup_date = schedules['pickup_date'] schedule.dropoff_delivery_id = schedules['dropoff_delivery_id'] schedule.dropoff_address = schedules['dropoff_address'] schedule.dropoff_date = schedules['dropoff_date'] schedule.special_instructions = schedules['special_instructions'] schedule.type = schedules['type'] schedule.token = schedules['token'] schedule.status = schedules['status'] schedule.deleted_at = schedules['deleted_at'] schedule.created_at = schedules['created_at'] schedule.updated_at = schedules['updated_at'] count_schedule = schedule.where({'schedule_id': schedule.schedule_id}) if len(count_schedule) > 0 or schedule.deleted_at: for data in count_schedule: schedule.id = data['id'] if schedule.deleted_at: schedule.delete() else: schedule.update_special() else: schedule.add_special() schedule.close_connection() if 'taxes' in updates: for taxes in updates['taxes']: tax = Tax() tax.tax_id = taxes['id'] tax.company_id = taxes['company_id'] tax.rate = taxes['rate'] tax.status = taxes['status'] tax.deleted_at = taxes['deleted_at'] tax.created_at = taxes['created_at'] tax.updated_at = taxes['updated_at'] count_tax = tax.where({'tax_id': tax.tax_id}) if len(count_tax) > 0 or tax.deleted_at: for data in count_tax: tax.id = data['id'] if tax.deleted_at: tax.delete() else: tax.update_special() else: tax.add_special() tax.close_connection() if 'transactions' in updates: for transactions in updates['transactions']: transaction = Transaction() transaction.trans_id = transactions['id'] transaction.company_id = transactions['company_id'] transaction.customer_id = transactions['customer_id'] transaction.schedule_id = transactions['schedule_id'] transaction.pretax = transactions['pretax'] transaction.tax = transactions['tax'] transaction.aftertax = transactions['aftertax'] transaction.credit = transactions['credit'] transaction.discount = transactions['discount'] transaction.total = transactions['total'] transaction.invoices = transactions['invoices'] if transactions['invoices'] else None transaction.account_paid = transactions['account_paid'] transaction.account_paid_on = transactions['account_paid_on'] transaction.type = transactions['type'] transaction.last_four = transactions['last_four'] transaction.tendered = transactions['tendered'] transaction.transaction_id = transactions['transaction_id'] transaction.status = transactions['status'] transaction.deleted_at = transactions['deleted_at'] transaction.created_at = transactions['created_at'] transaction.updated_at = transactions['updated_at'] count_transaction = transaction.where({'trans_id': transaction.trans_id}) if len(count_transaction) > 0 or transaction.deleted_at: for data in count_transaction: transaction.id = data['id'] if transaction.deleted_at: transaction.delete() else: transaction.update_special() else: transaction.add_special() transaction.close_connection() if 'users' in updates: for users in updates['users']: user = User() user.user_id = users['id'] user.company_id = users['company_id'] user.username = users['username'] user.first_name = users['first_name'] user.last_name = users['last_name'] user.street = users['street'] user.suite = users['suite'] user.city = users['city'] user.state = users['state'] user.zipcode = users['zipcode'] user.email = users['email'] user.phone = users['phone'] user.intercom = users['intercom'] user.concierge_name = users['concierge_name'] user.concierge_number = users['concierge_number'] user.special_instructions = users['special_instructions'] user.shirt_old = users['shirt_old'] user.shirt = users['shirt'] user.delivery = users['delivery'] user.profile_id = users['profile_id'] user.payment_status = users['payment_status'] user.payment_id = users['payment_id'] user.token = users['token'] user.api_token = users['api_token'] user.reward_status = users['reward_status'] user.reward_points = users['reward_points'] user.account = users['account'] user.account_total = users['account_total'] user.credits = users['credits'] user.starch = users['starch'] user.important_memo = users['important_memo'] user.invoice_memo = users['invoice_memo'] user.role_id = users['role_id'] user.deleted_at = users['deleted_at'] user.created_at = users['created_at'] user.updated_at = users['updated_at'] count_user = user.where({'user_id': user.user_id}) if len(count_user) > 0 or user.deleted_at: for data in count_user: user.id = data['id'] if user.deleted_at: user.delete() else: user.update_special() else: user.add_special() user.close_connection() if 'zipcodes' in updates: for zipcodes in updates['zipcodes']: zipcode = Zipcode() zipcode.zipcode_id = zipcodes['id'] zipcode.company_id = zipcodes['company_id'] zipcode.delivery_id = zipcodes['delivery_id'] zipcode.zipcode = zipcodes['zipcode'] zipcode.status = zipcodes['status'] zipcode.deleted_at = zipcodes['deleted_at'] zipcode.created_at = zipcodes['created_at'] zipcode.updated_at = zipcodes['updated_at'] # check to see if color_id already exists and update count_zipcode = zipcode.where({'zipcode_id': zipcode.zipcode_id}) if len(count_zipcode) > 0 or zipcode.deleted_at: for data in count_zipcode: zipcode.id = data['id'] if zipcode.deleted_at: zipcode.delete() else: zipcode.update_special() else: zipcode.add_special() zipcode.close_connection()
def eval_contract(block,transaction_list,tx): sys.stderr.write("evaluating contract\n") address = tx.to # Initialize stack stack = [] index = 0 stepcounter = 0 contract = block.get_contract(address) if not contract: return while 1: # Convert the data item into a code piece val_at_index = decode(contract.get(encode(index,256,32)),256) code = [ int(val_at_index / (256**i)) % 256 for i in range(6) ] code[0] = scriptcode_map.get(code[0],'INVALID') sys.stderr.write("Evaluating: "+ str(code)+"\n") # Invalid code instruction or STOP code stops execution sans fee if val_at_index >= 256 or code[0] in ['STOP','INVALID']: sys.stderr.write("stop code, exiting\n") break # Calculate fee minerfee = 0 nullfee = 0 stepcounter += 1 if stepcounter > 16: minerfee += getfee("stepfee") c = scriptcode_map[code[0]] if c in ['STORE','LOAD']: minerfee += getfee("datafee") if c in ['EXTRO','BALANCE']: minerfee += getfee("extrofee") if c in ['SHA256','RIPEMD-160','ECMUL','ECADD','ECSIGN','ECRECOVER']: minerfee += getfee("cryptofee") if c == 'STORE': existing = block.get_contract_state(address,code[2]) if reg[code[1]] != 0: nullfee += getfee("memoryfee") if existing: nullfee -= getfee("memoryfee") # If we can't pay the fee, break, otherwise pay it if block.get_balance(address) < minerfee + nullfee: sys.stderr.write("insufficient fee, exiting\n") break block.set_balance(address,block.get_balance(address) - nullfee - minerfee) block.reward += minerfee sys.stderr.write("evaluating operation\n") exit = False def stack_pop(n): if len(stack) < n: sys.stderr.write("Stack height insufficient, exiting") exit = True return [0] * n o = stack[-n:] stack = stack[:-n] return o # Evaluate operations if c == 'ADD': x,y = stack_pop(2) stack.append((x + y) % 2**256) elif c == 'MUL': x,y = stack_pop(2) stack.append((x * y) % 2**256) elif c == 'SUB': x,y = stack_pop(2) stack.append((x - y) % 2**256) elif c == 'DIV': x,y = stack_pop(2) if y == 0: break stack.append(int(x / y)) elif c == 'SDIV': x,y = stack_pop(2) if y == 0: break sign = (1 if x < 2**255 else -1) * (1 if y < 2**255 else -1) xx = x if x < 2**255 else 2**256 - x yy = y if y < 2**255 else 2**256 - y z = int(xx/yy) stack.append(z if sign == 1 else 2**256 - z) elif code == 'MOD': x,y = stack_pop(2) if y == 0: break stack.append(x % y) elif code == 'SMOD': x,y = stack_pop(2) if y == 0: break sign = (1 if x < 2**255 else -1) * (1 if y < 2**255 else -1) xx = x if x < 2**255 else 2**256 - x yy = y if y < 2**255 else 2**256 - y z = xx%yy stack.append(z if sign == 1 else 2**256 - z) elif code == 'EXP': x,y = stack_pop(2) stack.append(pow(x,y,2**256)) elif code == 'NEG': stack.append(2**256 - stack.pop(1)[0]) elif code == 'LT': x,y = stack_pop(2) stack.append(1 if x < y else 0) elif code == 'LE': x,y = stack_pop(2) stack.append(1 if x <= y else 0) elif code == 'GT': x,y = stack_pop(2) stack.append(1 if x > y else 0) elif code == 'GE': x,y = stack_pop(2) stack.append(1 if x >= y else 0) elif code == 'EQ': x,y = stack_pop(2) stack.append(1 if x == y else 0) elif code == 'NOT': stack.append(1 if stack.pop(1)[0] == 0 else 0) elif code == 'MYADDRESS': stack.append(address) elif code == 'TXSENDER': stack.append(decode(tx.sender,256)) elif code == 'TXVALUE': stack.append(tx.value) elif code == 'TXDATAN': stack.append(len(tx.data)) elif code == 'TXDATA': x, = stack_pop(1) stack.append(0 if x >= len(tx.data) else tx.data[x]) elif code == 'BLK_PREVHASH': stack.append(decode(block.prevhash,256)) elif code == 'BLK_COINBASE': stack.append(decode(block.coinbase,160)) elif code == 'BLK_TIMESTAMP': stack.append(block.timestamp) elif code == 'BLK_NUMBER': stack.append(block.number) elif code == 'BLK_DIFFICULTY': stack.append(block.difficulty) elif code == 'SHA256': L = stack_pop(1) hdataitems = stack_pop(math.ceil(L / 32.0)) hdata = ''.join([encode(x,256,32) for x in hdataitems])[:L] stack.append(decode(hashlib.sha256(hdata).digest(),256)) elif code == 'RIPEMD-160': L = stack_pop(1) hdataitems = stack_pop(math.ceil(L / 32.0)) hdata = ''.join([encode(x,256,32) for x in hdataitems])[:L] stack.append(decode(hashlib.new('ripemd160',hdata).digest(),256)) elif code == 'ECMUL': n,x,y = stack_pop(3) # Point at infinity if x == 0 and y == 0: stack.extend([0,0]) # Point not on curve, coerce to infinity elif x >= P or y >= P or (x ** 3 + 7 - y ** 2) % P != 0: stack.extend([0,0]) # Legitimate point else: x2,y2 = base10_multiply((x,y),n) stack.extend([x2,y2]) elif code == 'ECADD': x1,y1,x2,y2 = stack_pop(4) # Invalid point 1 if x1 >= P or y1 >= P or (x1 ** 3 + 7 - y1 ** 2) % P != 0: stack.extend([0,0]) # Invalid point 2 elif x2 >= P or y2 >= P or (x2 ** 3 + 7 - y2 ** 2) % P != 0: stack.extend([0,0]) # Legitimate points else: x3,y3 = base10_add((x1,y1),(x2,y2)) stack.extend([x3,y3]) elif code == 'ECSIGN': k,h = stack_pop(2) v,r,s = ecdsa_raw_sign(h,k) stack.extend([v,r,s]) elif code == 'ECRECOVER': h,v,r,s = stack_pop(4) x,y = ecdsa_raw_recover((v,r,s),h) stack.extend([x,y]) elif code == 'SHA3': L = stack_pop(1) hdataitems = stack_pop(math.ceil(L / 32.0)) hdata = ''.join([encode(x,256,32) for x in hdataitems])[:L] stack.append(decode(sha3.sha3_256(hdata).digest(),256)) elif code == 'PUSH': stack.append(contract.get(encode(index + 1,256,32))) index += 1 elif code == 'POP': stack_pop(1) elif code == 'DUP': x, = stack_pop(1) stack.extend([x,x]) elif code == 'SWAP': x,y = stack_pop(2) stack.extend([y,x]) elif code == 'SLOAD': stack.append(contract.get(encode(stack_pop(1)[0],256,32))) elif code == 'SSTORE': x,y = stack_pop(2) if exit: break contract.update(encode(x,256,32),y) elif code == 'JMP': index = stack_pop(1)[0] elif code == 'JMPI': newpos,c = stack_pop(2) if c != 0: index = newpos elif code == 'IND': stack.append(index) elif code == 'EXTRO': ind,addr = stack_pop(2) stack.push(block.get_contract(encode(addr,256,20)).get(encode(ind,256,32))) elif code == 'BALANCE': stack.push(block.get_balance(encode(stack_pop(1)[0],256,20))) elif code == 'MKTX': datan,fee,value,to = stack_pop(4) if exit: break elif (value + fee) > block.get_balance(address): break else: data = stack_pop(datan) tx = Transaction(0,encode(to,256,20),value,fee,data) tx.sender = address transaction_list.insert(0,tx) elif code == 'SUICIDE': sz = contract.get_size() negfee = -sz * getfee("memoryfee") toaddress = encode(stack_pop(1)[0],256,20) block.pay_fee(toaddress,negfee,False) contract.root = '' break if exit: break block.update_contract(address,contract)
def remote_transactions_received_handler(sender, transactions, **kwargs): "receives rlp.decoded serialized" txl = [Transaction.deserialize(rlp.encode(tx)) for tx in transactions] logger.debug('remote_transactions_received: %r', txl) for tx in txl: chain_manager.add_transaction(tx)
def eval_contract(block,transaction_list,tx): sys.stderr.write("evaluating contract\n") address = tx.to # Initialize registers reg = [0] * 256 reg[0] = decode(tx.sender,256) reg[1] = decode(tx.to,256) reg[2] = tx.value reg[3] = tx.fee index = 0 stepcounter = 0 contract = block.get_contract(address) if not contract: return while 1: # Convert the data item into a code piece val_at_index = decode(contract.get(encode(index,256,32)),256) code = [ int(val_at_index / (256**i)) % 256 for i in range(6) ] code[0] = scriptcode_map.get(code[0],'INVALID') sys.stderr.write("Evaluating: "+ str(code)+"\n") # Invalid code instruction or STOP code stops execution sans fee if val_at_index >= 256**6 or code[0] in ['STOP','INVALID']: sys.stderr.write("stop code, exiting\n") break # Calculate fee minerfee = 0 nullfee = 0 stepcounter += 1 if stepcounter > 16: minerfee += params["stepfee"] c = scriptcode_map[code[0]] if c in ['STORE','LOAD']: minerfee += params["datafee"] if c in ['EXTRO','BALANCE']: minerfee += params["extrofee"] if c in ['SHA256','RIPEMD-160','ECMUL','ECADD','ECSIGN','ECRECOVER']: minerfee += params["cryptofee"] if c == 'STORE': existing = block.get_contract_state(address,code[2]) if reg[code[1]] != 0: nullfee += params["memoryfee"] if existing: nullfee -= params["memoryfee"] # If we can't pay the fee, break, otherwise pay it if block.get_balance(address) < minerfee + nullfee: sys.stderr.write("insufficient fee, exiting\n") break block.set_balance(address,block.get_balance(address) - nullfee - minerfee) block.reward += minerfee sys.stderr.write("evaluating operation\n") # Evaluate operations if c == 'ADD': reg[code[3]] = (reg[code[1]] + reg[code[2]]) % 2**256 elif c == 'MUL': reg[code[3]] = (reg[code[1]] * reg[code[2]]) % 2**256 elif c == 'SUB': reg[code[3]] = (reg[code[1]] + 2**256 - reg[code[2]]) % 2**256 elif c == 'DIV': reg[code[3]] = int(reg[code[1]] / reg[code[2]]) elif c == 'SDIV': sign = 1 sign *= (1 if reg[code[1]] < 2**255 else -1) sign *= (1 if reg[code[2]] < 2**255 else -1) x = reg[code[1]] if reg[code[1]] < 2**255 else 2**256 - reg[code[1]] y = reg[code[2]] if reg[code[2]] < 2**255 else 2**256 - reg[code[2]] z = int(x/y) reg[code[3]] = z if sign == 1 else 2**256 - z elif code == 'MOD': reg[code[3]] = reg[code[1]] % reg[code[2]] elif code == 'SMOD': sign = 1 sign *= (1 if reg[code[1]] < 2**255 else -1) sign *= (1 if reg[code[2]] < 2**255 else -1) x = reg[code[1]] if reg[code[1]] < 2**255 else 2**256 - reg[code[1]] y = reg[code[2]] if reg[code[2]] < 2**255 else 2**256 - reg[code[2]] z = x%y reg[code[3]] = z if sign == 1 else 2**256 - z elif code == 'EXP': reg[code[3]] = pow(reg[code[1]],reg[code[2]],2**256) elif code == 'NEG': reg[code[2]] = 2**256 - reg[code[1]] elif code == 'LT': reg[code[3]] = 1 if reg[code[1]] < reg[code[2]] else 0 elif code == 'LE': reg[code[3]] = 1 if reg[code[1]] <= reg[code[2]] else 0 elif code == 'GT': reg[code[3]] = 1 if reg[code[1]] > reg[code[2]] else 0 elif code == 'GE': reg[code[3]] = 1 if reg[code[1]] >= reg[code[2]] else 0 elif code == 'EQ': reg[code[3]] = 1 if reg[code[1]] == reg[code[2]] else 0 elif code == 'NOT': reg[code[2]] = 1 if reg[code[1]] == 0 else 0 elif code == 'SHA256': inp = encode(reg[code[1]],256,32) reg[code[2]] = decode(hashlib.sha256(inp).digest(),256) elif code == 'RIPEMD-160': inp = encode(reg[code[1]],256,32) reg[code[2]] = decode(hashlib.new('ripemd160',inp).digest(),256) elif code == 'ECMUL': pt = (reg[code[1]],reg[code[2]]) # Point at infinity if pt[0] == 0 and pt[1] == 0: reg[code[4]], reg[code[5]] = 0,0 # Point not on curve, coerce to infinity elif (pt[0] ** 3 + 7 - pt[1] ** 2) % N != 0: reg[code[4]], reg[code[5]] = 0,0 # Legitimate point else: pt2 = base10_multiply(pt,reg[code[3]]) reg[code[4]], reg[code[5]] = pt2[0], pt2[1] elif code == 'ECADD': pt1 = (reg[code[1]],reg[code[2]]) pt2 = (reg[code[3]],reg[code[4]]) # Invalid point 1 if (pt1[0] ** 3 + 7 - pt1[1] ** 2) % N != 0: reg[code[5]], reg[code[6]] = 0,0 # Invalid point 2 elif (pt2[0] ** 3 + 7 - pt2[1] ** 2) % N != 0: reg[code[5]], reg[code[6]] = 0,0 # Legitimate points else: pt3 = base10_add(pt1,pt2) reg[code[5]], reg[code[6]] = pt3[0], pt3[1] elif code == 'ECSIGN': reg[code[3]], reg[code[4]], reg[code[5]] = ecdsa_raw_sign(reg[code[1]],reg[code[2]]) elif code == 'ECRECOVER': pt = ecdsa_raw_recover((reg[code[2]],reg[code[3]],reg[code[4]]),reg[code[1]]) reg[code[5]] = pt[0] reg[code[6]] = pt[1] elif code == 'COPY': reg[code[2]] = reg[code[1]] elif code == 'STORE': contract.update(encode(reg[code[2]],256,32),reg[code[1]]) elif code == 'LOAD': reg[code[2]] = contract.get(encode(reg[code[1]],256,32)) elif code == 'SET': reg[code[1]] = (code[2] + 256 * code[3] + 65536 * code[4] + 16777216 * code[5]) * 2**code[6] % 2**256 elif code == 'JMP': index = reg[code[1]] elif code == 'JMPI': if reg[code[1]]: index = reg[code[2]] elif code == 'IND': reg[code[1]] = index elif code == 'EXTRO': if reg[code[1]] >= 2**160: reg[code[3]] = 0 else: address = encode(reg[code[1]],256,20) field = encode(reg[code[2]]) reg[code[3]] = block.get_contract(address).get(field) elif code == 'BALANCE': if reg[code[1]] >= 2**160: reg[code[2]] = 0 else: address = encode(reg[code[1]],256,20) reg[code[2]] = block.get_balance(address) elif code == 'MKTX': to = encode(reg[code[1]],256,32) value = reg[code[2]] fee = reg[code[3]] if (value + fee) > block.get_balance(address): pass else: datan = reg[code[4]] data = [] for i in range(datan): ind = encode((reg[code[5]] + i) % 2**256,256,32) data.append(contract.get(ind)) tx = Transaction(0,to,value,fee,data) tx.sender = address transaction_list.insert(0,tx) elif code == 'DATA': reg[code[2]] = tx.data[reg[code[1]]] elif code == 'DATAN': reg[code[1]] = len(tx.data) elif code == 'MYADDRESS': reg[code[1]] = address elif code == 'BLKHASH': reg[code[1]] = decode(block.hash()) elif code == 'SUICIDE': sz = contract.get_size() negfee = -sz * params["memoryfee"] toaddress = encode(reg[code[1]],256,20) block.pay_fee(roaddress,negfee,False) contract.root = '' break block.update_contract(address,contract)