def loginAPI():
    global internal_storage, interruptQueue
    pub_hex = request.values.get("pub_key")
    pub_key = pub_hex
    internal_storage["Public_key"] = pub_key

    priv_hex = request.values.get("priv_key")
    priv_key = priv_hex
    internal_storage["Private_key"] = priv_key

    if getNeighbours(self_address):
        # not the first one
        # request latest block as json
        current_block = requestLatestBlock()

        data = json.loads(current_block)
        tx_list = []
        for tx in data['Tx_list']:
            tx_list.append(createTxFromDict(tx))
        # build block
        b = createBlockFromDict(tx_list, data)

        # update state
        bc = blockChain.Blockchain(_block=b)
        internal_storage["Miner"] = miner.Miner(
            _blockchain=bc,
            _pub=pub_key,
            _priv=priv_key
        )

    else:
        # create first block
        internal_storage["Miner"] = miner.Miner(_blockchain=None,
                                                _pub=pub_key,
                                                _priv=priv_key)
        generator = internal_storage["Miner"].mineBlock()
        try:
            interruptQueue = next(generator)
            block_data = next(generator)
            internal_storage["Miner"].broadcastBlock(
                _block_data=block_data,
                _neighbours=internal_storage["Neighbour_nodes"],
                _self_addr=self_address,
            )
        except StopIteration:
            print("MinerApp Interrupted")

    # re-routes back to homepage
    return homePage()
Exemple #2
0
def stat_from_memory(app, tlibpath="../tlib/", mempath="../memory/"):
    if os.path.exists("/tmp/stat.txt"):
        os.remove("/tmp/stat.txt")
    mine = miner.Miner(None, None, None, tlibpath, True, app, None, None, None,
                       None, mempath, False)
    mine.save_stat("/tmp/stat.txt")
    return load_statfile("/tmp/stat.txt")
    def test_part_two(self):
        "Test part two example of Miner object"

        # 1. Create Miner object from text
        myobj = miner.Miner(part2=True, text=aoc_04.from_text(PART_TWO_TEXT))

        # 2. Check the part two result
        self.assertEqual(myobj.part_two(verbose=False), PART_TWO_RESULT)
    def test_part_one(self):
        "Test part one example of Miner object"

        # 1. Create Miner object from text
        myobj = miner.Miner(text=aoc_04.from_text(PART_ONE_TEXT))

        # 2. Check the part one result
        self.assertEqual(myobj.part_one(verbose=False), PART_ONE_RESULT)
    def test_empty_init(self):
        "Test the default Miner creation"

        # 1. Create default Miner object
        myobj = miner.Miner()

        # 2. Make sure it has the default values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(myobj.text, None)
Exemple #6
0
    def __init__(self):
        '''
		Constructor function that creates a genesis block as soon as the 
		Blockchain class is created.
		'''

        self.main_chain_genesis = None
        self.latest_block = None

        self.__createGenesisBlock()

        miner.Miner(-1).mine(self.main_chain_genesis)
    def test_text_init(self):
        "Test the Miner object creation from text"

        # 1. Create Miner object from text
        myobj = miner.Miner(text=aoc_04.from_text(EXAMPLE_TEXT))

        # 2. Make sure it has the expected values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(len(myobj.text), 1)

        # 3. Check methods
        self.assertTrue(myobj.md5_number(609043).startswith('000001dbbfa'))
Exemple #8
0
 def insertAnalyzedResult(self, stockId, targetAt, period):
     stock = self.dbm.selectStockById(stockId)
     stockName = stock.get('name')
     print(stockName, 'is analyze', targetAt)
     if self.dbm.isNotForecastTarget(stock, targetAt.date(), period):
         return
     mine = miner.Miner()
     targetPlusCnt, targetMinusCnt, totalPlusCnt, totalMinusCnt, targetChartList, totalChartList, targetFinanceIdList, duration = mine.getAnalyzedCnt(
         targetAt, period, stockName, stock.get('id'))
     savedItemId = self.dbm.saveAnalyzedData(stockName, targetPlusCnt, targetMinusCnt, totalPlusCnt, totalMinusCnt,
                                             targetAt, period, duration)
     self.dbm.saveAnalyzedItemFinanceList(savedItemId, targetFinanceIdList)
     self.dbm.updateAnalyzedResultItem(stock)
     self.dbm.commit()
Exemple #9
0
def initiate_miners():
    the_miners_list = []

    if blockchainPlacement == 1:
        for i in range(NumOfFogNodes):
            the_miners_list.append(
                miner.Miner(i + 1, trans_delay, gossip_activated))
    if blockchainPlacement == 2:
        for i in range(NumOfMiners):
            the_miners_list.append(
                miner.Miner(i + 1, trans_delay, gossip_activated))
    for entity in the_miners_list:
        modification.write_file(
            "temporary/" + entity.address + "_local_chain.json", {})
        miner_wallets_log_py = modification.read_file(
            "temporary/miner_wallets_log.json")
        miner_wallets_log_py[str(
            entity.address)] = data['miners_initial_wallet_value']
        modification.rewrite_file("temporary/miner_wallets_log.json",
                                  miner_wallets_log_py)
    connect_miners(the_miners_list)
    output.miners_are_up()
    return the_miners_list
Exemple #10
0
def initiate_miners():
    the_miners_list = []
    miner_wallets_log_py = {}
    if blockchainPlacement == 1:
        for i in range(NumOfFogNodes):
            the_miners_list.append(
                miner.Miner(i + 1, trans_delay, gossip_activated))
    if blockchainPlacement == 2:
        for i in range(NumOfMiners):
            the_miners_list.append(
                miner.Miner(i + 1, trans_delay, gossip_activated))
    for entity in the_miners_list:
        with open(str("temporary/" + entity.address + "_local_chain.json"),
                  "w") as f:
            json.dump({}, f)
        with open("temporary/miner_wallets_log.json",
                  'w') as miner_wallets_log:
            miner_wallets_log_py[str(
                entity.address)] = data['miners_initial_wallet_value']
            json.dump(miner_wallets_log_py, miner_wallets_log, indent=4)
    connect_miners(the_miners_list)
    output.miners_are_up()
    return the_miners_list
Exemple #11
0
def part_two(args, input_lines):
    "Process part two of the puzzle"

    # 1. Create the puzzle solver
    solver = miner.Miner(part2=True, text=input_lines)

    # 2. Determine the solution for part two
    solution = solver.part_two(verbose=args.verbose, limit=args.limit)
    if solution is None:
        print("There is no solution")
    else:
        print("The solution for part two is %s" % (solution))

    # 3. Return result
    return solution is not None
Exemple #12
0
    def __init__(self, repo_dir, src_dir_suffix, model, top_n,
                 retriever_score_weight):
        print("Mining repository data")
        self.top_n = top_n
        self.retriever_score_weight = retriever_score_weight
        self.repository_miner = miner.Miner(repo_dir, src_dir_suffix)
        self.miner_data = self.repository_miner.mine()
        self.prediction_data = [[f[0], [m[0] for m in f[1]]]
                                for f in self.miner_data]
        self.result_transformer = SourceParagraphsTransformer(
            self.repository_miner.files)

        print("Fitting the pipeline")
        self.cdqa_pipeline = QAPipeline(
            reader=model,
            min_df=0.0,
            max_df=1.0,
            top_n=self.top_n,
            retriever_score_weight=retriever_score_weight)
def newUser():
    global internal_storage, interruptQueue
    priv, pub = keyPair.GenerateKeyPair()
    internal_storage["Private_key"] = priv.to_string().hex()
    internal_storage["Public_key"] = pub.to_string().hex()

    newUser = open("Newuser.html").read()

    info = "Public Key: {}<br>" \
    "Private Key: {}<br>" \
    "Please save these 2 (They are unrecoverable)".format(
        pub.to_string().hex(),
        priv.to_string().hex()
    )

    pub_key = internal_storage["Public_key"]
    priv_key = internal_storage["Private_key"]

    internal_storage["Miner"] = miner.Miner(_pub=pub_key, _priv=priv_key)

    # announce yourself
    getNeighbours(self_address)
    generator = internal_storage["Miner"].mineBlock()

    try:
        interruptQueue = next(generator)
        block_data = next(generator)
        internal_storage["Miner"].broadcastBlock(
            _block_data=block_data,
            _neighbours=internal_storage["Neighbour_nodes"],
            _self_addr=self_address,
        )
    except StopIteration:
        print("MinerApp New Interrupted")

    return info + newUser
Exemple #14
0
    def makeMiner(self, blockchain, txnMemoryPool):

        self.miner = miner.Miner(blockchain, txnMemoryPool)
Exemple #15
0
class VCM:
    """
    This class is simple abstract class
    just for showing responsibility of
    VCM (Vote Casting Machine).

    It just simulates VCMs' behavior.
    """

    blockchain = blockchain.Blockchain()
    miner = miner.Miner(100)
    election_public_key = crypto.load_public_key_file(config.ELECTION_KEYS_FOLDER, "election")

    def __init__(self, id):
        self.id = id
        self.private_key = crypto.load_private_key_file(config.VCM_KEYS_FOLDER, str(self.id))
        self.genesis_block = self.blockchain.get_block(0)

    """
    Start the machine.

    :param self: self class
    """
    def start(self):
        while True:
            os.system("clear")

            print("Welcome to Voting Interface")

            voter_id = raw_input("Please enter your ID: ")

            print("Verifying election signature...")

            self._verify_genesis_block()

            print("Election signature verification is successful")
            print("Fetching your electronic ballots...")

            voter_decrypted_ballots = self._get_voter_ballots(voter_id)

            print("Time to vote...")

            # let user read output
            self._wait_and_clear(2)

            for ballot in voter_decrypted_ballots:
                election_id_to_vote = ballot["election_id"]
                election_to_vote = self.genesis_block["content"]["election"][str(election_id_to_vote)]

                print("=" * 50)
                print("Please make your choice for %s \n" % election_to_vote["name"])
                print("Canditates are below: \n")

                for index, candidate in enumerate(election_to_vote["candidates"], start=1):
                    print("%d) %s" % (index, candidate))

                while True:
                    candidate_index = raw_input("\nPlease enter your choice: ")
                    candidate_index = int(candidate_index)

                    if candidate_index > 0 and candidate_index <= len(election_to_vote["candidates"]):
                        chosen_candidate = election_to_vote["candidates"][candidate_index - 1]

                        self.miner.add_vote(
                            self._cast_vote(chosen_candidate, ballot)
                        )

                        print("\nYou have chosen %s to vote" % (chosen_candidate))
                        print("=" * 50)

                        self._wait_and_clear(1)

                        break
                    else:
                        print("Please enter a value between 1 and %d \n" % (len(election_to_vote["candidates"])))

            print("Thanks for voting!")
            print("Restarting...")

            self._wait_and_clear(3)

    """
    Verify genesis block.

    :param self: self class
    """
    def _verify_genesis_block(self):
        crypto.verify(self.genesis_block["header"]["signature"], json.dumps(self.genesis_block["content"], sort_keys=True), self.election_public_key)

    """
    Get given voter's ballots.

    :param self: self class
    :param voter_id: voter_id
    """
    def _get_voter_ballots(self, voter_id):
        voter_decrypted_ballots = []
        voter_private_key = crypto.load_private_key_file(config.VOTER_KEYS_FOLDER, voter_id)
        voter_ballots = self.genesis_block["content"]["encrypted_ballots"][voter_id]

        for ballot in voter_ballots:
            decrypted_ballot = crypto.decrypt(ballot, voter_private_key)
            voter_decrypted_ballots.append(json.loads(decrypted_ballot))

        return voter_decrypted_ballots

    """
    Cast a vote with given parameters and sign it.

    :param self: self class
    :param chosen_candidate: chosen candidate
    :param proof: ballot content
    """
    def _cast_vote(self, chosen_candidate, proof):
        content = {
            "proof": proof,
            "vote": crypto.encrypt(str(chosen_candidate), self.election_public_key)
        }

        return {
            "content": content,
            "header": {
                "signature": crypto.sign(json.dumps(content, sort_keys=True), self.private_key),
                "vcm_id": self.id
            }
        }

    """
    Wait given seconds and clear terminal.

    :param self: self class
    :param wait: wait
    """
    def _wait_and_clear(self, wait):
        time.sleep(wait)
        os.system("clear")
Exemple #16
0
def main():
    parser = argparse.ArgumentParser(description="Miner")
    parser.add_argument('--tlibpath',
                        help="Test library path",
                        default="../tlib/")
    parser.add_argument('--apkspath', help="Apps path", default="../apks/")
    parser.add_argument('--parampath',
                        help="Param file path",
                        default="../etc/")
    parser.add_argument('app', help="App name")
    parser.add_argument('--mempath', help="memory path", default="../memory/")
    parser.add_argument('--erase', help="erase memory of tests")
    parser.add_argument('--query', help="query screen")
    parser.add_argument('--reset', help="reset route")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO)

    tags.load(os.path.join(args.parampath, "tags.txt"))
    value.init_params(args.parampath, args.app)
    appdb.collect_apps(args.apkspath)
    #appdb.load_urls(os.path.join(args.parampath, "urls.txt"))
    mine = miner.Miner(None, None, None, args.tlibpath, True, args.app, None,
                       None, None, None, args.mempath, False)

    if args.erase is not None:
        if os.path.exists(args.erase):
            keys = list(
                filter(lambda x: x,
                       open(args.erase).read().strip().split('\n')))
        else:
            keys = args.erase.split('#')

        if len(keys) == 0:
            print("no case to erase!")
            return

        print("%d cases to erase" % len(keys))
        for key in keys:
            feature_name, test_name = key.split(':')
            mine.erase_memory(feature_name, test_name)

        #mine.print_stat(simple=True)
        mine.save_memory()

        print("%d cases erased" % len(keys))
        return

    if args.reset is not None:
        route_no = int(args.reset)
        mine.slib.reset_route(route_no)
        mine.save_memory()
        return

    if args.query is not None:
        attrs = {}
        if ',' in args.query:
            screen = args.query.split(',')[0]
            for entry in args.query.split(',')[1:]:
                if '=' in entry:
                    key, val = entry.split('=', 1)
                    attrs[key] = val
                else:
                    if entry[0] == '-':
                        attrs[entry[1:]] = 'false'
                    else:
                        attrs[entry] = 'true'
        else:
            screen = args.query
        if screen != '.':
            attrs['screen'] = screen
        mine.slib.query_screen(attrs)
        return

    mine.print_stat(simple=True)
Exemple #17
0
def createMiner():
    m = miner.Miner()
    priv, pub = m.createNewAccount()

    return m, priv, pub
Exemple #18
0
def mine_coins():
    clear_window()
    ad = input("Enter your ID: ")
    mn = miner.Miner(block_chain=bc, miner_address=ad)
    print("Mining begun...")
    mn.mine_pending_transactions()
Exemple #19
0
n.addTransaction(t2)
n.showTransactions()
'''

t = AVLtree.AVL_Tree()
root = None
root = t.insert(root, 1)
root = t.insert(root, 2)
root = t.insert(root, 3)
print t.search(root, 2)
root = t.delete(root, 2)
print t.search(root, 2)
'''

user1 = user.User("rishik", "ajay")
user2 = user.User("rishik", "ajay")
n.addUser(user1)
n.addUser(user2)

m2 = miner.Miner(user2.getID())
m1 = miner.Miner(user1.getID())

m1.makeBlock(n)

print user1.getBalance()
print user2.getBalance()

n.showTransactions()

user1.processUpdates()
user1.showLedger()
Exemple #20
0
import transaction
import blockchain
import txnMemoryPool
import miner

# Create blockchain and genesis block in the process
krisChain = blockchain.Blockchain()
print("Height: " + str(len(krisChain.blockChain)))
krisChain.blockChain[-1].printBlock()

# Add two sets of transactions as blocks
krisPool = txnMemoryPool.TxnMemoryPool()

krisMiner = miner.Miner(krisChain, krisPool)

while (len(krisPool.memoryPool)) > 0:
    krisMiner.calculateNonce()
    #print("Height: " + str(len(krisChain.blockChain)))
    krisChain.blockChain[-1].printBlock()

#print("Height: " + str(len(krisChain.blockChain)))
Exemple #21
0
        elif hunt is not None:
            hunt = hunt.on_event(current_screen)
        else:
            army = army.on_event(current_screen)
            if not army:
                army = checkarmy.CheckArmy()
                winkey.send_key(winkey.VK_CODE['esc'])
                time.sleep(1)
                winkey.send_key(winkey.VK_CODE['esc'])
                time.sleep(1)

                if len(miners) is 0:
                    for p in players:
                        miners.append(
                            miner.Miner(
                                p,
                                screen.army_exists(current_screen,
                                                   p.base_area())))
                else:
                    found = False
                    for i, p in enumerate(players):
                        if screen.army_exists(current_screen, p.base_area()):
                            p.player_waiting_reset()
                            miners[i].set_wait_status(p)
                            found = True

                    if not found:
                        if not BLOCK_HUNTING and is_hunting_available(hunter):
                            print("START HUNTING")
                            hunt = hunting.Hunting(hunter.reset())
                            time.sleep(0.1)
                        else:
Exemple #22
0
 def start_workers(self):
     miner_thread = miner.Miner(self.blockchain, self.transactions)
     network_thread = network.Network()
     miner_thread.start()
     network_thread.start()
     return
Exemple #23
0
def erase(feature_name, test_name, tlibpath, app, mempath):
    mine = miner.Miner(None, None, None, tlibpath, True, app, None, None, None,
                       None, mempath, False)
    mine.erase_memory(feature_name, test_name)
    mine.save_memory()