Changeset 279

Show
Ignore:
Timestamp:
04/27/09 17:48:41 (3 years ago)
Author:
ocjhb
Message:

client can now buy coins

Location:
trunk/sandbox/jhb
Files:
4 added
5 modified
1 moved

Legend:

Unmodified
Added
Removed
  • trunk/sandbox/jhb/oc2/documentation.py

    r277 r279  
    11""" 
     2 
    23############################################################################### 
    34Setup an issuer 
  • trunk/sandbox/jhb/oc2/entity.py

    r258 r279  
    11import occrypto,container 
    2 from storage import Item 
    32 
    43class Entity(object): 
  • trunk/sandbox/jhb/oc2/storage.py

    r254 r279  
    1 import pickle,base64 
    2 class Item(object): 
    3      
    4     def dump(self,path): 
    5         return base64.b64encode(pickle.dumps(self)) 
     1import UserDict, cPickle 
     2class Storage(UserDict.UserDict): 
    63 
    7     def load(self,path): 
    8         return pickle.loads(base64.decode(open(path).read())) 
     4    def setFilename(self,filename): 
     5        self.filename = filename 
     6        return self 
     7 
     8    def save(self): 
     9        cPickle.dump(self.data,open(self.filename,'w')) 
     10        return self 
     11 
     12    def restore(self): 
     13        try: 
     14            self.data = cPickle.load(open(self.filename)) 
     15        except:             
     16            pass 
     17        return self 
     18 
  • trunk/sandbox/jhb/oc2/wallet.py

    r277 r279  
    5353        if not (denominations or keyids): 
    5454            raise "you need to ask at least for one" 
    55          
    5655        message = messages.FetchMintKeys() 
    57         message.denominations = denominations 
     56        message.denominations = [str(d) for d in denominations] 
    5857        message.keyids = keyids 
    5958         
    6059        response = transport(message) 
    61  
    6260        if response.header == 'MINTING_KEY_FAILURE': 
    6361            raise message 
     
    146144        return answer 
    147145 
     146 
     147    def getCurrency(self,id): 
     148        if self.storage.has_key(id): 
     149            return self.storage[id] 
     150        else: 
     151            currency = dict(cdds=[], 
     152                            blanks = {}, 
     153                            coins = [], 
     154                            transactions = {}) 
     155            self.storage[id]=currency 
     156            return currency 
     157 
     158    def listCurrencies(self): 
     159        out = [] 
     160        for key,currency in self.storage.items(): 
     161            cdd = currency['cdds'][-1] 
     162            amount = sum([int(coin.denomination) for coin in currency['coins']]) 
     163            out.append((cdd,amount)) 
     164        return out             
     165 
     166    def deleteCurrency(self,id): 
     167        del(self.storage[id]) 
     168 
     169 
     170    def tokenizeForBuying(self,amount,denominations): 
     171        denominations = [int(d) for d in denominations] 
     172        denominations.sort() 
     173        denominations.reverse() 
     174 
     175        out = [] 
     176        for d in denominations: 
     177            while amount and amount >= d: 
     178                out.append(d) 
     179                amount -= d 
     180        return out                 
     181 
     182         
     183 
     184#################################higher level############################# 
     185 
     186    def addCurrency(self,transport): 
     187        cdd = self.askLatestCDD(transport) 
     188        id = cdd.currencyId 
     189        currency = self.getCurrency(id) 
     190        if cdd.version not in [cdd.version for cdd in currency['cdds']]: 
     191            currency['cdds'].append(cdd) 
     192 
     193    def buyCoins(self,transport,amount,target): 
     194        cdd = self.askLatestCDD(transport) 
     195        currency = self.getCurrency(cdd.currencyId) 
     196        tokenized =  self.tokenizeForBuying(amount,cdd.denominations) #what coins do we need 
     197        wanted = list(set(tokenized)) #what mkcs do we want 
     198         
     199        keys = self.fetchMintKeys(transport,denominations=wanted) 
     200        mkcs = {} 
     201        for mkc in keys: 
     202            if not cdd.masterPubKey.verifyContainerSignature(mkc): 
     203                raise 'Invalid signature on mkc' 
     204            mkcs[mkc.denomination] = mkc 
     205         
     206        secrets = [] 
     207        data = [] 
     208        print tokenized 
     209        for denomination in tokenized: 
     210            mkc = mkcs[str(denomination)] 
     211            blank = self._makeBlank(cdd,mkc) 
     212            secret,blind = mkc.publicKey.blindBlank(blank) 
     213            secrets.append((blank,blind,mkc,secret)) 
     214            data.append((mkc.keyId,blind)) 
     215 
     216        tid = self.makeSerial()  
     217        response = self.requestTransfer(transport,tid,target,data,[])                  
     218        i = 0 
     219        signatures = response.signatures 
     220        for signature in signatures: 
     221            blank,blind,mkc,secret = secrets[i] 
     222            key = mkc.publicKey 
     223            blank.signature = key.unblind(secret,signature) 
     224            coin = blank 
     225            if not key.verifyContainerSignature(coin): 
     226                raise 'Invalid signature'  
     227            currency['coins'].append(coin) 
     228            i += 1 
     229            self.storage.save() 
  • trunk/sandbox/jhb/pys60/btsocket.py.jhb

    r278 r279  
    3030default_access_point = None 
    3131 
     32class AccessPoint(object): 
     33    def __init__(self,apid=None): 
     34        self.apid = apid 
     35 
     36    def start(self): 
     37        pass 
     38    def stop(self): 
     39        pass 
     40 
     41    def ip(self): 
     42        return 'fake ip' 
     43 
    3244def select_access_point(): 
    3345   """ 
     
    4557   This creates access point object by given apid. Returns access point object. 
    4658   """ 
    47    return repr(apid) 
     59   return AccessPoint(apid) 
    4860    
    4961def set_default_access_point(apo): 
  • trunk/sandbox/jhb/pys60/ocwallet.py

    r278 r279  
    33from key_codes import EKeyLeftArrow, EKeyRightArrow 
    44 
     5from oc2 import storage,wallet, transports 
    56 
    67class WalletClient: 
    78 
    8     def __init__(self,wallet): 
    9         self.wallet = wallet 
     9    def __init__(self,storage): 
     10        self.storage = storage 
     11        self.wallet = wallet.Wallet(storage) 
    1012        self.makeWalletMenu() 
    1113        self.displayWalletMenu()         
     
    1315                      (u'Receive',u'Receive coins',self.getReceiveDetails), 
    1416                      (u'Freshen up',u'Freshen up the coins',self.getFreshenUpDetails), 
    15                       (u'Buy',u'Buy new coins',self.getDetails), 
     17                      (u'Buy',u'Buy new coins',self.buyCoins), 
    1618                      (u'Sell',u'Sell coins',self.getDetails), 
    1719                      (u'Details',u'See what coins you hold',self.inspect),] 
    1820 
    19         self.methods=[(u'Internet',u'Use the net'), 
     21        self.methods=[(u'Internet',u'Use the internet'), 
    2022                      (u'Bluetooth',u'Mobile to mobile')] 
    2123         
    2224        self.todo = {} 
    23  
     25        self.apo = None 
    2426 
    2527    def makeWalletMenu(self): 
    26         self.wallet_list = [(u'12 hubtokens',u'the-hub.net'),(u'14 greenbucks',u'opencoin.org')] 
     28        self.wallet_list = [] 
     29        tmp = [(cdd.currencyId,cdd,amount) for cdd,amount in self.wallet.listCurrencies()] 
     30        tmp.sort() 
     31        self.currencies = [(t[1],t[2]) for t in tmp] 
     32 
     33        for cdd,amount in self.currencies: 
     34            title = u'%s %ss' % (amount,cdd.currencyId) 
     35            description = unicode(cdd.issuerServiceLocation) 
     36            self.wallet_list.append((title,description)) 
    2737        self.wallet_menu =  appuifw.Listbox(self.wallet_list,self.displayActionMenu) 
    2838        self.wallet_menu.bind(EKeyRightArrow,self.displayActionMenu) 
     
    3141        appuifw.app.body =  self.wallet_menu 
    3242        appuifw.app.title = u'opencoin - main\nchoose your currency' 
     43        appuifw.app.menu = [(u'add Currency',self.addCurrency), 
     44                            (u'delete Currency',self.delCurrency)] 
    3345 
    3446    def displayActionMenu(self): 
     
    4759        self.actions[current][2]() 
    4860 
     61 
     62    def getAmount(self): 
     63        amount = appuifw.query(u'Amount','number') 
     64        amount = int(amount) 
     65        self.todo['amount'] = amount 
     66        return amount 
     67 
     68    def getTarget(self): 
     69        target = '' 
     70        while target == '': 
     71            target = appuifw.query(u'Reference','text') 
     72        self.todo['target'] = target 
     73        return target             
     74 
    4975    def getDetails(self): 
    50         amount = appuifw.query(u'amount','number') 
    51         self.todo['amount'] = amount 
     76         
     77        amount = self.getAmount() 
     78        if not amount: 
     79            return 
    5280 
    53         target = appuifw.query(u'subject','text') 
    54         self.todo['target'] = target 
     81        target = self.getTarget() 
     82        if not target: 
     83            return 
    5584 
    5685        method = self.getMethod() 
     
    80109        #print 'inspect' 
    81110        pass 
     111 
     112 
     113    def addCurrency(self): 
     114        url = appuifw.query(u'url','text',u'http://localhost:9090') 
     115        self.todo['url'] = url 
     116        transport = self.getHTTPTransport(url)  
     117        self.wallet.addCurrency(transport) 
     118        self.makeWalletMenu() 
     119        self.displayWalletMenu() 
     120 
     121 
     122    def getCurrentCurrency(self): 
     123        return self.currencies[self.wallet_menu.current()] 
     124 
     125    def delCurrency(self): 
     126        cdd,amount = self.getCurrentCurrency() 
     127        id = cdd.currencyId 
     128        result = appuifw.query(u'Delete %s %ss?' % (amount,id),'query') 
     129        if result: 
     130            self.wallet.deleteCurrency(id) 
     131        self.makeWalletMenu() 
     132        self.displayWalletMenu() 
     133 
     134    def buyCoins(self): 
     135        amount = self.getAmount() 
     136        if not amount: 
     137            return 
    82138         
     139        target = self.getTarget() 
     140        if not target: 
     141            return 
     142 
     143        cdd,alreadythere = self.getCurrentCurrency() 
     144        url = cdd.issuerServiceLocation 
     145 
     146        transport = transports.HTTPTransport(url) 
     147        self.wallet.buyCoins(transport,amount,target) 
     148        self.makeWalletMenu() 
     149        self.displayWalletMenu() 
     150 
    83151    def execute(self): 
    84152        #print 'execute' 
    85153        print self.todo 
    86154 
     155 
     156    def getHTTPTransport(self,url): 
     157        self.startInternet() 
     158        transport = transports.HTTPTransport(url) 
     159        return transport 
     160 
     161    def startInternet(self): 
     162        if not self.apo: 
     163            import sys 
     164            try: 
     165                sys.modules['socket'] = __import__('btsocket') 
     166                import socket 
     167                apid = socket.select_access_point() 
     168                apo = socket.access_point(apid) 
     169                socket.set_default_access_point(apo) 
     170                apo.start() 
     171                self.apo = apo 
     172                self.ip = apo.ip() 
     173 
     174            except ImportError: 
     175                import socket 
     176             
     177 
     178    def stopInternet(self): 
     179        if self.apo: 
     180            self.apo.stop() 
     181            self.apo = None 
     182 
     183 
     184 
     185     
     186 
    87187#appuifw.app.screen='full' 
    88188app_lock = e32.Ao_lock() 
    89 w = WalletClient({}) 
     189storage = storage.Storage() 
     190storage.setFilename('data/wallet.bin') 
     191storage.restore() 
     192 
     193w = WalletClient(storage) 
    90194appuifw.app.screen='normal' 
    91195appuifw.app.exit_key_handler = app_lock.signal 
    92196import time 
    93197app_lock.wait() 
     198storage.save() 
    94199print 'fini'