Beispiel #1
0
    def incremental_read(self):

        #read files in dir
        for file in sorted(os.listdir(self.directory)):
            # try:
            # for each file
            with open(self.directory + file) as f:
                timestamp = int(file.split('.')[0])

                #read only newer files
                if self.prev_timestamp < timestamp:

                    hash = f.readline().strip('\r\n')
                    trytes = f.readline().strip('\r\n')
                    neighbor = f.readline().strip('\r\n')
                    #height = int(f.readline().strip('\r\n').split('Height: ')[1])

                    #parse fields
                    tx = transaction(trytes, hash)

                    #add to graph
                    self.add_tx_to_tangle(tx)

                    if len(self.first) < MARK_AS_START:
                        self.graph.node[tx.hash]["height"] = 0
                        self.first.append(tx.hash)

                    #stats:
                    if (self.prev_timestamp / self.res_ns <
                            timestamp / self.res_ns):
                        print 'reading', file, '...'
                        self.prev_timestamp = timestamp
                        self.analytics.analyze()
Beispiel #2
0
    def sell_stock_due_to_price_check(self, bought, purchase_price,
                                      purchase_date, row):
        current_close_price = float(row[self.close_column])
        per = self.position_flag * (
            (current_close_price - purchase_price) / purchase_price)
        if per >= self.target_price:
            sell_amount = bought * current_close_price
            self.total_sell = self.total_sell + sell_amount
            self.overall_sell = self.overall_sell + sell_amount
            self.total_sold += bought
            sell_with_brokerage = 0.0
            brokerage_object = brokerage()
            if (purchase_date != row[self.datetime_column][:10]):
                brokerage_fee = brokerage_object.calculate_delivery_brokerage(
                    sell_amount)
                sell_with_brokerage = sell_amount - (self.position_flag *
                                                     brokerage_fee)
                self.logger.info("Delivery Sale: " + "Sell amount: " +
                                 str(sell_amount) + " sell with brokerage: " +
                                 str(sell_with_brokerage) +
                                 " Brokerage fee: " + str(brokerage_fee))
            else:
                brokerage_fee = brokerage_object.calculate_intraday_brokerage(
                    sell_amount)
                sell_with_brokerage = sell_amount - brokerage_fee
                self.logger.info("Intraday Sale: " + "Sell amount: " +
                                 str(sell_amount) + " sell with brokerage: " +
                                 str(sell_with_brokerage) +
                                 " Brokerage fee: " + str(brokerage_fee))
                self.overall_c_intraday = self.overall_c_intraday + 1

            self.overall_sell_with_brokerage = self.overall_sell_with_brokerage + sell_with_brokerage

            self.logger.info("Stock " + self.line[self.column_no_of_ticker] +
                             " sold " + str(bought) + " shares at " +
                             str(current_close_price) + " price at date " +
                             str(row)[2:12] + " at time " + str(row)[13:18] +
                             "\n")
            self.overall_c_wins = self.overall_c_wins + 1
            self.c_total_wins = self.c_total_wins + 1
            # the last element has already been initialised to 0.  modify it to
            # the sold amount
            self.sell_with_brokerage[-1] = sell_with_brokerage
            self.sell_amount[-1] = sell_amount
            self.sell_met_target[-1] = "1"
            """Use of Transaction Class"""
            date = str(row)[2:12]
            time = str(row)[12:18]
            print_object = transaction(self.path_to_transaction_file)
            print_object.print_transaction_items(
                date, time, self.line[self.column_no_of_ticker], "0",
                str(bought), str(current_close_price), str(sell_amount), "1")
            '''
            self.transactions_file.writerow(str(row)[2:12] +
                                            str(row)[12:18] +
                                            self.line[0] + "0" + str(bought) + str(row[2]) +
                                            str(sell_amount) +  "1")
            '''
            return True
        return False
Beispiel #3
0
def generate_block_chain(file_name, limit):
    print("Generating new Block Chain...")
    now = time()

    # Genera un iterable (solo puede ser iterado una única vez)
    transactions = map(
        lambda i: transaction(
            int(sha256(f"hola {i}".encode()).hexdigest(), 16), RSA),
        range(100))
    blockChain = block_chain(
        next(transactions
             ))  # Obtenemos la primera transacción para generar el Block Chain

    for _ in range(1, limit):  # Toma entre 400 a 600 segundos
        blockChain.add_block(
            next(transactions)
        )  # Obtenemos las próximas transacciones y las agregamos a Block Chain

    if limit != 100:
        for _ in range(limit, 100):
            add_wrong_block(
                blockChain, next(transactions)
            )  # Obtenemos las transacciones restantes y las agregamos a Block Chain

    with open(file_name, 'wb') as output_file:
        pickle.dump(blockChain, output_file)

    print(
        f"File '{file_name}' has been created!\nVerification: {blockChain.verify()}\nTime elapsed: {time() - now}"
    )
Beispiel #4
0
def create_track(tool_name,
                 tool_version,
                 project_name=None,
                 project_uuid=None,
                 info=None):
    def make_track(cursor):
        # 校验项目是否注册
        sql = None
        if project_uuid:
            try:
                uuid = UUID(project_uuid)
            except:
                uuid = project_uuid
            sql = sql_find_project(uuid)
        elif project_name:
            sql = sql_find_project_unsafe(project_name)
        else:
            return '参数错误'
        cursor.execute(sql)
        info_project = cursor.fetchone()
        cursor.nextset()

        if not info_project:
            return '项目未注册'
        else:
            project_id = info_project['id']
            # 处理工具信息
            tool_id = create_tool(tool_name, tool_version)

            # 记录日志
            isSuc = create_log(project_id, tool_id, info)
            cursor.close()
            return '成功' if isSuc else None

    return transaction(make_track)
Beispiel #5
0
 def sell_stock_due_to_stop_loss(self, bought, close_price, index):
     per = (float(self.rowslist[index][2]) - close_price) / close_price
     if per <= self.stop_loss:
         sell_amount = bought * float(self.rowslist[index][2])
         self.total_sell = self.total_sell + sell_amount
         self.overall_sell = self.overall_sell + sell_amount
         self.total_sold += bought
         self.logger.info("Stop Loss Sale: Stock " + self.line[0] +
                          " sold " + str(bought) + " shares at " +
                          self.rowslist[index][2] + " price at date " +
                          str(self.rowslist[index])[2:12] + " at time " +
                          str(self.rowslist[index])[13:18] + "\n")
         self.overall_c_stoploss = self.overall_c_stoploss + 1
         self.c_total_stoploss = self.c_total_stoploss + 1
         # the last element has already been initialised to  0.  modify it to the sold amount
         self.sell_amount[-1] = bought * float(self.rowslist[index][2])
         self.sell_stop_loss[-1] = "1"
         """Use of Transaction Class"""
         date = str(self.rowslist[index])[2:12]
         time = str(self.rowslist[index])[12:18]
         print_object = transaction(self.path_to_transaction_file)
         print_object.print_transaction_items(date, time, self.line[0], "0",
                                              str(bought),
                                              str(self.rowslist[index][2]),
                                              str(sell_amount), "2")
         '''
         self.transactions_file.writerow(str(self.rowslist[index])[2:12] +
                                         str(self.rowslist[index])[12:18] +
                                         self.line[0] + "0" + str(bought) + str(self.rowslist[index][2]) +
                                         str(sell_amount) + "1")
         '''
         return True
     return False
Beispiel #6
0
def read_projects():
    def get_projects(cursor):
        sql = sql_find_all_project()
        cursor.execute(sql)
        return cursor.fetchall()

    return transaction(get_projects)
Beispiel #7
0
def read_log_tool(name, version=None):
    def get_log_tool(cursor):
        sql = sql_find_log_join_tool(name, version)
        print(sql)
        cursor.execute(sql)
        return cursor.fetchall()
        # if version:
        #   sql = sql_find_tool_version(name, version)
        #   cursor.execute(sql)
        #   info_tool = cursor.fetchone()
        #   if info_tool:
        #     sql = sql_find_log_tool(info_tool['id'])
        #     cursor.execute(sql)
        #     return cursor.fetchall()
        # else:
        #   sql = sql_find_tool(name)
        #   cursor.execute(sql)
        #   info_tools = cursor.fetchall()
        #   if info_tools:
        #     tool_ids = list()
        #     for info_tool in info_tools:
        #       tool_ids.append(info_tool['id'])
        #     sql = sql_find_log_tools(tool_ids)
        #     cursor.execute(sql)
        #     return cursor.fetchall()

    return transaction(get_log_tool)
Beispiel #8
0
    def extract_dump(self):
        for file in sorted(os.listdir(folder)):
            if file.endswith('.dmp'):
                count = 0
                with open(folder + file, 'r') as f:
                    for line in f:
                        tx_hash, tx = line.split(',')
                        tx = transaction.transaction(tx, tx_hash)

                        hash = tx.hash
                        branch = tx.branch_transaction_hash
                        trunk = tx.trunk_transaction_hash

                        date = datetime.datetime.fromtimestamp(
                            tx.timestamp).strftime('%Y-%m-%d-%H')

                        self.store_to_transactions_table(tx, date)
                        self.store_to_addresses_table(tx, date)
                        self.store_to_bundles_table(tx, date)
                        self.store_to_tags_table(tx, date)
                        self.store_to_transaction_hashes_table(tx, date)
                        self.store_to_approvee_table(hash, branch, date)
                        self.store_to_approvee_table(hash, trunk, date)

                        count += 1
                        print('Dumped so far', count, file=sys.stdout)
Beispiel #9
0
def erbsunde(fro, too, value, sk, saveas):
    bp = f"../transactions/{saveas}/"
    os.makedirs(bp, exist_ok=False)
    for date in times():
        t = transaction(fro, too, value, date=date)
        t.signate(sk)
        t.save(bp + str(date) + ".json")
Beispiel #10
0
def filetoblock(filename) :				
	f = open(filename, 'r')
	prevhash = readword(f.readline())
	B = block(prevhash)
	B.max_trans_num = int(readword(f.readline()))
	B.nonce = int(readword(f.readline()))
	#B.translist = [transaction.transaction(0,0) for i in range (B.max_trans_num)] 	
	for i in range(B.max_trans_num) :		
		incount = int(readword(f.readline()))
		outcount = int(readword(f.readline()))
		T = transaction.transaction(incount,outcount)
		T.inlist = [transaction.inputtrans() for i1 in range (T.incount)]	#Create an array of type inlist[incount]
		T.sign = readword(f.readline())
		T.hash = readword(f.readline())
		for j in range(T.incount) :	# iterating through each input and adding them to the transaction's inlist
			I = transaction.inputtrans()
			I.hash = readword(f.readline())
			I.n = readword(f.readline())
			I.sign = readword(f.readline())
			I.pub = readword(f.readline())
			T.inlist[j] = I
	
		T.outlist = [transaction.outputtrans() for i2 in range (T.outcount)]	   #Create an array of type outlist[outcount] 
		for j in range(T.outcount) :	# iterating through each output and adding them to the transaction's outlist
			O = transaction.outputtrans()
			O.value = int(readword(f.readline()))
			O.addr = readword(f.readline())
			T.outlist[j] = O
	 	B.translist[i] = T	# adding the transaction to the block's translist
	return B
Beispiel #11
0
 def hParse(self,hFile):
     with open(hFile, newline='', errors="ignore") as csvfile: 
         reader = csv.reader(csvfile, quotechar="\"")
         for row in reader:
             if row[3] not in self.transactions:
                 self.transactions[row[3]] = transaction.transaction()
                 self.transactions[row[3]].set_tranNum(str(row[3]))
                 self.transactions[row[3]].set_siteID(str(row[0]))
Beispiel #12
0
def read_project(project_uuid=None, project_id=None):
    def get_project(cursor):
        sql = sql_find_project(project_uuid=project_uuid,
                               project_id=project_id)
        cursor.execute(sql)
        return cursor.fetchone()

    return transaction(get_project)
Beispiel #13
0
def __submit_result(ea, request_hash):
    args = util.read_conf('{}/config/YZDataRequest.json'.format(tx_home),
                          '{}/compiled'.format(tx_home))
    succ, args = __update_func_args(request_hash, args)
    if not succ:
        return
    tx = transaction(ea.host, ea.project_id)
    tx.call_and_send_transaction(args.keystore_path, submitter_passwd, args)
Beispiel #14
0
def main():
    # t_l is the list of fake transactions to test out the merkle tree.
    t_l = []
    for i in range(10):
        t_l.append(transaction("Alex", "Bobby", 5).hashSelf())

    # This prints the merkleRoot of the list of transactions: t_l
    print(merkleRoot(t_l))
 def _loadcheckpointfile(self, filename):
     for line in open(filename).read().splitlines():
         segments = line.split(" ")
         key = segments[0]
         values = (segments[1], segments[2], None)
         action = transaction(key, values)
         self._data[segments[0]]=(segments[1], segments[2],)
         self._updatevaluescount(action)
 def _loadcheckpointfile(self, filename):
     for line in open(filename).read().splitlines():
         segments = line.split(" ")
         key = segments[0]
         values = (segments[1], segments[2], None)
         action = transaction(key, values)
         self._data[segments[0]] = (
             segments[1],
             segments[2],
         )
         self._updatevaluescount(action)
Beispiel #17
0
    def _parsing_transaction(self, byte_array, count):
        transaction_list = []
        data_length = int(len(byte_array) / 2)
        data_from = 0
        data_to = data_length
        for i in range(count):
            transaction_obj = transaction(self.common_util.slicing(byte_array, data_from, data_to))
            data_from += transaction_obj.get_size()
            transaction_list.append(transaction_obj)

        return transaction_list
Beispiel #18
0
def read_tool(name, version=None):
    def get_tool(cursor):
        if version:
            sql = sql_find_tool_version(name, version)
            cursor.execute(sql)
            return cursor.fetchone()
        else:
            sql = sql_find_tool(name)
            cursor.execute(sql)
            return cursor.fetchall()

    return transaction(get_tool)
Beispiel #19
0
    def setvalue(self, key, value):
        values = self._block.getvalue(key)
        if values == None:
            values = self._db.getvalue(key)

        if values != None:
            values = (value, values[1], values[0])
        else:
            values = (value, 0, None)
        action = transaction(key, values)

        self._block.setvalue(action)
Beispiel #20
0
def user_input():
    global link_status
    global pending_transaction_queue
    global balance
    global block_chain
    global pending_credit
    global current_block
    transaction_re = re.compile(r'moneyTransfer\((\d+), (\d+), (\d+)\)')
    fail_link_re = re.compile(r'failLink\((\d+)\)')
    fix_link_re = re.compile(r'fixLink\((\d+)\)')
    while True:
        user_input = input()
        transaction_event = transaction_re.match(user_input)
        fail_link_event = fail_link_re.match(user_input)
        fix_link_event = fix_link_re.match(user_input)
        if user_input == 'print blockchain':
            print(block_chain)
            logger.info('depth of blockchain: %s', block_chain.depth)
        elif user_input == 'print balance':
            print(f'balance: {balance}')
        elif user_input == 'failProcess' or user_input == 'exit':
            save_process()
            break
        elif user_input == 'print queue':
            print("Pending transactions:")
            if current_block:
                for trans in current_block.transactions:
                    print(trans)
            for trans in pending_transaction_queue:
                print(trans)
        elif transaction_event:
            logger.debug("transaction initiated")
            sender = int(transaction_event.group(1))
            receiver = int(transaction_event.group(2))
            amount = int(transaction_event.group(3))
            if balance - pending_credit >= amount:
                pending_credit += amount
                logger.info(
                    "adding transaction with sender: %s, receiver: %s, amount: %s",
                    sender, receiver, amount)
                pending_transaction_queue.append(
                    transaction(sender, receiver, amount))
            else:
                logger.info(
                    "failed to initiate transaction: spending too much")
        elif fail_link_event:
            dest = int(fail_link_event.group(1))
            logger.info("failing link from %d to %d", pid, dest)
            link_status[dest] = False
        elif fix_link_event:
            dest = int(fix_link_event.group(1))
            logger.info("fixing link from %d to %d", pid, dest)
            link_status[dest] = True
Beispiel #21
0
 def buy_stocks(self, row):
     purchase_cost = float(row[self.close_column])
     config_obj = config.config(r"../config.txt")
     purchase_cutoff_time = config_obj.purchase_cutoff_time
     checkdate = row[
         self.datetime_column][2:11] + purchase_cutoff_time[:4] + ":00"
     if 'pm' in purchase_cutoff_time or 'Pm' in purchase_cutoff_time or 'PM' in purchase_cutoff_time or 'pM' in purchase_cutoff_time:
         checkdate = datetime.strptime(
             checkdate, "%y-%m-%d %H:%M:%S") + timedelta(hours=12)
     else:
         checkdate = datetime.strptime(checkdate, "%y-%m-%d %H:%M:%S")
     curr_date = datetime.strptime(row[self.datetime_column][2:18],
                                   "%y-%m-%d %H:%M:%S")
     if curr_date < checkdate:
         bought = int(self.max_capital_for_single_buy / purchase_cost)
         if bought != 0:
             actual_cost = (bought * purchase_cost)
             self.total_cost = self.total_cost + actual_cost
             self.total_purchased += bought
             self.overall_cost = self.overall_cost + actual_cost
             self.c_overall_buy_trans = self.c_overall_buy_trans + 1
             self.c_transactions_today = self.c_transactions_today + 1
             self.buy_amount[-1] = str(actual_cost)
             self.logger.info("Stock " +
                              self.line[self.column_no_of_ticker] +
                              " bought " + str(bought) + " shares at " +
                              str(purchase_cost) + " price at date " +
                              str(row)[2:12] + " at time " +
                              str(row)[12:18] + "\n")
             """Use of Transaction Class"""
             date = str(row)[2:12]
             time = str(row)[12:18]
             print_object = transaction(self.path_to_transaction_file)
             print_object.print_transaction_items(
                 date, time, self.line[self.column_no_of_ticker], "1",
                 str(bought), str(purchase_cost), str(actual_cost), "0")
             '''
             self.transactions_file.writerow(str(self.rowslist[index_close])[2:12] +  str(self.rowslist[index_close])[12:18] +
                                             self.line[0] +  "1" +  str(bought) + str(purchase_cost) + str(0.0-actual_cost) +
                                             "0")
             '''
         else:
             # this may happen if the price of one stock is more than the
             # maximum capital
             self.logger.error("Could not buy stock " + self.line[0] +
                               " on date " + str(row)[2:12] +
                               " due to insufficient daily stock fund\n")
         return bought
     else:
         self.logger.error("Could not buy stock " + self.line[0] +
                           " on date " + str(row)[2:12] +
                           " due to cut-off time for purchase\n")
         return 0
Beispiel #22
0
def dailyScript(dayNumber, numberSessions):
    open('mergedTSF.txt', 'w').close()
    if dayNumber <= 5:
        #run 3 transactions per day
        transaction.transaction(test_id=str(dayNumber) + 'a')
        transaction.transaction(test_id=str(dayNumber) + 'b')
        transaction.transaction(test_id=str(dayNumber) + 'c')
        if int(
                numberSessions
        ) > 3:  # run any extra transactions dynamically based on user input
            for i in range(0, int(numberSessions) - 3):
                print("Starting new session...")
                subprocess.call("python frontendSourceCodeSingleDay.py " +
                                "newVAF.txt " + "TTSF" + str(dayNumber) +
                                chr(ord('a') + i + int(numberSessions) - 1) +
                                ".txt")

    else:
        print("Error! cannot run for more than 5 days")

    mTSF = open('mergedTSF.txt', 'a')
    mTSF.write(
        "EOS " + "0000000" + " " + "000" + " " + "0000000" + " " + "***\n"
    )  # extra final EOS line after concat based on backend requirements
    mTSF.close()
    #run backend at end of day
    subprocess.call("python backendSourceCodeSingleDay.py " + "newMAF" +
                    "day" + str(dayNumber - 1) + ".txt mergedTSF.txt " +
                    str(dayNumber))
Beispiel #23
0
def asObject(a_dictionary, kind):
    b = a_dictionary
    if kind == 'block':
        temp_trans_list = []
        for trans_dict in a_dictionary['transactions']:
            temp_trans_list.append(asObject(trans_dict, "transaction"))
        tempBlock = block.block(b['index'], b['timestamp'], temp_trans_list,
                                b['nonce'], b['current_hash'],
                                b['previous_hash'])
        return tempBlock
    return transaction.transaction(b['sender'], b['recipient'], b['amount'],
                                   b['timestamp'], b['inputs'], b['outputs'],
                                   b['id'], b['signature'])
Beispiel #24
0
def create_project(project_name,
                   project_uuid=None,
                   project_type=None,
                   author=None):
    if not project_name:
        raise ValueError('Please pass correct project name!')

    def add(cursor):
        uuid = project_uuid if project_uuid else uuid4()
        sql = sql_add_project(project_name, project_type, uuid, author)
        cursor.execute(sql)
        return project_uuid

    return transaction(add)
Beispiel #25
0
    def sell_stock_at_end_of_day(self, bought, purchase_price, purchase_date,
                                 row):
        current_close_price = float(row[self.close_column])
        sell_amount = bought * current_close_price
        self.total_sold += bought
        self.total_sell = self.total_sell + sell_amount
        self.overall_sell = self.overall_sell + sell_amount
        sell_with_brokerage = 0.0
        brokerage_object = brokerage()
        if (purchase_date != row[self.datetime_column][:10]):
            brokerage_fee = brokerage_object.calculate_delivery_brokerage(
                sell_amount)
            sell_with_brokerage = sell_amount - (self.position_flag *
                                                 brokerage_fee)
            self.logger.info("Delivery Sale: " + "Sell amount: " +
                             str(sell_amount) + " sell with brokerage: " +
                             str(sell_with_brokerage) + " Brokerage fee: " +
                             str(brokerage_fee))
        else:
            brokerage_fee = brokerage_object.calculate_intraday_brokerage(
                sell_amount)
            sell_with_brokerage = sell_amount - brokerage_fee
            self.logger.info("Intraday Sale: " + "Sell amount: " +
                             str(sell_amount) + " sell with brokerage: " +
                             str(sell_with_brokerage) + " Brokerage fee: " +
                             str(brokerage_fee))
            self.overall_c_intraday = self.overall_c_intraday + 1
            if sell_with_brokerage < bought * purchase_price:
                self.c_intraday_losses = self.c_intraday_losses + 1

        self.overall_sell_with_brokerage = self.overall_sell_with_brokerage + sell_with_brokerage

        self.logger.info("Stock " + self.line[self.column_no_of_ticker] +
                         " sold " + str(bought) + " shares at " +
                         str(current_close_price) + " price at date " +
                         str(row)[2:12] + " at time " + str(row)[13:18] + "\n")
        self.overall_c_sellEod = self.overall_c_sellEod + 1
        self.c_total_sellEOD = self.c_total_sellEOD + 1
        # the last element has already been initialised to 0.  modify it to the
        # sold amount
        self.sell_amount[-1] = sell_amount
        self.sell_EOD[-1] = "1"

        print_object = transaction(self.path_to_transaction_file)
        date = str(row)[2:12]
        time = str(row)[12:18]
        print_object.print_transaction_items(
            date, time, self.line[self.column_no_of_ticker], "0", str(bought),
            str(current_close_price), str(self.sell_amount[-1]), "3")
def creation():
    bc = None
    RSAkey = rsa_key()
    for i in range(0, 100):
        message = random.randrange(1, 2**10)
        t = transaction(message, RSAkey)
        if (i == 0): bc = block_chain(t)
        else: bc.add_block(t)
        print(i+1)
    valid, index = bc.verify()
    assert valid, "Blockchain no es valido"
    assert len(bc.list_of_blocks) == 100, "Blockchain no contiene 100 bloques"
    with open("./out/BC_100blocks_100valids.block", 'wb') as file:
        pickle.dump(bc, file)
    print("BlockChain serializado en /out/BC_100blocks_100valids.block")
def test():
    conn = server.connect()
    try:
        os.remove("graph.dot")
    except:
        pass
    txn = transaction.transaction(tx_hash,conn) 
    test=False

    txn.verify(True)
    test=open("graph.dot",'r').read()

    print(test)
    
    assert_equal(test,result)
Beispiel #28
0
def test():
    conn = server.connect()
    try:
        os.remove("graph.dot")
    except:
        pass
    txn = transaction.transaction(tx_hash, conn)
    test = False

    txn.verify(True)
    test = open("graph.dot", 'r').read()

    print(test)

    assert_equal(test, result)
Beispiel #29
0
def create_log(
    project_id,
    tool_id,
    info=None,
):
    if not project_id or not tool_id:
        raise ValueError('Please pass correct parameters!')

    def make_log(cursor):
        sql = sql_add_log(project_id=project_id, tool_id=tool_id, info=info)
        cursor.execute(sql)
        isAffect = cursor.rowcount
        cursor.close()
        return bool(isAffect)

    return transaction(make_log)
Beispiel #30
0
    def rollback(self):
        temp_transactions_list = self._transactions[self._level]
        for tran in reversed(temp_transactions_list):
            action = transaction(tran.key, (tran.oldvalue, tran.version,tran.value))
            self._appendtran(action)
            self.setvalue(action)
        if self._level == 0:
            self._transactions = [[]]
        else:
            self._transactions.pop()

        if self._level > 0:
            self._level -= 1
        if 0 == len(temp_transactions_list):
            return "NO Transaction"
        return "Success"
Beispiel #31
0
    def rollback(self):
        temp_transactions_list = self._transactions[self._level]
        for tran in reversed(temp_transactions_list):
            action = transaction(tran.key,
                                 (tran.oldvalue, tran.version, tran.value))
            self._appendtran(action)
            self.setvalue(action)
        if self._level == 0:
            self._transactions = [[]]
        else:
            self._transactions.pop()

        if self._level > 0:
            self._level -= 1
        if 0 == len(temp_transactions_list):
            return "NO Transaction"
        return "Success"
Beispiel #32
0
def create_tool(tool_name, tool_version):
    if not tool_name or not tool_version:
        raise ValueError('Please pass correct parameters!')

    def make_tool(cursor):
        sql = sql_find_tool_version(tool_name, tool_version)
        cursor.execute(sql)
        info_tool = cursor.fetchone()
        if not info_tool:
            sql = sql_add_tool(tool_name, tool_version)
            cursor.execute(sql)
            tool_id = cursor.lastrowid
        else:
            tool_id = info_tool['id']
        cursor.close()
        return tool_id

    return transaction(make_tool)
Beispiel #33
0
def singleRun():
    open('mergedTSF.txt', 'w').close()
    #run front end for 3 daily transactions
    transaction.transaction(test_id='1a')
    transaction.transaction(test_id='1b')
    transaction.transaction(test_id='1c')
    mTSF = open('mergedTSF.txt', 'a')
    mTSF.write(
        "EOS " + "0000000" + " " + "000" + " " + "0000000" + " " + "***\n"
    )  # extra final EOS line after concat based on backend requirements
    mTSF.close()
    #run back end to process transactions
    subprocess.call("python backendSourceCode.py newMAF.txt mergedTSF.txt")
Beispiel #34
0
    def POST(self):
        trans_data = cherrypy.request.json
        trans_list = trans_data['list']
        user_id = trans_data['user_id']
        from sqlalchemy import and_
        ipaddress = cherrypy.request.remote.ip
        mytransaction = model.session.query(transaction).filter(
            and_(
                transaction.created >= datetime.date.today(),
                transaction.created <
                datetime.date.today() + datetime.timedelta(days=1),
                transaction.ipadress == ipaddress,
                transaction.user_id == user_id)).one_or_none()
        if mytransaction is None:
            mytransaction = transaction(user_id, ipaddress)
            mytransaction.save()
        for vh in trans_list:
            myvisit_history = visit_history(vh, mytransaction.id)
            myvisit_history.save()

        return []
    def POST(self):
        trans_data = cherrypy.request.json
        trans_list = trans_data['list']
        user_id = trans_data['user_id']
        from sqlalchemy import and_
        ipaddress = cherrypy.request.remote.ip
        mytransaction = model.session.query(transaction).filter(
                and_(
                    transaction.created >= datetime.date.today(),
                    transaction.created < datetime.date.today() + datetime.timedelta(days=1),
                    transaction.ipadress == ipaddress,
                    transaction.user_id == user_id
                )
            ).one_or_none()
        if mytransaction is None:
            mytransaction = transaction(user_id, ipaddress)
            mytransaction.save()
        for vh in trans_list:
            myvisit_history = visit_history(vh, mytransaction.id)
            myvisit_history.save()

        return []
Beispiel #36
0
    def sell_stock_at_end_of_day(self, bought, close_price, index):
        self.total_sold += bought
        self.total_sell = self.total_sell + bought * float(
            self.rowslist[index][1])
        self.overall_sell = self.overall_sell + bought * float(
            self.rowslist[index][1])
        self.logger.info("Stock " + self.line[0] + " sold " + str(bought) +
                         " shares at " + self.rowslist[index][1] +
                         " price at date " + str(self.rowslist[index])[2:12] +
                         " at time " + str(self.rowslist[index])[13:18] + "\n")
        self.overall_c_sellEod = self.overall_c_sellEod + 1
        self.c_total_sellEOD = self.c_total_sellEOD + 1
        # the last element has already been initialised to  0.  modify it to the sold amount
        self.sell_amount[-1] = bought * float(self.rowslist[index][1])
        self.sell_EOD[-1] = "1"

        print_object = transaction(self.path_to_transaction_file)
        date = str(self.rowslist[index])[2:12]
        time = str(self.rowslist[index])[12:18]
        print_object.print_transaction_items(date, time, self.line[0], "0",
                                             str(bought),
                                             str(self.rowslist[index][2]),
                                             str(self.sell_amount[-1]), "3")
Beispiel #37
0
	def __init__(self,prev_hash):
		self.prev_hash = prev_hash
		self.max_trans_num = 5
		self.nonce = dummy_nonce
		self.translist = [transaction.transaction(0,0) for i in range (self.max_trans_num)] 	
import transaction
import createnode
import proof_of_work
import block
import treestruct

#	teacher1 -> student1 == 10
t = transaction.transaction(1,2)
t.sign = "teacher1sign"
t.hash = 12346
t.inlist[0].hash = "100"
t.inlist[0].n = 0
t.inlist[0].sign = "signghf"
t.inlist[0].pub = createnode.teacher1publickey
t.outlist[0].value = 10
t.outlist[0].addr = createnode.student1publickey
t.outlist[1].value = 90
t.outlist[1].addr = createnode.teacher1publickey

createnode.i_am.currentblock.add_trans_to_block(t)

#	teacher2 -> student2 == 10
t = transaction.transaction(1,2)
t.sign = "teacher2sign"
t.hash = 12347
t.inlist[0].hash = "101"
t.inlist[0].n = 0
t.inlist[0].sign = "signghf"
t.inlist[0].pub = createnode.teacher2publickey
t.outlist[0].value = 10
t.outlist[0].addr = createnode.student2publickey
def transaction_test():
    conn = server.connect()
    for tx_hash in hashes: #each hash is its own test case
        yield assert_true, transaction.transaction(tx_hash, conn).verify()
Beispiel #40
0
from treestruct import *
import block
import node


# adding the block to the blockchain kept by node1, assuming this test is run from the node1's machine
node0 = node.node()
node1 = node.node()
node2 = node.node()
node3 = node.node()
node4 = node.node()

block1 = block.block(9999)	#genesis hash

#transaction 1 in the block sent by node0 with address 1000
t1 = transaction.transaction(0,2)
t1.sign = "sign1"
t1.hash = 12341
# no input trans but has two outputs
t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)]
t1.outlist[0].value = 1
t1.outlist[0].addr = node1.publickey
t1.outlist[1].value = 19
t1.outlist[1].addr = node0.publickey
# adding trans1 to the block
block1.translist[0] = t1

#transaction 2 in the block sent by node0 with address 1000
t1 = transaction.transaction(1,2)
t1.sign = "sign2"
t1.hash = 12342
Beispiel #41
0
i_am.publickey = "1"

#teacher's public keys are kept static
teacher1publickey = "1"
teacher2publickey = "2"
teacher3publickey = "3"
teacher4publickey = "4"
teacher5publickey = "5"

student1publickey = "876"
student2publickey = "567"
student3publickey = "563"
student4publickey = "890"
student5publickey = "173"

t1 = transaction.transaction(0,1)
t1.sign = "signadmin"
t1.hash = "100"
t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)]
t1.outlist[0].value = transaction.transaction(0,0).STAR
t1.outlist[0].addr = teacher1publickey
i_am.blockhead.propblock.add_trans_to_block(t1)


t1 = transaction.transaction(0,1)
t1.sign = "signadmin"
t1.hash = "101"
t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)]
t1.outlist[0].value = transaction.transaction(0,0).STAR
t1.outlist[0].addr = teacher2publickey
i_am.blockhead.propblock.add_trans_to_block(t1)
import createnode
import transaction
import block


t = transaction.transaction(1,3)
t.sign = "teacher1sign"
t.hash = "12346"
t.inlist[0].hash = "100"
t.inlist[0].n = 0
t.inlist[0].sign = "teacher1sign"
t.inlist[0].pub = createnode.teacher1publickey
t.outlist[0].value = 70
t.outlist[0].addr = createnode.teacher1publickey
t.outlist[1].value = 10
t.outlist[1].addr = createnode.student2publickey
t.outlist[2].value = 20
t.outlist[2].addr = createnode.student1publickey

# write the transaction to a file
transaction.transtofile(t, "trans1.txt")
transaction.signtrans(createnode.i_am, "trans1.txt")
newt = transaction.filetotrans("signedtrans5.txt")

#add transaction to the currentblock of the node
createnode.i_am.currentblock.add_trans_to_block(newt)
	def read(self):
		while '!' in self.fileBuffer.peek(1)[0]:
			self.qifHeaders.append(self.fileBuffer.readline().strip())
		for transaction_fields in [tran.strip().split("\n") for tran in self.fileBuffer.read().split("^")]:
			if len(transaction_fields) > 1:
				self.qifTransactions.append(transaction.transaction(transaction_fields))
import sys, yaml
from transaction import transaction, add_transaction

for a in range(1,len(sys.argv)):
    i = sys.argv[a]
    transactionArray = i.split(',')
    length = len(transactionArray)
    
    if length == 3:
        t = transaction(transactionArray[0], transactionArray[1],transactionArray[2])
    if length == 4 :
        t = transaction(transactionArray[0], transactionArray[1],transactionArray[2], transactionArray[3])
    if length == 5:
        t = transaction(transactionArray[0], transactionArray[1],transactionArray[2], transactionArray[3], True) 

    if length >= 3 and length <= 5:
        add_transaction(t)