Пример #1
0
def list_sites(keys):
    """List sites with stored public keys"""
    key_store = KeyStore(get_config_file())
    for site, key in key_store.list_sites().iteritems():
        if keys:
            click.echo("{} = {}".format(site, key))
        else:
            click.echo(site)
Пример #2
0
 def __init__(self, cip, cport, sip, sport, lbip, lbport):
     # create an INET, STREAMing socket
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sip = sip
     self.sport = sport
     self.cip = cip
     self.cport = cport
     self.lbip = lbip
     self.lbport = lbport
     self.store = KeyStore((self.lbip, self.lbport), (self.cip, self.cport),
                           (self.sip, sport))  # KeyStore
Пример #3
0
def workflow(site):
    """Run the simulated workflow"""
    click.echo("Preparing input for site {}".format(site))
    key_store = KeyStore(get_config_file())
    if key_store.does_site_exist(site):
        flow.generate_mesh()
        flow.generate_control_files()
        flow.compress_input()
        flow.encrpyt_input()
        flow.transfer_files()
    else:
        click.echo("Site {} does not exist in keystore, please add_site".format(site))
Пример #4
0
    def run(self, argv):
        #os.system('clear')
        self.parseParameters(argv)
        self.versionCheck(
        )  #check the local version against the remote version
        self.displayBanner()  #Print banner first and all messages after
        self.loadConfig()  # load config
        modules_dict = self.loadModules()  # load input/action modules
        self.modulesLoaded()

        if self.config["list_modules"]:
            self.display.printModuleList(modules_dict)
            sys.exit()

        self.additionalInfo()
        self.msfCheck()

        # parse inputs
        for input in self.inputs.keys():
            for inputmodule in self.inputModules.keys():
                _instance = self.inputModules[inputmodule]
                if _instance.getType() == input:
                    for file in self.inputs[input]:
                        self.display.verbose("Loading [%s] with [%s]" %
                                             (file, inputmodule))
                        _instance.go(file)

        # populate any initial events
        self.populateInitEvents()

        # begin menu loop
        self.threadcount_thread = Thread(
            target=EventHandler.print_thread_count, args=(self.display, ))
        self.threadcount_thread.start()
        while self.isRunning:
            self.displayMenu()

        kb.save(self.kbSaveFile)

        # generate reports
        self.display.output("Generating Reports")
        for reportmodule in self.reportModules.keys():
            _instance = self.reportModules[reportmodule]
            _instance.process()

        self.display.output()
        self.display.output("Good Bye!")
        self.cleanup()
Пример #5
0
  def sendCoins(self):
    sendAmt = self.amountBox.get()            #Amount to send
    recvKey = self.recieverKey.get("1.0",'end-1c')   #recievers public key

    if not sendAmt:
      messagebox.showwarning("Warning", "Please enter a BitCoin amount.")
    elif len(recvKey) <= 1:
      messagebox.showwarning("Warning", "Please enter the receivers key.")
    else:
      result = messagebox.askyesno("Send Confirmation", 'Sending {} BitCoins to reciever:\n {}'.format(sendAmt, recvKey))

      if result:
        print('Sending {} BitCoins to reciever:\n {}'.format(sendAmt, recvKey))
        t = Transaction(owner=KeyStore.getPrivateKey(), callback=self.update_balance)
        
        try:
          pubKey = self.client.keyTable[recvKey]
        except:
          messagebox.showwarning('Address not found.', 'Oops. That PyCoin address could not be found.')
          return
        try:
          t.add_output(Transaction.Output(int(sendAmt), RSA.importKey(pubKey)))
        except:
          messagebox.showwarning('Insufficient funds.', 'Oops. It looks like you ran out of money. :(')
          return
        t.finish_transaction()

      self.amountBox.delete(0,END)
Пример #6
0
 def initApp(self):
   #Connect Here
   self.client = P2PClientManager.getClient(port=random.randint(40000, 60000))
   self.client.subscribe(Message.NEW_TRANSACTION, self.update_balance)
   self.client.subscribe_to_info(self.update_status)
   t = threading.Thread(target=self.start_miner)
   t.start()
   if not self.db.hasRanBefore():
     c = CoinBase(owner=KeyStore.getPrivateKey(), amt=100)
     c.finish_transaction()
     self.db.setRanBefore()
     #messagebox.showinfo('Welcome', 'This is your first time running the app. You get to start off with 100 PyCoins!')
   #Get balance, Save to variable below
   self.coin_balance.set(str(KeyStore.get_balance()))
   print('PyCoin Address: ', SHA.new(KeyStore.getPublicKey().exportKey()).hexdigest())
   log.debug("GUI created")
Пример #7
0
    def run(self, argv):
        #os.system('clear')
        self.parseParameters(argv)
        self.displayBanner() #Print banner first and all messages after
        self.loadConfig() # load config
        modules_dict = self.loadModules() # load input/action modules
        self.modulesLoaded()

        if self.config["list_modules"]:
            self.display.printModuleList(modules_dict)
            sys.exit()

        self.additionalInfo()
        self.msfCheck()

        # parse inputs
        for input in self.inputs.keys():
            for inputmodule in self.inputModules.keys():
                _instance = self.inputModules[inputmodule]
                if _instance.getType() == input:
                    for file in self.inputs[input]:
                        self.display.verbose("Loading [%s] with [%s]" % (file, inputmodule))
                        _instance.go(file)

        # populate any initial events
        self.populateInitEvents()

        # begin menu loop
        self.threadcount_thread = Thread(target=EventHandler.print_thread_count, args=(self.display,))
        self.threadcount_thread.start()
        self.runScan()  # Skip first trip through menu and go straight into a scan using whatever arguments were passed
        self.isRunning = False
#        while self.isRunning:
#            self.displayMenu()

        if (kb):
            kb.save(self.kbSaveFile)

        # generate reports
        self.display.output("Generating Reports")
        for reportmodule in self.reportModules.keys():
            _instance = self.reportModules[reportmodule]
            _instance.process()

        self.display.output()
        self.display.output("Good Bye!")
        self.cleanup()
Пример #8
0
 def show_address(self):
   f = Tk()
   label = Label(f, text='PyCoin Address')
   label.pack()
   k = SHA.new(KeyStore.getPublicKey().exportKey()).hexdigest()
   key = Text(f, width=42, height=1)
   key.insert(INSERT, k)
   key.pack()
Пример #9
0
def add_key(tag):
    if tag.__class__.__name__ != 'NTAG215':
        logger.error(f'Wrong tag type ({tag.__class__.__name__})')
        return

    logger.info('Adding key')
    keystore = KeyStore(args.database_file)
    key = keystore.add_new_key(tag.identifier)
    secret = key[0]
    key = key[1]
    tag.write(6, secret[0:4])
    tag.write(7, secret[4:8])
    tag.write(8, secret[8:12])
    tag.write(9, secret[12:16])
    tag.protect(password=key.get_access_key(),
                read_protect=True,
                protect_from=4)
Пример #10
0
def configure():
    """Configure the client"""
    if not get_config_file():
        if click.confirm("Config file does not exist," " generate new keys and write file?"):
            key_store = KeyStore(get_config_file_name(), new=True)
            click.echo(
                "Keystore written to {} \n Private Key: \
                \n {} \n Public Key: \n {}".format(
                    get_config_file_name(), key_store.private_key, key_store.public_key
                )
            )
    else:
        key_store = KeyStore(get_config_file())
        private = click.prompt("Private Key", default=key_store.private_key)
        public = click.prompt("Public Key", default=key_store.public_key)
        key_store.update_key(private, public)
        click.echo("Keystore written to {}".format(get_config_file()))
Пример #11
0
    def run(self, argv):
        self.parseParameters(argv)
        self.displayBanner()  #Print banner first and all messages after
        self.loadConfig()  # load config
        modules_dict = self.loadModules()  # load input/action modules
        self.modulesLoaded()

        if self.config["list_modules"]:
            self.display.printModuleList(modules_dict)
            sys.exit()

        self.additionalInfo()

        # parse inputs
        for input in self.inputs.keys():
            for inputmodule in self.inputModules.keys():
                _instance = self.inputModules[inputmodule]
                if _instance.getType() == input:
                    for file in self.inputs[input]:
                        self.display.verbose("Loading [%s] with [%s]" %
                                             (file, inputmodule))
                        _instance.go(file)

        # populate any initial events
        self.populateInitEvents()

        # begin menu loop
        self.threadcount_thread = Thread(
            target=EventHandler.print_thread_count, args=(self.display, ))
        self.threadcount_thread.start()
        self.runScan(
        )  # Skip first trip through menu and go straight into a scan using whatever arguments were passed

        if (kb):
            kb.save(self.kbSaveFile)

        # generate reports
        self.display.output("Generating Reports")
        for reportmodule in self.reportModules.keys():
            _instance = self.reportModules[reportmodule]
            _instance.process()

        self.display.output()
        self.display.output("Good Bye!")
        self.cleanup()
Пример #12
0
 def __init__(self, name='config.txt'):
     self.name = name
     try:
         data = self._load_from_file()
         self.version = data['version']
         self.keyStore = KeyStore(data['keystore'])
     except IOError as e:
         self._generate_new()
     except ValueError as e:
         self._generate_new()
Пример #13
0
    def run(self, argv):
        # load config
        self.parseParameters(argv)
        self.loadConfig()

        # check the local version against the remote version
        self.versionCheck()

        # load input/action modules
        str = self.loadModules()

        # Everything must have loaded properly, so display the banner
        self.displayBanner()
        if (self.config["list_modules"]):
            self.display.print_list("List of Current Modules", str)
            self.display.output("")

        # parse inputs
        for input in self.inputs.keys():
            for inputmodule in self.inputModules.keys():
                _instance = self.inputModules[inputmodule]
                if (_instance.getType() == input):
                    for file in self.inputs[input]:
                        self.display.verbose("Loading [%s] with [%s]" %
                                             (file, inputmodule))
                        _instance.go(file)

        # populate any inital events
        self.populateInitEvents()

        # begin menu loop
        self.threadcount_thread = Thread(
            target=EventHandler.print_thread_count, args=(self.display, ))
        self.threadcount_thread.start()
        while self.isRunning:
            self.displayMenu()

        kb.save(self.kbSaveFile)

        self.display.output()
        self.display.output("Good Bye!")
        self.cleanup()
Пример #14
0
    def run(self, argv):
        # load config
        self.parseParameters(argv)
        self.loadConfig()

        # check the local version against the remote version
        self.versionCheck()

        # load input/action modules
        str = self.loadModules()

        # Everything must have loaded properly, so display the banner
        self.displayBanner()
        if (self.config["list_modules"]):
            self.display.print_list("List of Current Modules", str)
            self.display.output("")

        # parse inputs
        for input in self.inputs.keys():
            for inputmodule in self.inputModules.keys():
                _instance = self.inputModules[inputmodule]
                if (_instance.getType() == input):
                    for file in self.inputs[input]:
                        self.display.verbose("Loading [%s] with [%s]" % (file, inputmodule))
                        _instance.go(file)

        # populate any inital events
        self.populateInitEvents()

        # begin menu loop
        self.threadcount_thread = Thread(target=EventHandler.print_thread_count, args=(self.display,))
        self.threadcount_thread.start()
        while self.isRunning:
            self.displayMenu()

        kb.save(self.kbSaveFile)

        self.display.output()
        self.display.output("Good Bye!")
        self.cleanup()
Пример #15
0
    def run(self, argv):
        #os.system('clear')
        self.parseParameters(argv)
        self.versionCheck()  #check the local version against the remote version
        self.displayBanner() #Print banner first and all messages after
        self.loadConfig() # load config
        modules_dict = self.loadModules() # load input/action modules
        self.modulesLoaded()

        if self.config["list_modules"]:
            self.display.printModuleList(modules_dict)
            sys.exit()

        self.additionalInfo()
        self.msfCheck()

        # parse inputs
        for input in self.inputs.keys():
            for inputmodule in self.inputModules.keys():
                _instance = self.inputModules[inputmodule]
                if _instance.getType() == input:
                    for file in self.inputs[input]:
                        self.display.verbose("Loading [%s] with [%s]" % (file, inputmodule))
                        _instance.go(file)

        # populate any initial events
        self.populateInitEvents()

        # begin menu loop
        self.threadcount_thread = Thread(target=EventHandler.print_thread_count, args=(self.display,))
        self.threadcount_thread.start()
        while self.isRunning:
            self.displayMenu()

        kb.save(self.kbSaveFile)

        self.display.output()
        self.display.output("Good Bye!")
        self.cleanup()
Пример #16
0
def authenticate_key(tag):
    global currentEvent, pin

    if tag.__class__.__name__ != 'NTAG215':
        logger.error(f'Wrong tag type ({tag.__class__.__name__})')
        return

    logger.info('Authenticating key')
    keystore = KeyStore(args.database_file)
    key = keystore.get_key_from_db(tag.identifier)

    if key is None:
        logger.error('No key found for tag')
        return

    if tag.authenticate(key.access_key) and key.validate(tag.read(6)):
        logger.info('Switching on pin')
        pin.on()
        if pin.is_active:
            logger.info('Renewing scheduler')
            if currentEvent:
                currentEvent.cancel()
        currentEvent = Scheduler(10, pin.off)
        currentEvent.start()
Пример #17
0
def decrypt(input, key, agent_url, key_module, output):
    """Decrypt File"""
    click.echo("Decrypting file {}".format(input))
    if key:
        time, size, out_file = crypto.decrypt_file_with_symkey(input, key, output)
        click.echo("{} bytes decrypted in {} seconds,output to {}".format(size, time, out_file))
    elif agent_url:
        sym_key = agent.get_sym_key(agent_url)
        time, size, out_file = crypto.decrypt_file_with_symkey(input, sym_key, output)
        click.echo("{} bytes decrypted in {} seconds,output to {}".format(size, time, out_file))
    elif key_module:
        m = import_module(key_module)
        key_func = getattr(m, "get_private_key")
        priv_key = key_func()
        if priv_key is not None:
            key_store = KeyStore(get_config_file(), private_key=priv_key)
            time, size, out_file = key_store.decrypt_file(input, output)
            click.echo("{} bytes decrypted in {} seconds,output to {}".format(size, time, out_file))
        else:
            click.echo("Private Key not returned by key module")
    else:
        key_store = KeyStore(get_config_file())
        time, size, out_file = key_store.decrypt_file(input, output)
        click.echo("{} bytes decrypted in {} seconds,output to {}".format(size, time, out_file))
Пример #18
0
 def __init__(self, host, port=None):
     if port:
         P2PClient.CLIENT_PORT = port
     else:
         P2PClient.CLIENT_PORT = 65000
     log.debug('Creating client on port... %d', self.CLIENT_PORT)
     self.p2pserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     log.debug('Connecting to host...')
     self.p2pserver.connect((host, P2PClient.PORT))
     self.myIP = self.p2pserver.getsockname()[0]  # the ip of this machine
     self.myPublicKey = KeyStore.getPublicKey().exportKey()
     self.trans_queue = []
     self.received_trans = []
     self.received_blocks = []
     self.peer_list = []
     self.trans_listeners = []
     self.block_listeners = []
     self.keyTable = {}
Пример #19
0
 def __init__(self, host, port=None):
   if port:
     P2PClient.CLIENT_PORT = port
   else:
     P2PClient.CLIENT_PORT = 65000
   log.debug('Creating client on port... %d', self.CLIENT_PORT)
   self.p2pserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   log.debug('Connecting to host...')
   self.p2pserver.connect((host, P2PClient.PORT))
   self.myIP = self.p2pserver.getsockname()[0] # the ip of this machine
   self.myPublicKey = KeyStore.getPublicKey().exportKey()
   self.trans_queue = []
   self.received_trans = []
   self.received_blocks = []
   self.peer_list = []
   self.trans_listeners = []
   self.block_listeners = []
   self.keyTable = {}
Пример #20
0
def verify_single_block_multi_transaction_blockchain(tx_pool):
    blockchain = Blockchain()
    key_store = KeyStore()

    block_number = 0
    previous_block_hash = blockchain.current_block.block_hash if not blockchain.is_empty(
    ) else None
    header = BlockHeader(block_number, previous_block_hash, key_store,
                         config.MINING_DIFFICULTY)
    txs = [tx_pool.get() for i in xrange(config.BLOCKCHAIN_LENGTH)]
    block = MultiTransactionBlock(header, txs)

    if previous_block_hash:
        blockchain.current_block.header.next_block = block

    blockchain.accept_block(block)

    print block
    logger.info(block)

    blockchain.verify_chain()
Пример #21
0
class Config(object):
    
    def __init__(self, name='config.txt'):
        self.name = name
        try:
            data = self._load_from_file()
            self.version = data['version']
            self.keyStore = KeyStore(data['keystore'])
        except IOError as e:
            self._generate_new()
        except ValueError as e:
            self._generate_new()
        
    def _load_from_file(self):
        with open(self.name) as f:
            data = json.loads(f.read())
            return {
                'version': data['version'],
                'keystore': data['keystore']
            }

    def _generate_new(self):
        self.version = 1
        self.keyStore = KeyStore()
        self.save()

    def save(self):
        with open(self.name, 'w') as f:
            f.write(str(self))

    def to_config(self):
        return {
            'version': self.version,
            'keystore': self.keyStore.to_config()
        }

    def __str__(self):
        return json.dumps(self.to_config()) 
Пример #22
0
def main():
    args = parser.parse_args()
    key_store = KeyStore(args.project_id)
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')
    kms = GoogleKMS(kms_client, args.project_id, args.location_id,
                    args.key_ring_id, key_store)

    if args.command == "put":
        kms.put(args.key_id, Config.DEFAULT_DATASTORE_KIND, args.name,
                args.plaintext)
    elif args.command == "get":
        print(kms.get(args.key_id, Config.DEFAULT_DATASTORE_KIND, args.name))
    elif args.command == "get-all":
        print(kms.get_all(args.key_id, Config.DEFAULT_DATASTORE_KIND))
    elif args.command == "create-keyring":
        print(
            kms.create_key_ring(kms_client, args.project_id, args.location_id,
                                args.new_keyring_id))
    elif args.command == "create-key":
        print(
            kms.create_key(kms_client, args.project_id, args.location_id,
                           args.key_ring_id, args.new_key_id))
    else:
        parser.print_help()
Пример #23
0
 def get_conf():
     ks = KeyStore()
     return ks.get_elasticsearch_credentials()
Пример #24
0
 def displayKbMenu(self):
     searchString = ""
     depth = 0
     searches = {0: ""}
     self.display.output()
     self.display.output("---------------------------------------")
     self.display.output("Browse Knowledgebase")
     results = {}
     while True:
         self.display.output("[ " + searchString + " ]")
         if (searchString != ""):
             results = kb.get(searchString)
             i = 0
             for option in results:
                 self.display.output(str(i) + ". " + option)
                 i += 1
         else:
             self.display.output()
             self.display.output("0. host")
             self.display.output("1. service")
             self.display.output("2. domain")
             self.display.output("3. osint")
             results = ["host", "service", "domain", "osint"]
             i = 4  # Keep selection filter from breaking
         self.display.output()
         self.display.output(
             "Choose From Above Or: (a)dd, (d)elete, (b)ack, (m)ain menu, (i)mport, write to (t)emp file")
         self.display.output()
         search = self.display.input("Select option or enter custom search path: ")
         if search == "m":
             break
         elif search == "b":
             if depth > 0:
                 depth -= 1
             searchString = searches[depth]
         elif search == "a":
             text = self.display.input("Input new record: ")
             kb.add(searchString + "/" + text.replace("/", "|"))
         elif search == "d":
             choice = self.display.input("Choose record to remove: ")
             try:
                 if int(choice) in range(i):
                     kb.rm(searchString + "/" + results[int(choice)])
                 else:
                     self.display.error("%s - Not a valid option" % (choice))
             except ValueError:
                 self.display.error("Not a valid option")
         elif search == "i":
             self.display.error("Not implemented yet")
         elif search == "t":
             tempPath = self.config["tmpDir"] + "KBRESULTS-" + Utils.getRandStr(10) + ".txt"
             text = ""
             for line in results:
                 text = text + line + "\n"
             Utils.writeFile(text, tempPath)
             self.display.output("Results written to: %s" % (tempPath))
         elif re.match("([a-zA-Z0-9.\*]*/)+([a-zA-Z0-9.\*]*)", search) != None:
             # Input in form of a/b/c/d, search keystore
             searchString = search
             depth = 0
             searches[depth] = searchString
         else:
             try:
                 if int(search) in range(i):
                     if searchString == "":
                         searchString = results[int(search)]
                     else:
                         searchString = searchString + "/" + results[int(search)]
                     depth += 1
                     searches[depth] = searchString
                 else:
                     self.display.error("%s - Not a valid option" % (search))
             except ValueError:
                 self.display.error("%s - Not a valid option" % (search))
Пример #25
0
def add_site(site_name, public_key):
    """Add public key for new HPC site"""
    click.echo("Adding site key for site {}".format(site_name))
    key_store = KeyStore(get_config_file())
    key_store.add_site(site_name, public_key)
Пример #26
0
def get_shared_key(site):
    """Generate a shared key for the site"""
    key_store = KeyStore(get_config_file())
    pub_key, secret = key_store.get_shared_secret(site)
    click.echo("Public Key: \n{}".format(hexlify(pub_key)))
    click.echo("Secret: \n{}".format(hexlify(secret)))
Пример #27
0
from ucryptolib import aes
from hashlib import hmac_sha512

from io import BytesIO

reckless_fname = "%s/%s" % (storage_root, "reckless.json")

qr_scanner = QRScanner()
usb_host = USBHost()

# entropy that will be converted to mnemonic
entropy = None
# network we are using
network = None
# our key storage
keystore = KeyStore(storage_root=storage_root)

DEFAULT_XPUBS = []
ALL_XPUBS = []

SUPPORTED_SCRIPTS = {
    "p2wpkh": "Native Segwit",
    "p2sh-p2wpkh": "Nested Segwit",
    "p2wsh-sortedmulti": "Native Segwit Multisig",
    "p2sh-p2wsh-sortedmulti": "Nested Segwit Multisig",
}

def catchit(fn):
    """ Catches an error in the function and 
        displays error screen with exception """
    # Maybe there is a better way... 
Пример #28
0
 def _generate_new(self):
     self.version = 1
     self.keyStore = KeyStore()
     self.save()
Пример #29
0
 def displayKbMenu(self):
     searchString = ""
     depth = 0
     searches = {0: ""}
     self.display.output()
     self.display.output("---------------------------------------")
     self.display.output("Browse Knowledgebase")
     results = {}
     while True:
         self.display.output("[ " + searchString + " ]")
         if (searchString != ""):
             results = kb.get(searchString)
             i = 0
             for option in results:
                 self.display.output(str(i) + ". " + option)
                 i += 1
         else:
             self.display.output()
             self.display.output("0. host")
             self.display.output("1. service")
             self.display.output("2. domain")
             results = ["host", "service", "domain"]
             i = 3  # Keep selection filter from breaking
         self.display.output()
         self.display.output(
             "Choose From Above Or: (a)dd, (d)elete, (b)ack, (m)ain menu, (i)mport, write to (t)emp file"
         )
         self.display.output()
         search = self.display.input(
             "Select option or enter custom search path: ")
         if search == "m":
             break
         elif search == "b":
             if depth > 0:
                 depth -= 1
             searchString = searches[depth]
         elif search == "a":
             text = self.display.input("Input new record: ")
             kb.add(searchString + "/" + text.replace("/", "|"))
         elif search == "d":
             choice = self.display.input("Choose record to remove: ")
             try:
                 if int(choice) in range(i):
                     kb.rm(searchString + "/" + results[int(choice)])
                 else:
                     self.display.error("%s - Not a valid option" %
                                        (choice))
             except ValueError:
                 self.display.error("Not a valid option")
         elif search == "i":
             self.display.error("Not implemented yet")
         elif search == "t":
             tempPath = self.config[
                 "tmpDir"] + "KBRESULTS-" + Utils.getRandStr(10) + ".txt"
             text = ""
             for line in results:
                 text = text + line + "\n"
             Utils.writeFile(text, tempPath)
             self.display.output("Results written to: %s" % (tempPath))
         elif re.match("([a-zA-Z0-9.\*]*/)+([a-zA-Z0-9.\*]*)",
                       search) != None:
             # Input in form of a/b/c/d, search keystore
             searchString = search
             depth = 0
             searches[depth] = searchString
         else:
             try:
                 if int(search) in range(i):
                     if searchString == "":
                         searchString = results[int(search)]
                     else:
                         searchString = searchString + "/" + results[int(
                             search)]
                     depth += 1
                     searches[depth] = searchString
                 else:
                     self.display.error("%s - Not a valid option" %
                                        (search))
             except ValueError:
                 self.display.error("%s - Not a valid option" % (search))
Пример #30
0
      peer_list = pickle.loads(port)
      log.debug('peer list: %s', peer_list)
      client.update_peer_list(peer_list)
      client.broadcast_info('New peer added')
      
      

if __name__ == '__main__':
  import sys
  from keystore import KeyStore
  from TransactionManager.transaction import Transaction
  port = sys.argv[1]
  P2PClient.CLIENT_PORT = int(port)
  trans = Transaction()
  trans.add_input(Transaction.Input(20, b'FFFFFFFF'))
  trans.add_output(Transaction.Output(10, KeyStore.getPublicKey())) # just pay to ourselves for now
  trans.add_input(Transaction.Input(5, b'FFFFFFFF'))
  s = trans.build_struct()
  
  c = P2PClient()
  c.send_message(Message.add)
  c.send_message(Message.NEW_TRANSACTION, s)
  
  import time
  time.sleep(5)
  
  trans = Transaction()
  trans.add_input(Transaction.Input(100, b'FFFFFFFF'))
  trans.add_output(Transaction.Output(55, KeyStore.getPublicKey())) # just pay to ourselves for now
  trans.add_input(Transaction.Input(4, b'FFFFFFFF'))
  s = trans.build_struct()
Пример #31
0
 def update_balance(self, t=None):
   bal = str(KeyStore.get_balance())
   self.coin_balance.set(bal)
Пример #32
0
            peer_list = pickle.loads(port)
            log.debug('peer list: %s', peer_list)
            client.update_peer_list(peer_list)
            client.broadcast_info('New peer added')


if __name__ == '__main__':
    import sys
    from keystore import KeyStore
    from TransactionManager.transaction import Transaction
    port = sys.argv[1]
    P2PClient.CLIENT_PORT = int(port)
    trans = Transaction()
    trans.add_input(Transaction.Input(20, b'FFFFFFFF'))
    trans.add_output(Transaction.Output(
        10, KeyStore.getPublicKey()))  # just pay to ourselves for now
    trans.add_input(Transaction.Input(5, b'FFFFFFFF'))
    s = trans.build_struct()

    c = P2PClient()
    c.send_message(Message.add)
    c.send_message(Message.NEW_TRANSACTION, s)

    import time
    time.sleep(5)

    trans = Transaction()
    trans.add_input(Transaction.Input(100, b'FFFFFFFF'))
    trans.add_output(Transaction.Output(
        55, KeyStore.getPublicKey()))  # just pay to ourselves for now
    trans.add_input(Transaction.Input(4, b'FFFFFFFF'))
Пример #33
0
class Server:
    def __init__(self, cip, cport, sip, sport, lbip, lbport):
        # create an INET, STREAMing socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sip = sip
        self.sport = sport
        self.cip = cip
        self.cport = cport
        self.lbip = lbip
        self.lbport = lbport
        self.store = KeyStore((self.lbip, self.lbport), (self.cip, self.cport),
                              (self.sip, sport))  # KeyStore

    def start(self):
        threading.Thread(target=self.store.start).start()
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((self.cip, self.cport))
        self.socket.listen(constants.LEADER_QUEUE_SIZE)
        while 1:
            (clientsocket, address) = self.socket.accept()

            # parts = request_parser.ProtoParser.parse(msg)
            # t = threading.Thread(target=self.__process,
            #                     args=(clientsocket, parts))

            t = threading.Thread(target=self.__process_block,
                                 args=(clientsocket, ))
            t.start()

    def __process_block(self, clientsocket):
        msg = clientsocket.recv(constants.BUFFER_SIZE)
        print msg
        if msg[:3] == "set":
            while msg.count("\r\n") < 2:
                msg = msg + clientsocket.recv(constants.BUFFER_SIZE)
            parts = msg.split("\r\n")
            key = parts[0].split(" ")[1]
            val = parts[1]
            print msg, key, val
            self.set(key, val)
            clientsocket.send("STORED\r\n")
        elif msg[:3] == "get":
            while (msg.find("\r\n") == -1):
                msg = msg + clientsocket.recv(constants.BUFFER_SIZE)
            res = ""
            parts = msg.strip().split(" ")
            for part in parts[1:]:
                value = self.get(part)
                if value is not None:
                    res = res + "VALUE " + part + " 0 " + str(
                        len(value)) + "\r\n" + str(value) + "\r\n"
            print "get res ", res
            res += "END\r\n"
            clientsocket.send(res)
        clientsocket.close()

    def stop(self):
        pass

    # Calls Keystores API
    def get(self, key):
        return self.store.get(key)

    # Same
    def set(self, key, value):
        self.store.set(key, value)
Пример #34
0
def encrypt(target_site, input, output):
    """Encrypt File"""
    click.echo("Encrypting file {} for site {}".format(input, target_site))
    key_store = KeyStore(get_config_file())
    time, size, out_file = key_store.encrypt_file(target_site, input, output)
    click.echo("{} bytes encrypted in {} seconds, output to {}".format(size, time, out_file))
Пример #35
0
 def _retrieve_credentials(self):
     ks = KeyStore()
     creds = ks.get_email_credentials()
     self._user = creds["user"]
     self._password = creds["password"]
Пример #36
0
      
    return P2PClientManager.p2p
    
  def deleteClient():
    log.info('Deleting client...')
    P2PClientManager.p2p.stop()
    P2PClientManager.p2p = None
    
if __name__ == '__main__':
  import sys
  from keystore import KeyStore
  port = sys.argv[1]
  P2PClient.CLIENT_PORT = int(port)
  trans = Transaction()
  trans.add_input(Transaction.Input(20, b'FFFFFFFF', 0))
  trans.add_output(Transaction.Output(10, KeyStore.getPublicKey())) # just pay to ourselves for now
  trans.add_input(Transaction.Input(5, b'FFFFFFFF', 0))
  s = trans.build_struct()
  
  c = P2PClient()
  c.send_message(Message.add)
  c.send_message(Message.NEW_TRANSACTION, s)
  
  import time
  time.sleep(5)
  
  trans = Transaction()
  trans.add_input(Transaction.Input(100, b'FFFFFFFF', 0))
  trans.add_output(Transaction.Output(55, KeyStore.getPublicKey())) # just pay to ourselves for now
  trans.add_input(Transaction.Input(4, b'FFFFFFFF', 0))
  s = trans.build_struct()