Exemple #1
0
def learned_current_acoin_interval(tup,
                                   onAcoinInterval=None,
                                   onNewIntervalCallback=None):
    #there must be at least one interval
    if len(tup) != 2:
        log_ex("Bank ran out of ACoin intervals!",
               "THIS MUST BE FIXED IMMEDIATELY")
        return
    current, next = tup
    interval = current[0]
    expires = DBUtil.ctime_to_int(current[1].ctime())
    expiresNext = DBUtil.ctime_to_int(next[1].ctime())
    #expires is natively a datetime
    #expires = DBUtil.ctime_to_int(expires.ctime())
    Globals.CURRENT_ACOIN_INTERVAL = [interval, expires, expiresNext]
    if onNewIntervalCallback:
        onNewIntervalCallback()
    now = int(time.time())
    if Globals.isListening == False:
        onAcoinInterval()
        Globals.isListening = True
    #schedule the next lookup after we know when the interval rolls over
    lookupTime = expires - now + (MAX_BANK_CLOCK_SKEW)
    if lookupTime <= 0:
        lookupTime = EXPIRED_CHECK_INTERVAL
    Globals.reactor.callLater(lookupTime, update_local_acoin_interval,
                              onAcoinInterval, onNewIntervalCallback)
  def insert_interval_row(base, highestInterval):
    validAfter = base
    spoilsOn = validAfter + lifetime

    sql = "INSERT INTO acoin_interval (interval_id, valid_after, spoils_on) VALUES (%s, %s, %s)"
    inj = (highestInterval, DBUtil.int_to_ctime(validAfter), DBUtil.int_to_ctime(spoilsOn))
    cur.execute(sql, inj)
    
    return validAfter, spoilsOn
    def insert_interval_row(base, highestInterval):
        validAfter = base
        spoilsOn = validAfter + lifetime

        sql = "INSERT INTO acoin_interval (interval_id, valid_after, spoils_on) VALUES (%s, %s, %s)"
        inj = (highestInterval, DBUtil.int_to_ctime(validAfter),
               DBUtil.int_to_ctime(spoilsOn))
        cur.execute(sql, inj)

        return validAfter, spoilsOn
Exemple #4
0
def _create_table(statType, cur):
    stat = statType()
    tableName = stat._get_table_name()
    if not DBUtil.table_exists(cur, tableName):
        sql = "CREATE TABLE %s (time TIMESTAMP WITHOUT TIME ZONE, value REAL);" % (
            tableName)
        cur.execute(sql)
Exemple #5
0
def _update_statistics(cur, startTime, intervalLen, statTypes):
  """Update all statistics with the most recent events from the database"""
  currentTime = DBUtil.get_current_gmtime()
  intervalStartTime = startTime - (startTime % intervalLen)
  #for each type of stat:
  for statType in statTypes:
    #for each interval:
    for period in range(intervalStartTime, currentTime, intervalLen):
      #calculate the statistic
      stat = statType(period, period+intervalLen)
      stat.calculate(cur)
      #update it in the database
      stat.update(cur)
Exemple #6
0
def _update_statistics(cur, startTime, intervalLen, statTypes):
    """Update all statistics with the most recent events from the database"""
    currentTime = DBUtil.get_current_gmtime()
    intervalStartTime = startTime - (startTime % intervalLen)
    #for each type of stat:
    for statType in statTypes:
        #for each interval:
        for period in range(intervalStartTime, currentTime, intervalLen):
            #calculate the statistic
            stat = statType(period, period + intervalLen)
            stat.calculate(cur)
            #update it in the database
            stat.update(cur)
 def _on_learned_hexkey(self, result):
   """Called when the sql query to retrieve the invite hexkey from the IP cache finishes"""
   #if there was no entry in the cache
   if not result:
     self._reply(RESPONSE_CODES["BAD_EMAIL"])
     return
   
   #unpack the db result
   hexKey, eventTime = result[0]
   eventTime = eventTime.ctime()
   
   #if the cache entry is too old
   if DBUtil.ctime_to_int(eventTime) - DBUtil.ctime_to_int(self.curTime) > CACHE_ENTRY_LIFETIME:
     self._reply(RESPONSE_CODES["BAD_EMAIL"])
     return
     
   #otherwise, check if this invite has been redeemed yet
   sql = "SELECT value, email FROM email_signup_keys WHERE redeemed = FALSE AND value = %s"
   inj = (hexKey,)
   redeemedDeferred = self.db.read(sql, inj)
   redeemedDeferred.addCallback(self._on_learned_invite)
   redeemedDeferred.addErrback(self._handle_error)
Exemple #8
0
    def _on_learned_hexkey(self, result):
        """Called when the sql query to retrieve the invite hexkey from the IP cache finishes"""
        #if there was no entry in the cache
        if not result:
            self._reply(RESPONSE_CODES["BAD_EMAIL"])
            return

        #unpack the db result
        hexKey, eventTime = result[0]
        eventTime = eventTime.ctime()

        #if the cache entry is too old
        if DBUtil.ctime_to_int(eventTime) - DBUtil.ctime_to_int(
                self.curTime) > CACHE_ENTRY_LIFETIME:
            self._reply(RESPONSE_CODES["BAD_EMAIL"])
            return

        #otherwise, check if this invite has been redeemed yet
        sql = "SELECT value, email FROM email_signup_keys WHERE redeemed = FALSE AND value = %s"
        inj = (hexKey, )
        redeemedDeferred = self.db.read(sql, inj)
        redeemedDeferred.addCallback(self._on_learned_invite)
        redeemedDeferred.addErrback(self._handle_error)
Exemple #9
0
def learned_current_acoin_interval(tup, onAcoinInterval=None, onNewIntervalCallback=None):
  #there must be at least one interval
  if len(tup) != 2:
    log_ex("Bank ran out of ACoin intervals!", "THIS MUST BE FIXED IMMEDIATELY")
    return
  current, next = tup
  interval = current[0]
  expires = DBUtil.ctime_to_int(current[1].ctime())
  expiresNext = DBUtil.ctime_to_int(next[1].ctime())
  #expires is natively a datetime
  #expires = DBUtil.ctime_to_int(expires.ctime())
  Globals.CURRENT_ACOIN_INTERVAL = [interval, expires, expiresNext]
  if onNewIntervalCallback:
    onNewIntervalCallback()
  now = int(time.time())
  if Globals.isListening == False:
    onAcoinInterval()
    Globals.isListening = True
  #schedule the next lookup after we know when the interval rolls over
  lookupTime = expires-now + (MAX_BANK_CLOCK_SKEW)
  if lookupTime <= 0:
    lookupTime = EXPIRED_CHECK_INTERVAL
  Globals.reactor.callLater(lookupTime, update_local_acoin_interval, onAcoinInterval, onNewIntervalCallback)
  def _on_learned_invite(self, result):
    """Called when the sql query to retrieve the invite hexkey and email out of the database finishes"""
    #fail if we couldnt find an invite
    if not result:
      self._reply(RESPONSE_CODES["BAD_EMAIL"])
      return
      
    #unpack the database response
    self.hexKey, self.email = result[0]

    #everything checks out, time to actually insert the user
    self.saltedPassword = DBUtil.format_auth(self.username, self.password)
    sql = "INSERT INTO accounts (username, balance, email, time, password) VALUES (%s, %s, %s, %s, %s) RETURNING username"
    inj = (self.username, STARTING_BALANCE, self.email, self.curTime, cyborg.Binary(self.saltedPassword))
    creationDeferred = self.db.Pool.conn_pool.runQuery(sql, inj)
    creationDeferred.addCallback(self._on_account_creation_succeeded)
    creationDeferred.addErrback(self._on_account_creation_failed)
Exemple #11
0
    def _on_learned_invite(self, result):
        """Called when the sql query to retrieve the invite hexkey and email out of the database finishes"""
        #fail if we couldnt find an invite
        if not result:
            self._reply(RESPONSE_CODES["BAD_EMAIL"])
            return

        #unpack the database response
        self.hexKey, self.email = result[0]

        #everything checks out, time to actually insert the user
        self.saltedPassword = DBUtil.format_auth(self.username, self.password)
        sql = "INSERT INTO accounts (username, balance, email, time, password) VALUES (%s, %s, %s, %s, %s) RETURNING username"
        inj = (self.username, STARTING_BALANCE, self.email, self.curTime,
               cyborg.Binary(self.saltedPassword))
        creationDeferred = self.db.Pool.conn_pool.runQuery(sql, inj)
        creationDeferred.addCallback(self._on_account_creation_succeeded)
        creationDeferred.addErrback(self._on_account_creation_failed)
        cur.execute("DELETE FROM acoin_interval WHERE interval_id > %s",
                    (nextInterval, ))
        tup = get_last_interval()
        curInterval, curTime = tup[0]
        print(
            "You deleted ALL intervals after %s (expires at %s).  Are you SURE you wanted to do that?  (type anything except continue to abort):  "
            % (nextInterval, nextTime.ctime()))
        x = raw_input()
        if x != "continue":
            raise Exception("User aborted.")
    assert tup
    assert len(tup) == 1

    highestACoinInterval, highestACoinFreshUntil = tup[0]
    #the freshness is a ctime type... we need to convert it into a float
    base = DBUtil.ctime_to_int(highestACoinFreshUntil.ctime())
    highestACoinInterval = int(highestACoinInterval)

    sql = []
    inj = []
    startTime = highestACoinFreshUntil.ctime()
    startInterval = highestACoinInterval
    print("Creating intervals...")
    for x in range(numberOfIntervalsToMake):
        highestACoinInterval += 1
        validAfter, spoilsOn = insert_interval_row(base, highestACoinInterval)
        #need to update base for next iteration
        base = spoilsOn

    print(
        "Created %s interval[s] from time %s to time %s ending with interval: %s"
    x = raw_input()
    if x != "y":
      raise Exception("User aborted.")
    cur.execute("DELETE FROM acoin_interval WHERE interval_id > %s", (nextInterval,))
    tup = get_last_interval()
    curInterval, curTime = tup[0]
    print("You deleted ALL intervals after %s (expires at %s).  Are you SURE you wanted to do that?  (type anything except continue to abort):  " % (nextInterval, nextTime.ctime()))
    x = raw_input()
    if x != "continue":
      raise Exception("User aborted.")
  assert tup
  assert len(tup) == 1
    
  highestACoinInterval, highestACoinFreshUntil = tup[0]
  #the freshness is a ctime type... we need to convert it into a float
  base = DBUtil.ctime_to_int(highestACoinFreshUntil.ctime())
  highestACoinInterval = int(highestACoinInterval)

  sql = []
  inj = []
  startTime = highestACoinFreshUntil.ctime()
  startInterval = highestACoinInterval
  print("Creating intervals...")
  for x in range(numberOfIntervalsToMake):
    highestACoinInterval += 1
    validAfter, spoilsOn = insert_interval_row(base, highestACoinInterval)
    #need to update base for next iteration
    base = spoilsOn
    
  print("Created %s interval[s] from time %s to time %s ending with interval: %s"%(highestACoinInterval - 1 - startInterval, startTime, DBUtil.int_to_ctime(spoilsOn), highestACoinInterval - 1))
  conn.commit()
Exemple #14
0
 def _get_db_start_time(self):
   return DBUtil.int_to_ctime(self.startTime)
Exemple #15
0
 def _get_db_end_time(self):
   return DBUtil.int_to_ctime(self.endTime)
Exemple #16
0
def _create_table(statType, cur):
  stat = statType()
  tableName = stat._get_table_name()
  if not DBUtil.table_exists(cur, tableName):
    sql = "CREATE TABLE %s (time TIMESTAMP WITHOUT TIME ZONE, value REAL);" % (tableName)
    cur.execute(sql)
Exemple #17
0
 def _get_db_end_time(self):
     return DBUtil.int_to_ctime(self.endTime)
Exemple #18
0
 def _get_db_start_time(self):
     return DBUtil.int_to_ctime(self.startTime)