当前位置: 首页>>代码示例>>Python>>正文


Python utils.Basic类代码示例

本文整理汇总了Python中common.utils.Basic的典型用法代码示例。如果您正苦于以下问题:Python Basic类的具体用法?Python Basic怎么用?Python Basic使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Basic类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_prefix

 def get_prefix(self):
   """@returns:  the beginning of the message from this relay"""
   #send back the PAR version first, so that people can deal with the message intelligently
   msg = Basic.write_byte(self.parVersion)
   #send back our hexid, so they know who this is from:
   msg += Basic.write_hexid(Globals.FINGERPRINT)
   return msg
开发者ID:clawplach,项目名称:BitBlinder,代码行数:7,代码来源:ServerPaymentHandler.py

示例2: sym_decrypt

 def sym_decrypt(self, msg):
   """this is disgusting because we use two different systems for symmetric encryption
   type 0 uses SmmetricKey while
   type 1 uses EncryptedDatagram
   quirks: 
   0 must also update the nonce stored in the db
   1 performs heavy crypto and has non symmetric client/server side encryption/decryption"""
   if not self.symKey:
     msgType, msg = Basic.read_byte(msg)
     if msgType is 0:
       #get the tor fingerprint so we know how to decrypt the message
       (binId,), msg = Basic.read_message('!20s', msg)
       #convert the tor fingerprint back into hex
       self.hexId = binascii.hexlify(binId).upper()
       #get the symmetric key out of the database:
       sql = "SELECT Owner, Public_Key, Msgnum, auth_blob FROM Relays WHERE Tor_Id = %s"
       inj = (self.hexId,)
       d = db.read(sql, inj)
       #get the sym key from the db and decrypt the msg
       d.addCallback(self.fetch_sym_key, msg)
       #update the message number in the database
       d.addCallback(self.update_db)
     elif msgType is 1:
       self.symKey = EncryptedDatagram.ServerSymKey(Globals.GENERIC_KEY)
       d = threads.deferToThread(self.get_sym_key_value, msg)
     else:
       raise Exception("Unknown msgType:  %s" % (msgType))
   else:
     raise Exception('Passing more than one message per tcp connection is currently not supported')
   return d
开发者ID:clawplach,项目名称:BitBlinder,代码行数:30,代码来源:BankServer.py

示例3: unpack_and_mint

 def unpack_and_mint(self, msg):
   """unpacks the request retreiving the number of coins packed and the total value desired.
   Verification: values must be positive!
   """
   self.number, msg = Basic.read_short(msg)
   value, msg = Basic.read_int(msg)
   log_msg('REQUEST:: %s %s'%(self.number, self.hexId), 0)
   if not BankUtil.is_positive_integer(self.number):
     raise ValueError('number of coins must be greater than 0!')
   if value != ACOIN_VALUE or not BankUtil.is_positive_integer(value):
     raise ValueError('coins must have a positive, integer value')
     
   self.bill = 0
   self.signatures = ""
   for i in range(0, self.number):
     #TODO: move to a worker pool or something
     sig = Globals.ACOIN_KEY.decrypt(msg[:Globals.ACOIN_KEY_BYTES], False)
     self.signatures += struct.pack('!%ss'%(Globals.ACOIN_KEY_BYTES), sig)
     msg = msg[Globals.ACOIN_KEY_BYTES:]
     self.bill += value
     
   #TODO: move this constraint to postgres to get rid of any potential race conditions
   sql = "SELECT balance FROM Accounts WHERE Username = %s"
   inj = (self.user,)
   d = db.read(sql, inj)
   return d
开发者ID:clawplach,项目名称:BitBlinder,代码行数:26,代码来源:ACoinMessages.py

示例4: datagramReceived

 def datagramReceived(self, datagram, address):
   try:
     self.address = address
     log_msg('Datagram received from %s:%s!'%address, 3)
     msgType, msg = Basic.read_byte(datagram)
     #for compatability really
     if msgType == 1:
       #is it a replay?
       if not cache.has_key(msg):
         self.request = msg
         self.symKey = EncryptedDatagram.ServerSymKey(Globals.GENERIC_KEY)
         msg = self.symKey.decrypt(msg)
         #for compatability really
         request_type, msg = Basic.read_byte(msg)
         if request_type == 3:
           self.handler = ACoinMessages.Payment(self.reply, self.address) 
           self.handler.on_message(msg)
         else:
           raise Exception("Unknown request_type:  %s" % (request_type))
       else:
         self.reply(cache[msg], putInQueue=False)
         return
     else:
       raise Exception("Unknown msgType:  %s" % (msgType))
   except Exception, e:
     self.err(e)
开发者ID:clawplach,项目名称:BitBlinder,代码行数:26,代码来源:BankServer.py

示例5: stringReceived

 def stringReceived(self, data):
   """Called when the login response arrives"""
   self.factory.done = True
   self.responseReceived = True
   text = None
   try:
     protocol, data = Basic.read_byte(data)
     if protocol == 1:
       returnCode, data = Basic.read_byte(data)
       if returnCode == 1:
         format = '!IIII4sI'
         (balance, currentACoinInterval, currentACoinIntervalExpiration, nextAcoinIntervalExpiration, host, port), blob = Basic.read_message(format, data)
         size = struct.calcsize(SymmetricKey.MESSAGE_FORMAT)
         authBlob = blob[:size]
         text = blob[size:]
         host = socket.inet_ntoa(host)
         self.factory.bank.on_new_info(balance, currentACoinInterval, currentACoinIntervalExpiration, nextAcoinIntervalExpiration)
         self.factory.bank.on_login_success(balance, authBlob, host, port, text)
       else:
         size = struct.calcsize('!I')
         timeout = struct.unpack('!I', data[:size])[0]
         text = data[size:]
         raise BadLoginPasswordError(timeout)
     else:
       raise Exception('unknown protocol: %s'%(protocol))
   except Exception, error:
     self.factory.bank.on_login_failure(error, text)
开发者ID:clawplach,项目名称:BitBlinder,代码行数:27,代码来源:LoginFactory.py

示例6: _send_remote_peer_request

 def _send_remote_peer_request(self, infohash, callback):
   #make sure we have a circuit to send it out on:
   if self.circ and self.circ.is_done():
     self.circ = None
   if not self.circ:
     self.circ = self.app.find_or_build_best_circuit(force=True, protocol="DHT")
     if self.circ == None:
       log_msg("Could not build circuit for DHT remote peer request", 0, "dht")
       return
   #generate the message:  (version, infohash, peerList)
   msg = ""
   #header:
   msg += Basic.write_byte(Node.VERSION)
   #infohash:
   msg += infohash
   #peers:
   for host, port in self.knownNodes:
     #is this an IP address?
     if isIPAddress(host):
       msg += Basic.write_byte(0)
       msg += struct.pack("!4sH", socket.inet_aton(host), port)
     #otherwise, it's a URL that has to be resolved remotely
     else:
       msg += Basic.write_byte(1)
       msg += Basic.write_lenstr(host)
       msg += Basic.write_short(port)
   self.circ.send_dht_request(msg, self.make_callback_wrapper(callback))
开发者ID:clawplach,项目名称:BitBlinder,代码行数:27,代码来源:Proxy.py

示例7: stringReceived

 def stringReceived(self, encryptedMsg):
   self.responseReceived = True
   self.transport.loseConnection()
   blob = self.factory.bank.decrypt_message(encryptedMsg)
   log_msg("ACoin REQUEST response received.", 4)
   responseCode, blob = Basic.read_byte(blob)
   #we had enough credits in our account
   if responseCode == 0:
     (newBalance, number), coins = Basic.read_message('!II', blob)
     #update the balance
     self.factory.bank.on_new_balance_from_bank(newBalance)
     acoinStrFormat = "%ss" % (Globals.ACOIN_KEY_BYTES)
     format = '!' + (acoinStrFormat * number)
     sigs = list(struct.unpack(format, coins))
     while len(self.factory.requests) > 0:
       request = self.factory.requests.pop(0)
       sig = sigs.pop(0)
       coin = BankMessages.parse_acoin_response(self.factory.bank, sig, request, ProgramState.DEBUG)
       if coin:
         self.factory.bank.add_acoin(coin)
       else:
         log_msg("Got an invalid ACoin from the bank!?", 3)
   #the bank could not check out the coins because our account doesn't have enough credits!
   else:
     (newBalance,), blob = Basic.read_message('!I', blob)
     self.factory.bank.on_new_balance_from_bank(newBalance)
开发者ID:clawplach,项目名称:BitBlinder,代码行数:26,代码来源:ACoinRequestFactory.py

示例8: message_arrived

 def message_arrived(self, msg):
     """Called when a payment message is received via the controller.
 Is responsible for piecing it back together into the actual message.
 @param msg:  the data received from Tor
 @type  msg:  str"""
     self.buffer += msg
     # is the whole message here?
     msgLen, msgData = Basic.read_short(self.buffer)
     if len(msgData) >= msgLen:
         msgData = msgData[:msgLen]
         # we just discard the rest of the cell, two messages are never packed in the same cell currently
         self.buffer = ""
         # what type of message is this?
         msgType, msgData = Basic.read_byte(msgData)
         # ok, now handle that message:
         for msgName in MESSAGE_CODES.keys():
             if msgType == MESSAGE_CODES[msgName]:
                 # if we don't know how to handle this message, just close the circuit
                 if msgName not in self.messageHandlers:
                     log_msg("Remote request for %s, which we do not know how to handle" % (msgName), 1)
                     self.close()
                     return
                 # get the handler:
                 handler = self.messageHandlers[msgName]
                 # get the handler function:
                 funcName = "handle_%s" % (msgName)
                 if not hasattr(handler, funcName):
                     raise Exception("%s cannot handle %s payment message?" % (handler, msgName))
                 f = getattr(handler, funcName)
                 f(msgData)
                 return
         # uhh, not sure how to handle this message:
         raise Exception("Unknown message type for payment message:  %s" % (msgType))
开发者ID:kans,项目名称:BitBlinder,代码行数:33,代码来源:TorMessages.py

示例9: load_public_key

  def load_public_key(s=None, fileName=None):
    assert s or fileName, "load_public_key must be passed either a string or file"
    if fileName:
      key = M2Crypto.RSA.load_pub_key(fileName)
      publicKey = PublicKey(key)
      eStr, nStr = key.pub()
      publicKey.e = Basic.bytes_to_long(eStr[4:])
      publicKey.n = Basic.bytes_to_long(nStr[4:])
      return publicKey
    else:
      start = s.find("-----BEGIN RSA PUBLIC KEY-----")
      end = s.find("-----END RSA PUBLIC KEY-----")
      if start == -1:
        raise Exception("Missing PEM prefix")
      if end == -1:
        raise Exception("Missing PEM postfix")
      remainder = s[end+len("-----END RSA PUBLIC KEY-----\n\r"):]
      s = s[start+len("-----BEGIN RSA PUBLIC KEY-----") : end]

      parser = decoder.decode(s.decode("base64"))[0]
      n = long(parser.getComponentByPosition(0))
      e = long(parser.getComponentByPosition(1))
      
      publicKey = PublicKey(n, e)
      return publicKey, remainder
开发者ID:clawplach,项目名称:BitBlinder,代码行数:25,代码来源:PublicKey.py

示例10: handle_bank_relay

 def handle_bank_relay(self, msg):
   """Send a message to the bank on behalf of someone else, then send the reply onward
   @param msg:  the message to relay
   @type  msg:  str"""
   version, msg = Basic.read_byte(msg)
   assert version == 1, "only accepts version 1 of PAR protocol"
   responseHop, msg = Basic.read_byte(msg)
   bankMsg, msg = Basic.read_lenstr(msg)
   responseMsg, msg = Basic.read_lenstr(msg)
   payment = UDPPayment.UDPPayment(self.bank, bankMsg)
   paymentDeferred = payment.get_deferred()
   def success(response, responseMsg=responseMsg, responseHop=responseHop):
     responseMsg += response
     if responseHop != 0:
       self.send_direct_tor_message(responseMsg, "payment", True, responseHop)
     else:
       self.handle_payment(responseMsg)
   paymentDeferred.addCallback(success)
   def failure(error):
     if error and hasattr(error, "value") and issubclass(type(error.value), TimeoutError):
       #TODO:  this indicates that the bank is down, or something is wrong with their network?
       log_msg("Relayed payment timed out  :(", 0, "par")
     else:
       log_ex(error, "Relaying payment message failed!")
   paymentDeferred.addErrback(failure)
开发者ID:clawplach,项目名称:BitBlinder,代码行数:25,代码来源:ServerPaymentHandler.py

示例11: _reply

 def _reply(self, code):
   """Send an appropriately encoded reply to the client"""
   self.reply_func(Basic.write_byte(1) + Basic.write_byte(code))
   if code == RESPONSE_CODES["SUCCESS"]:
     log_msg("Account %s created for %s" % (self.username, self.ipAddress))
   else:
     log_msg("Account creation attempt failed with code = %s" % (code))
开发者ID:clawplach,项目名称:BitBlinder,代码行数:7,代码来源:AccountCreation.py

示例12: __init__

 def __init__(self, n, e=None):
   """Pass either two arguments (e,n) to build from existing data, or pass one
   argument (n=existing key) to build from an existing key."""
   if e:
     eStrLen = 0
     tmp = 1L
     while tmp < e or eStrLen % 2 != 0:
       tmp *= 256L 
       eStrLen += 1
     nStrLen = 0
     #NOTE:  this is completely bizarre.  Why does m2crypto think that we need an odd number of bytes to encode a key?
     nStrLen += 1
     tmp = 1L
     while tmp < n or eStrLen % 2 != 0:
       tmp *= 256L 
       nStrLen += 1
     eStr = struct.pack(">I%ss" % (eStrLen), eStrLen, Basic.long_to_bytes(e, eStrLen))
     nStr = struct.pack(">I%ss" % (nStrLen), nStrLen, Basic.long_to_bytes(n, nStrLen))
     self.key = M2Crypto.RSA.new_pub_key((eStr, nStr))
     self.e = long(e)
     self.n = long(n)
   else:
     #validate that this is of the correct type:
     try:
       if n.__class__.__name__ not in ("RSA", "RSA_pub"):
         raise Exception("Wrong type")
     except:
       raise Exception("n is not the right type:  " + str(n))
     self.key = n
   #: length of the key in bytes (used in blinding/unblinding)
   self.keyLen = len(self.key)
开发者ID:clawplach,项目名称:BitBlinder,代码行数:31,代码来源:PublicKey.py

示例13: start_payment_loop

  def start_payment_loop(self):
    coin = Bank.get().get_acoins(1)
    if not coin:
      log_msg("No ACoins left!")
      return
    coin = coin[0]
    #generate ACoin request
    request = BankMessages.make_acoin_request(Bank.get(), Bank.get().currentACoinInterval, 1)
    #make the message:
    bankMsg = Basic.write_byte(1)
    bankMsg += coin.write_binary() + request.msg
    key = EncryptedDatagram.ClientSymKey(Bank.get().PUBLIC_KEY)
    bankMsg = Basic.write_byte(1) + key.encrypt(Basic.write_byte(3) + bankMsg)
    payment = UDPPayment.UDPPayment(Bank.get(), bankMsg)
    paymentDeferred = payment.get_deferred()
    def success(result, request=request):
      log_msg("success")
      self.payments += 1
#      self.start_payment_loop()
      #validate the ACoin
      code, sig = Basic.read_byte(result)
      coin = BankMessages.parse_acoin_response(Bank.get(), sig, request, False)
      if not coin:
        log_msg("Invalid ACoin sent for payment!")
      else:
        Bank.get().on_earned_coin(coin)
    paymentDeferred.addCallback(success)
    def failure(error):
      self.start_payment_loop()
      log_ex(error, "Failure during test?")
      self.failures += 1
    paymentDeferred.addErrback(failure)
开发者ID:clawplach,项目名称:BitBlinder,代码行数:32,代码来源:BankDisplay.py

示例14: _read_header

 def _read_header(self, data, msgName):
   #read the version
   version, data = Basic.read_byte(data)
   assert version == self.VERSION, "Bad version number: %s" % (version)
   #read the message type:
   msgType, data = Basic.read_byte(data)
   assert msgType == self.MESSAGES[msgName], "Bad message type: %s" % (msgType)
   return data
开发者ID:clawplach,项目名称:BitBlinder,代码行数:8,代码来源:EchoMixin.py

示例15: _port_test_failure

 def _port_test_failure(reason):
     # is this one of the errors that corresponds to unreachability?
     if Basic.exception_is_a(reason, [CannotListenError, TimeoutError]):
         return False
     # otherwise, we do not know the state of reachability (None signals that)
     # and log the error if necessary
     unexpectedException = not Basic.exception_is_a(reason, [ConnectError])
     if unexpectedException:
         log_ex(reason, "Unexpected failure while testing port")
     return None
开发者ID:kans,项目名称:BitBlinder,代码行数:10,代码来源:NetworkState.py


注:本文中的common.utils.Basic类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。