Skip to content

Commit 1eb1f98

Browse files
author
Caner Candan
committed
Merge branch 'master' of github.com:canercandan/ucoin-python-api
2 parents 3d3893d + b47db73 commit 1eb1f98

File tree

5 files changed

+322
-174
lines changed

5 files changed

+322
-174
lines changed

__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -177,9 +177,9 @@ def requests_post(self, path, **kwargs):
177177

178178
return response
179179

180-
def merkle_easy_parser(self, path):
180+
def merkle_easy_parser(self, path, begin=None, end=None):
181181
root = self.requests_get(path, leaves='true').json()
182-
for leaf in root['leaves']:
182+
for leaf in root['leaves'][begin:end]:
183183
yield self.requests_get(path, leaf=leaf).json()['leaf']
184184

185185
from . import pks, ucg, hdc, wrappers

hdc/transactions/__init__.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -71,34 +71,42 @@ def __get__(self, **kwargs):
7171
class Sender(Base):
7272
"""GET all the transactions sent by this sender and stored by this node (should contain all transactions of the sender)."""
7373

74-
def __init__(self, pgp_fingerprint):
74+
def __init__(self, pgp_fingerprint, begin=None, end=None):
7575
"""
7676
Arguments:
7777
- `pgp_fingerprint`: PGP fingerprint of the key we want to see sent transactions.
78+
- `begin`: integer value used by the merkle parser to know when to begin requesting.
79+
- `end`: integer value used by the merkle parser to know when to end requesting.
7880
"""
7981

8082
super().__init__()
8183

8284
self.pgp_fingerprint = pgp_fingerprint
85+
self.begin = begin
86+
self.end = end
8387

8488
def __get__(self, **kwargs):
85-
return self.merkle_easy_parser('/sender/%s' % self.pgp_fingerprint)
89+
return self.merkle_easy_parser('/sender/%s' % self.pgp_fingerprint, begin=self.begin, end=self.end)
8690

8791
class Recipient(Base):
8892
"""GET all the transactions received for this recipient stored by this node."""
8993

90-
def __init__(self, pgp_fingerprint):
94+
def __init__(self, pgp_fingerprint, begin=None, end=None):
9195
"""
9296
Arguments:
9397
- `pgp_fingerprint`: PGP fingerprint of the key we want to see sent transactions.
98+
- `begin`: integer value used by the merkle parser to know when to begin requesting.
99+
- `end`: integer value used by the merkle parser to know when to end requesting.
94100
"""
95101

96102
super().__init__()
97103

98104
self.pgp_fingerprint = pgp_fingerprint
105+
self.begin = begin
106+
self.end = end
99107

100108
def __get__(self, **kwargs):
101-
return self.merkle_easy_parser('/recipient/%s' % self.pgp_fingerprint)
109+
return self.merkle_easy_parser('/recipient/%s' % self.pgp_fingerprint, begin=self.begin, end=self.end)
102110

103111
class View(Base):
104112
"""GET the transaction of given TRANSACTION_ID."""

wrappers/__init__.py

+2-168
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
# Caner Candan <[email protected]>, http://caner.candan.fr
1818
#
1919

20-
import hashlib, logging
20+
import logging
2121
from .. import pks, ucg, hdc, settings
2222

2323
logger = logging.getLogger("wrappers")
@@ -26,170 +26,4 @@ class Wrapper:
2626
def __call__(self):
2727
pass
2828

29-
class Transaction(Wrapper):
30-
def __init__(self, type, pgp_fingerprint, message=''):
31-
self.pgp_fingerprint = pgp_fingerprint
32-
self.message = message
33-
self.type = type
34-
35-
def __call__(self):
36-
try:
37-
last_tx = hdc.transactions.sender.Last(self.pgp_fingerprint).get()
38-
except ValueError:
39-
last_tx = None
40-
41-
context_data = {}
42-
context_data.update(settings)
43-
context_data['version'] = 1
44-
context_data['number'] = 0 if not last_tx else last_tx['transaction']['number']+1
45-
context_data['previousHash'] = hashlib.sha1(("%(raw)s%(signature)s" % last_tx).encode('ascii')).hexdigest().upper() if last_tx else None
46-
context_data['message'] = self.message
47-
context_data['type'] = self.type
48-
context_data.update(self.get_context_data())
49-
50-
tx = """\
51-
Version: %(version)d
52-
Currency: %(currency)s
53-
Sender: %(fingerprint)s
54-
Number: %(number)d
55-
""" % context_data
56-
57-
if last_tx: tx += "PreviousHash: %(previousHash)s\n" % context_data
58-
59-
tx += self.get_message(context_data)
60-
61-
tx += """\
62-
Comment:
63-
%(message)s
64-
""" % context_data
65-
66-
tx = tx.replace("\n", "\r\n")
67-
txs = settings['gpg'].sign(tx, detach=True)
68-
69-
return self.process(tx, txs)
70-
71-
def get_context_data(self):
72-
return {}
73-
74-
def get_message(self, context_data, tx=''):
75-
return tx
76-
77-
def process(self, tx, txs):
78-
try:
79-
hdc.transactions.Process().post(transaction=tx, signature=txs)
80-
except ValueError as e:
81-
print(e)
82-
else:
83-
return True
84-
85-
return False
86-
87-
class Transfer(Transaction):
88-
def __init__(self, pgp_fingerprint, recipient, coins, message=''):
89-
super().__init__('TRANSFER', pgp_fingerprint, message)
90-
self.recipient = recipient
91-
self.coins = coins
92-
93-
def get_message(self, context_data, tx=''):
94-
context_data['recipient'] = self.recipient
95-
96-
tx += """\
97-
Recipient: %(recipient)s
98-
Type: %(type)s
99-
Coins:
100-
""" % context_data
101-
102-
for coin in self.coins.split(','):
103-
data = coin.split(':')
104-
issuer = data[0]
105-
for number in data[1:]:
106-
context_data.update(hdc.coins.View(issuer, int(number)).get())
107-
tx += '%(id)s, %(transaction)s\n' % context_data
108-
109-
return tx
110-
111-
class Issue(Transaction):
112-
def __init__(self, pgp_fingerprint, amendment, coins, message=''):
113-
super().__init__('ISSUANCE', pgp_fingerprint, message)
114-
self.amendment = amendment
115-
self.coins = coins
116-
117-
def get_next_coin_number(self, coins):
118-
number = 0
119-
for c in coins:
120-
candidate = int(c['id'].split('-')[1])
121-
if candidate > number: number = candidate
122-
return number+1
123-
124-
def get_message(self, context_data, tx=''):
125-
context_data['amendment'] = self.amendment
126-
127-
tx += """\
128-
Recipient: %(fingerprint)s
129-
Type: %(type)s
130-
Coins:
131-
""" % context_data
132-
133-
try:
134-
last_issuance = hdc.transactions.sender.issuance.Last(self.pgp_fingerprint).get()
135-
except ValueError:
136-
last_issuance = None
137-
138-
previous_idx = 0 if not last_issuance else self.get_next_coin_number(last_issuance['transaction']['coins'])
139-
140-
for idx, coin in enumerate(self.coins):
141-
context_data['idx'] = idx+previous_idx
142-
context_data['base'], context_data['power'] = [int(x) for x in coin.split(',')]
143-
tx += '%(fingerprint)s-%(idx)d-%(base)d-%(power)d-A-%(amendment)d\n' % context_data
144-
145-
return tx
146-
147-
class CoinsWrapper(Wrapper):
148-
def __init__(self, pgp_fingerprint):
149-
self.pgp_fingerprint = pgp_fingerprint
150-
151-
class CoinsGet(CoinsWrapper):
152-
def __init__(self, pgp_fingerprint, values):
153-
super().__init__(pgp_fingerprint)
154-
self.values = values
155-
156-
def __call__(self):
157-
__list = hdc.coins.List(self.pgp_fingerprint).get()
158-
coins = {}
159-
for c in __list['coins']:
160-
for id in c['ids']:
161-
n,b,p,t,i = id.split('-')
162-
amount = int(b) * 10**int(p)
163-
coins[amount] = {'issuer': c['issuer'], 'number': int(n), 'base': int(b), 'power': int(p), 'type': t, 'type_number': int(i), 'amount': amount}
164-
165-
issuers = {}
166-
for v in self.values:
167-
if v in coins:
168-
c = coins[v]
169-
issuers[c['issuer']] = issuers.get(c['issuer']) or []
170-
issuers[c['issuer']].append(c)
171-
else:
172-
raise ValueError('You do not have enough coins of value (%d)' % v)
173-
174-
res = ''
175-
for i, issuer in enumerate(issuers):
176-
if i > 0: res += ','
177-
res += issuer
178-
for c in issuers[issuer]:
179-
res += ':%(number)d' % c
180-
181-
return res
182-
183-
class CoinsList(CoinsWrapper):
184-
def __call__(self):
185-
__list = hdc.coins.List(self.pgp_fingerprint).get()
186-
coins = []
187-
__sum = 0
188-
for c in __list['coins']:
189-
for id in c['ids']:
190-
n,b,p,t,i = id.split('-')
191-
amount = int(b) * 10**int(p)
192-
__dict = {'issuer': c['issuer'], 'number': int(n), 'base': int(b), 'power': int(p), 'type': t, 'type_number': int(i), 'amount': amount}
193-
coins.append(__dict)
194-
__sum += amount
195-
return __sum, coins
29+
from . import transactions, coins

wrappers/coins.py

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#!/usr/bin/env python3
2+
#
3+
# This program is free software: you can redistribute it and/or modify
4+
# it under the terms of the GNU General Public License as published by
5+
# the Free Software Foundation, either version 3 of the License, or
6+
# (at your option) any later version.
7+
#
8+
# This program is distributed in the hope that it will be useful,
9+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11+
# GNU General Public License for more details.
12+
#
13+
# You should have received a copy of the GNU General Public License
14+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
15+
#
16+
# Authors:
17+
# Caner Candan <[email protected]>, http://caner.candan.fr
18+
#
19+
20+
import logging
21+
from . import Wrapper, pks, ucg, hdc, settings
22+
23+
logger = logging.getLogger("coins")
24+
25+
class Coins(Wrapper):
26+
def __init__(self, pgp_fingerprint):
27+
self.pgp_fingerprint = pgp_fingerprint
28+
29+
class Get(Coins):
30+
def __init__(self, pgp_fingerprint, values):
31+
super().__init__(pgp_fingerprint)
32+
self.values = values
33+
34+
def __call__(self):
35+
__list = hdc.coins.List(self.pgp_fingerprint).get()
36+
coins = {}
37+
for c in __list['coins']:
38+
for id in c['ids']:
39+
n,b,p,t,i = id.split('-')
40+
amount = int(b) * 10**int(p)
41+
if amount not in coins: coins[amount] = []
42+
coins[amount].append({'issuer': c['issuer'], 'number': int(n), 'base': int(b), 'power': int(p), 'type': t, 'type_number': int(i), 'amount': amount})
43+
44+
issuers = {}
45+
for v in self.values:
46+
if v in coins and coins[v]:
47+
c = coins[v].pop()
48+
issuers[c['issuer']] = issuers.get(c['issuer']) or []
49+
issuers[c['issuer']].append(c)
50+
else:
51+
raise ValueError('You do not have enough coins of value (%d)' % v)
52+
53+
res = ''
54+
for i, issuer in enumerate(issuers):
55+
if i > 0: res += ','
56+
res += issuer
57+
for c in issuers[issuer]:
58+
res += ':%(number)d' % c
59+
60+
return res
61+
62+
class List(Coins):
63+
def __init__(self, pgp_fingerprint, limit=None):
64+
super().__init__(pgp_fingerprint)
65+
self.limit = limit
66+
67+
def __call__(self):
68+
__list = hdc.coins.List(self.pgp_fingerprint).get()
69+
coins = []
70+
__sum = 0
71+
72+
for c in __list['coins']:
73+
for id in c['ids']:
74+
n,b,p,t,i = id.split('-')
75+
amount = int(b) * 10**int(p)
76+
__dict = {'issuer': c['issuer'], 'number': int(n), 'base': int(b), 'power': int(p), 'type': t, 'type_number': int(i), 'amount': amount}
77+
78+
if not self.limit or self.limit >= amount:
79+
coins.append(__dict)
80+
__sum += amount
81+
82+
return __sum, coins

0 commit comments

Comments
 (0)