Balances now belong to accounts, and identities map to an account

This commit is contained in:
moneromooo 2015-01-31 23:40:13 +00:00
parent 333c90d46a
commit b07bb7ba6b
8 changed files with 107 additions and 50 deletions

View File

@ -148,9 +148,10 @@ def AddBalance(link,cmd):
aidentity=Link(network,User(network,anick)).identity() aidentity=Link(network,User(network,anick)).identity()
else: else:
aidentity=anick aidentity=anick
account = GetAccount(aidentity)
log_info("AddBalance: Adding %s to %s's balance" % (AmountToString(units),aidentity)) log_info("AddBalance: Adding %s to %s's balance" % (AmountToString(units),aidentity))
try: try:
balance = redis_hincrby("balances",aidentity,units) balance = redis_hincrby("balances",account,units)
except Exception, e: except Exception, e:
log_error('AddBalance: exception: %s' % str(e)) log_error('AddBalance: exception: %s' % str(e))
link.send( "An error has occured") link.send( "An error has occured")
@ -349,12 +350,6 @@ def lower_nick(s,net):
return news return news
def MigrateRedis(): def MigrateRedis():
balances=redis_hgetall('balances')
for balance in balances:
if balance.find(':') == -1:
redis_hset('balances','freenode:'+balance,balances[balance])
redis_hdel('balances',balance)
keys=redisdb.keys('*') keys=redisdb.keys('*')
for key in keys: for key in keys:
if key.startswith('dice:stats:') and key.find('freenode:') == -1: if key.startswith('dice:stats:') and key.find('freenode:') == -1:
@ -424,6 +419,16 @@ def MigrateRedis():
redisdb.hset(hashname,altkey,redis_hget(hashname,k)) redisdb.hset(hashname,altkey,redis_hget(hashname,k))
redisdb.hdel(hashname,k) redisdb.hdel(hashname,k)
if not redis_exists('accounts'):
idx=0
balances = redis_hgetall('balances')
for key in balances:
redis_hset('balances',idx,balances[key])
redis_hset('accounts',key,idx)
redis_hdel('balances',key)
idx += 1
redis_set('next_account_id',idx)
RegisterCommands() RegisterCommands()
redisdb = connect_to_redis(config.redis_host,config.redis_port) redisdb = connect_to_redis(config.redis_host,config.redis_port)
MigrateRedis() MigrateRedis()

View File

@ -69,12 +69,13 @@ def IsBetValid(link,amount,minbet,maxbet,potential_loss,max_loss,max_loss_ratio)
def IsPlayerBalanceAtLeast(link,units): def IsPlayerBalanceAtLeast(link,units):
try: try:
balance = redis_hget("balances",link.identity()) account = GetAccount(link)
balance = redis_hget("balances",account)
if balance == None: if balance == None:
balance = 0 balance = 0
balance=long(balance) balance=long(balance)
if units > balance: if units > balance:
log_info ('%s does not have enough balance' % link.user.nick) log_info ('%s does not have enough balance' % link.identity())
return False, "You only have %s" % (AmountToString(balance)) return False, "You only have %s" % (AmountToString(balance))
except Exception,e: except Exception,e:
log_error ('failed to query balance') log_error ('failed to query balance')
@ -139,6 +140,7 @@ def GetServerSeedHash(link,game):
def RecordGameResult(link,game,win,lose,units): def RecordGameResult(link,game,win,lose,units):
identity=link.identity() identity=link.identity()
account=GetAccount(identity)
try: try:
ts=datetime.datetime.utcnow() ts=datetime.datetime.utcnow()
tsh="%u" % (ts.hour) tsh="%u" % (ts.hour)
@ -169,7 +171,7 @@ def RecordGameResult(link,game,win,lose,units):
p.zincrby(nzhtname+"wagered",tsh,units) p.zincrby(nzhtname+"wagered",tsh,units)
p.zincrby(nzdtname+"wagered",tsd,units) p.zincrby(nzdtname+"wagered",tsd,units)
if win: if win:
p.hincrby("balances",identity,units) p.hincrby("balances",account,units)
p.hincrby(tname,"won",units) p.hincrby(tname,"won",units)
p.hincrby(rtname,"won",units) p.hincrby(rtname,"won",units)
p.hincrby(alltname,"won",units) p.hincrby(alltname,"won",units)
@ -187,7 +189,7 @@ def RecordGameResult(link,game,win,lose,units):
p.zincrby(nzhtname+"nwon",tsh,1) p.zincrby(nzhtname+"nwon",tsh,1)
p.zincrby(nzdtname+"nwon",tsd,1) p.zincrby(nzdtname+"nwon",tsd,1)
if lose: if lose:
p.hincrby("balances",identity,-units) p.hincrby("balances",account,-units)
p.hincrby(tname,"lost",units) p.hincrby(tname,"lost",units)
p.hincrby(rtname,"lost",units) p.hincrby(rtname,"lost",units)
p.hincrby(alltname,"lost",units) p.hincrby(alltname,"lost",units)
@ -269,11 +271,11 @@ def RetrieveHouseBalance(force_refresh=False):
house_balance = unlocked_balance house_balance = unlocked_balance
user_balances=0 user_balances=0
identities = redis_hgetall("balances") accounts = redis_hgetall("balances")
for identity in identities: for account in accounts:
ib = long(identities[identity]) ab = long(accounts[account])
house_balance = house_balance - ib house_balance = house_balance - ab
user_balances+=ib user_balances+=ab
earmarked_balances=0 earmarked_balances=0
earmarked = redis_hgetall("earmarked") earmarked = redis_hgetall("earmarked")
@ -296,9 +298,13 @@ def GetHouseBalance(link,cmd):
try: try:
balance = RetrieveHouseBalance() balance = RetrieveHouseBalance()
personal_balance=0 personal_balance=0
seen_accounts=[]
for network in networks: for network in networks:
identity=network.name+':'+config.tipbot_name identity=network.name+':'+config.tipbot_name
personal_balance += long(redis_hget('balances',identity) or 0) account=redis_hget('accounts',identity)
if not account in seen_accounts:
personal_balance += long(redis_hget('balances',account) or 0)
seen_accounts.append(account)
except Exception,e: except Exception,e:
log_error('Failed to retrieve house balance: %s' % str(e)) log_error('Failed to retrieve house balance: %s' % str(e))
link.send('An error occured') link.send('An error occured')

View File

@ -24,6 +24,12 @@ class Link:
def __repr__(self): def __repr__(self):
return '<link: network %s, user %s, group %s, data %s>' % (str(self.network),str(self.user),str(self.group),str(self.data)) return '<link: network %s, user %s, group %s, data %s>' % (str(self.network),str(self.user),str(self.group),str(self.data))
def __eq__(self,link):
return self.identity()==link.identity()
def __ne__(self,link):
return not self.__eq__(link)
def identity(self): def identity(self):
return self.identity_string return self.identity_string

View File

@ -120,7 +120,8 @@ def Cancel(link,cmd):
for bettor in bettors: for bettor in bettors:
units = long(redis_hget(tname,bettor+":units")) units = long(redis_hget(tname,bettor+":units"))
log_info('Refunding %s to %s' % (AmountToString(units),bettor)) log_info('Refunding %s to %s' % (AmountToString(units),bettor))
p.hincrby('balances',bettor,units) a = GetAccount(bettor)
p.hincrby('balances',a,units)
p.hincrby('earmarked','bookie',-units) p.hincrby('earmarked','bookie',-units)
refundmsg.append('%s to %s' % (AmountToString(units), NickFromIdentity(bettor))) refundmsg.append('%s to %s' % (AmountToString(units), NickFromIdentity(bettor)))
p.hdel('bookie:active',book_index) p.hdel('bookie:active',book_index)
@ -300,9 +301,10 @@ def Bet(link,cmd):
log_info('%s wants to bet %s on %s' % (identity, AmountToString(units), outcome)) log_info('%s wants to bet %s on %s' % (identity, AmountToString(units), outcome))
try: try:
log_info('Bet: %s betting %s on outcome %s' % (identity, AmountToString(units), outcome)) log_info('Bet: %s betting %s on outcome %s' % (identity, AmountToString(units), outcome))
account = GetAccount(link)
try: try:
p = redis_pipeline() p = redis_pipeline()
p.hincrby("balances",identity,-units) p.hincrby("balances",account,-units)
p.hincrby("earmarked","bookie",units) p.hincrby("earmarked","bookie",units)
p.hincrby(tname+":bets",outcome,units) p.hincrby(tname+":bets",outcome,units)
p.hincrby(tname,"bets",units) p.hincrby(tname,"bets",units)
@ -359,11 +361,12 @@ def Result(link,cmd):
o = redis_hget(tname,bettor+":outcome") o = redis_hget(tname,bettor+":outcome")
ounits = long(redis_hget(tname,bettor+":units")) ounits = long(redis_hget(tname,bettor+":units"))
if o == outcome: if o == outcome:
a = GetAccount(bettor)
owinunits = long(total_units_bet * (1-config.bookie_fee) * ounits / total_units_bet_by_winners) owinunits = long(total_units_bet * (1-config.bookie_fee) * ounits / total_units_bet_by_winners)
if owinunits<ounits: if owinunits<ounits:
owinunits=units owinunits=units
resultmsg.append("%s wins %s" % (NickFromIdentity(bettor), AmountToString(owinunits))) resultmsg.append("%s wins %s" % (NickFromIdentity(bettor), AmountToString(owinunits)))
p.hincrby("balances",bettor,owinunits) p.hincrby("balances",a,owinunits)
else: else:
resultmsg.append("%s loses %s" % (NickFromIdentity(bettor), AmountToString(ounits))) resultmsg.append("%s loses %s" % (NickFromIdentity(bettor), AmountToString(ounits)))
p.hdel('bookie:active',book_index) p.hdel('bookie:active',book_index)

View File

@ -111,8 +111,11 @@ def UpdateCoin(data):
recipient = GetIdentityFromPaymentID(payment_id) recipient = GetIdentityFromPaymentID(payment_id)
if not recipient: if not recipient:
raise RuntimeError('Payment ID %s not found' % payment_id) raise RuntimeError('Payment ID %s not found' % payment_id)
account = redis_hget('accounts',recipient)
if accounts == None:
raise RuntimeError('No account found for %s' % recipient)
log_info('UpdateCoin: Found payment %s to %s for %s' % (tx_hash,recipient, AmountToString(amount))) log_info('UpdateCoin: Found payment %s to %s for %s' % (tx_hash,recipient, AmountToString(amount)))
cp.hincrby('confirming_payments',recipient,amount) cp.hincrby('confirming_payments',account,amount)
except Exception,e: except Exception,e:
log_error('UpdateCoin: No identity found for payment id %s, tx hash %s, amount %s: %s' % (payment_id, tx_hash, amount, str(e))) log_error('UpdateCoin: No identity found for payment id %s, tx hash %s, amount %s: %s' % (payment_id, tx_hash, amount, str(e)))
payments=new_payments payments=new_payments
@ -135,8 +138,10 @@ def UpdateCoin(data):
recipient = GetIdentityFromPaymentID(payment_id) recipient = GetIdentityFromPaymentID(payment_id)
if not recipient: if not recipient:
raise RuntimeError('Payment ID %s not found' % payment_id) raise RuntimeError('Payment ID %s not found' % payment_id)
if accounts == None:
raise RuntimeError('No account found for %s' % recipient)
log_info('UpdateCoin: Found payment %s to %s for %s' % (tx_hash,recipient, AmountToString(amount))) log_info('UpdateCoin: Found payment %s to %s for %s' % (tx_hash,recipient, AmountToString(amount)))
pipe.hincrby("balances",recipient,amount) pipe.hincrby("balances",account,amount)
pipe.sadd("processed_txs",tx_hash) pipe.sadd("processed_txs",tx_hash)
except Exception,e: except Exception,e:
log_error('UpdateCoin: No identity found for payment id %s, tx hash %s, amount %s: %s' % (payment_id, tx_hash, amount, str(e))) log_error('UpdateCoin: No identity found for payment id %s, tx hash %s, amount %s: %s' % (payment_id, tx_hash, amount, str(e)))

View File

@ -31,7 +31,9 @@ pending_confirmations=dict()
def PerformTip(link,whoid,units): def PerformTip(link,whoid,units):
identity=link.identity() identity=link.identity()
try: try:
balance = redis_hget("balances",identity) account = GetAccount(identity)
who_account = GetAccount(whoid)
balance = redis_hget("balances",account)
if balance == None: if balance == None:
balance = 0 balance = 0
balance=long(balance) balance=long(balance)
@ -45,8 +47,8 @@ def PerformTip(link,whoid,units):
p.incrby("tips_total_amount",units); p.incrby("tips_total_amount",units);
p.hincrby("tips_count",identity,1); p.hincrby("tips_count",identity,1);
p.hincrby("tips_amount",identity,units); p.hincrby("tips_amount",identity,units);
p.hincrby("balances",identity,-units); p.hincrby("balances",account,-units);
p.hincrby("balances",whoid,units) p.hincrby("balances",who_account,units)
p.execute() p.execute()
link.send("%s has tipped %s %s" % (NickFromIdentity(identity), NickFromIdentity(whoid), AmountToString(units))) link.send("%s has tipped %s %s" % (NickFromIdentity(identity), NickFromIdentity(whoid), AmountToString(units)))
except Exception, e: except Exception, e:
@ -123,7 +125,8 @@ def Rain(link,cmd):
units = long(amount * coinspecs.atomic_units) units = long(amount * coinspecs.atomic_units)
try: try:
balance = redis_hget("balances",identity) account = GetAccount(identity)
balance = redis_hget("balances",account)
if balance == None: if balance == None:
balance = 0 balance = 0
balance=long(balance) balance=long(balance)
@ -131,11 +134,14 @@ def Rain(link,cmd):
link.send("You only have %s" % (AmountToString(balance))) link.send("You only have %s" % (AmountToString(balance)))
return return
userlist=[user.identity() for user in link.network.get_users(group.name)] userlist=link.network.get_users(group.name)
log_log("users in %s: %s" % (group.name,str(userlist))) log_log("users in %s: %s" % (group.name,str([user.identity() for user in userlist])))
userlist.remove(identity) userlist.remove(link)
for n in config.no_rain_to_nicks: for n in config.no_rain_to_nicks:
userlist.remove(IdentityFromString(link,n)) i=IdentityFromString(link,n)
l=Link(link.network,User(link.network,NickFromIdentity(i)),group)
if l in userlist:
userlist.remove(l)
if users == None or users > len(userlist): if users == None or users > len(userlist):
users = len(userlist) users = len(userlist)
everyone = True everyone = True
@ -148,10 +154,10 @@ def Rain(link,cmd):
link.send("This would mean not even an atomic unit per nick") link.send("This would mean not even an atomic unit per nick")
return return
log_info("%s wants to rain %s on %s users in %s" % (identity, AmountToString(units), users, group.name)) log_info("%s wants to rain %s on %s users in %s" % (identity, AmountToString(units), users, group.name))
log_log("eligible users in %s: %s" % (group.name, str(userlist))) log_log("eligible users in %s: %s" % (group.name, str([user.identity() for user in userlist])))
random.shuffle(userlist) random.shuffle(userlist)
userlist = userlist[0:users] userlist = userlist[0:users]
log_log("selected users in %s: %s" % (group.name, userlist)) log_log("selected users in %s: %s" % (group.name, [user.identity() for user in userlist]))
user_units = long(units / users) user_units = long(units / users)
enumerate_users = False enumerate_users = False
@ -163,13 +169,14 @@ def Rain(link,cmd):
msg = "%s rained %s on:" % (link.user.nick, AmountToString(user_units)) msg = "%s rained %s on:" % (link.user.nick, AmountToString(user_units))
enumerate_users = True enumerate_users = True
pipe = redis_pipeline() pipe = redis_pipeline()
pipe.hincrby("balances",identity,-units) pipe.hincrby("balances",account,-units)
pipe.incrby("rain_total_count",1) pipe.incrby("rain_total_count",1)
pipe.incrby("rain_total_amount",units) pipe.incrby("rain_total_amount",units)
pipe.hincrby("rain_count",identity,1) pipe.hincrby("rain_count",identity,1)
pipe.hincrby("rain_amount",identity,units) pipe.hincrby("rain_amount",identity,units)
for user in userlist: for user in userlist:
pipe.hincrby("balances",user,user_units) a = GetAccount(user)
pipe.hincrby("balances",a,user_units)
if enumerate_users: if enumerate_users:
msg = msg + " " + NickFromIdentity(user) msg = msg + " " + NickFromIdentity(user)
pipe.execute() pipe.execute()
@ -223,7 +230,8 @@ def RainActive(link,cmd):
units = long(amount * coinspecs.atomic_units) units = long(amount * coinspecs.atomic_units)
try: try:
balance = redis_hget("balances",identity) account = GetAccount(link)
balance = redis_hget("balances",account)
if balance == None: if balance == None:
balance = 0 balance = 0
balance=long(balance) balance=long(balance)
@ -232,17 +240,20 @@ def RainActive(link,cmd):
return return
now = time.time() now = time.time()
userlist = [user.identity() for user in link.network.get_active_users(seconds,group.name)] userlist = link.network.get_active_users(seconds,group.name)
log_log('userlist: %s' % str(userlist)) log_log('userlist: %s' % str([user.identity() for user in userlist]))
userlist.remove(link.identity()) userlist.remove(link)
for n in config.no_rain_to_nicks: for n in config.no_rain_to_nicks:
userlist.remove(IdentityFromString(link,n)) i=IdentityFromString(link,n)
l=Link(link.network,User(link.network,NickFromIdentity(i)),group)
if l in userlist:
userlist.remove(l)
weights=dict() weights=dict()
weight=0 weight=0
log_log('userlist to loop: %s' % str(userlist)) log_log('userlist to loop: %s' % str([user.identity() for user in userlist]))
for n in userlist: for n in userlist:
log_log('user to check: %s' % NickFromIdentity(n)) log_log('user to check: %s' % n.user.nick)
t = link.network.get_last_active_time(NickFromIdentity(n),group.name) t = link.network.get_last_active_time(n.user.nick,group.name)
if t == None: if t == None:
continue continue
dt = now - t dt = now - t
@ -256,7 +267,7 @@ def RainActive(link,cmd):
return return
pipe = redis_pipeline() pipe = redis_pipeline()
pipe.hincrby("balances",identity,-units) pipe.hincrby("balances",account,-units)
pipe.incrby("arain_total_count",1); pipe.incrby("arain_total_count",1);
pipe.incrby("arain_total_amount",units); pipe.incrby("arain_total_amount",units);
pipe.hincrby("arain_count",identity,1); pipe.hincrby("arain_count",identity,1);
@ -269,9 +280,10 @@ def RainActive(link,cmd):
user_units = long(units * weights[n] / weight) user_units = long(units * weights[n] / weight)
if user_units <= 0: if user_units <= 0:
continue continue
act = now - link.network.get_last_active_time(NickFromIdentity(n),link.group.name) act = now - link.network.get_last_active_time(n.user.nick,link.group.name)
log_info("%s rained %s on %s (last active %f hours ago)" % (identity, AmountToString(user_units),n,act/3600)) log_info("%s rained %s on %s (last active %f hours ago)" % (identity, AmountToString(user_units),n.identity(),act/3600))
pipe.hincrby("balances",n,user_units) a=GetAccount(n)
pipe.hincrby("balances",a,user_units)
rained_units += user_units rained_units += user_units
if not minu or user_units < minu: if not minu or user_units < minu:
minu = user_units minu = user_units

View File

@ -77,8 +77,9 @@ def Withdraw(link,cmd):
link.send("Sorry, withdrawal is disabled due to a wallet error which requires admin assistance") link.send("Sorry, withdrawal is disabled due to a wallet error which requires admin assistance")
return return
account = GetAccount(identity)
try: try:
balance = redis_hget("balances",identity) balance = redis_hget('accounts',account)
if balance == None: if balance == None:
balance = 0 balance = 0
balance=long(balance) balance=long(balance)
@ -133,7 +134,7 @@ def Withdraw(link,cmd):
link.send( "Tx sent: %s" % tx_hash) link.send( "Tx sent: %s" % tx_hash)
try: try:
redis_hincrby("balances",identity,-amount) redis_hincrby("balances",account,-amount)
except Exception, e: except Exception, e:
log_error('Withdraw: FAILED TO SUBTRACT BALANCE: exception: %s' % str(e)) log_error('Withdraw: FAILED TO SUBTRACT BALANCE: exception: %s' % str(e))
CheckDisableWithdraw() CheckDisableWithdraw()

View File

@ -19,6 +19,7 @@ from decimal import *
import tipbot.config as config import tipbot.config as config
import tipbot.coinspecs as coinspecs import tipbot.coinspecs as coinspecs
from tipbot.log import log_error, log_warn, log_info, log_log from tipbot.log import log_error, log_warn, log_info, log_log
from tipbot.link import Link
from tipbot.redisdb import * from tipbot.redisdb import *
registered_networks=dict() registered_networks=dict()
@ -284,10 +285,28 @@ def RetrieveTipbotBalance(force_refresh=False):
cached_tipbot_unlocked_balance=unlocked_balance cached_tipbot_unlocked_balance=unlocked_balance
return balance, unlocked_balance return balance, unlocked_balance
def GetAccount(link_or_identity):
if isinstance(link_or_identity,Link):
identity=link_or_identity.identity()
else:
identity=link_or_identity
account = redis_hget('accounts',identity)
if account == None:
log_info('No account found for %s, creating new one' % identity)
next_account_id = long(redis_get('next_account_id') or 0)
account = next_account_id
if redis_hexists('accounts',account):
raise RuntimeError('Next account ID already exists (%d)', account)
redis_hset('accounts',identity,account)
next_account_id += 1
redis_set('next_account_id',next_account_id)
return account
def RetrieveBalance(link): def RetrieveBalance(link):
try: try:
balance = redis_hget("balances",link.identity()) or 0 account = GetAccount(link)
confirming = redis_hget("confirming_payments",link.identity()) or 0 balance = redis_hget("balances",account) or 0
confirming = redis_hget("confirming_payments",account) or 0
return long(balance), long(confirming) return long(balance), long(confirming)
except Exception, e: except Exception, e:
log_error('RetrieveBalance: exception: %s' % str(e)) log_error('RetrieveBalance: exception: %s' % str(e))