Skip to content

Commit d7ec9c5

Browse files
committed
global update address and private_key
1 parent 587de31 commit d7ec9c5

File tree

4 files changed

+126
-60
lines changed

4 files changed

+126
-60
lines changed

tronapi/account.py

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,56 @@
66
from ecdsa import SECP256k1, SigningKey
77
from eth_keys import KeyAPI
88

9-
address_prefix = "41"
10-
public_prefix = "04"
9+
from tronapi import utils
1110

1211

1312
class Address(dict):
1413
def __init__(self, **kwargs):
1514
super().__init__(**kwargs)
1615

17-
self.hex = kwargs.get('hex')
18-
self.base58 = kwargs.get('base58')
16+
self.hex = str(kwargs.get('hex'))
17+
self.base58 = str(kwargs.get('base58'))
1918

2019
def __str__(self):
2120
return self.hex
2221

2322

23+
class Account(object):
24+
25+
def __init__(self):
26+
pass
27+
28+
@staticmethod
29+
def from_hex(address):
30+
"""Helper function that will convert a generic value from hex
31+
32+
Args:
33+
address (str): address
34+
35+
"""
36+
if not utils.is_hex(address):
37+
return address
38+
39+
return base58.b58encode_check(bytes.fromhex(address))
40+
41+
@staticmethod
42+
def to_hex(address):
43+
"""Helper function that will convert a generic value to hex
44+
45+
Args:
46+
address (str): address
47+
48+
"""
49+
if utils.is_hex(address):
50+
return address.lower().replace('0x', '41', 2)
51+
52+
return base58.b58decode_check(address).hex().upper()
53+
54+
@staticmethod
55+
def from_private_key(private_key):
56+
return PrivateKey(private_key).address.hex
57+
58+
2459
class GenerateAccount(object):
2560

2661
def __init__(self):
@@ -33,7 +68,7 @@ def public_key(self, is_hex=True):
3368
public_key = self._private.get_verifying_key().to_string()
3469

3570
if is_hex:
36-
return public_prefix + public_key.hex()
71+
return '04' + public_key.hex()
3772

3873
return public_key
3974

@@ -42,11 +77,14 @@ def address(self):
4277
keccak = sha3.keccak_256()
4378
keccak.update(self.public_key(False))
4479
address = keccak.hexdigest()[24:]
45-
address = address_prefix + address
80+
address = '41' + address
4681
to_base58 = base58.b58encode_check(bytes.fromhex(address))
4782

4883
return Address(base58=address, hex=to_base58.decode())
4984

85+
def __str__(self):
86+
return self.private_key().lower()
87+
5088

5189
class PrivateKey(object):
5290
def __init__(self, private_key):
@@ -70,13 +108,14 @@ def private_key(self):
70108
@property
71109
def public_key(self) -> str:
72110
public_key = self._key.public_key
73-
return public_prefix + str(public_key)[2:]
111+
return '04' + str(public_key)[2:]
74112

75113
@property
76114
def address(self):
77115
public_key = self._key.public_key
78-
address = address_prefix + public_key.to_address()[2:]
116+
address = '41' + public_key.to_address()[2:]
79117
to_base58 = base58.b58encode_check(bytes.fromhex(address))
118+
80119
return Address(base58=address, hex=to_base58.decode())
81120

82121
def __str__(self):

tronapi/contact.py

Whitespace-only changes.

tronapi/transactions.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ def send_trx(self, to, amount, account):
2626
if not isinstance(amount, float) or amount <= 0:
2727
raise InvalidTronError('Invalid amount provided')
2828

29-
_to = self.tron.to_hex(to)
30-
_from = self.tron.to_hex(account)
29+
_to = self.tron.address.to_hex(to)
30+
_from = self.tron.address.to_hex(account)
3131

3232
if _to == _from:
3333
raise TronError('Cannot transfer TRX to the same account')
@@ -63,8 +63,8 @@ def send_token(self, to, amount, token_id, account):
6363
if not self.tron.is_address(account):
6464
raise InvalidTronError('Invalid origin address provided')
6565

66-
_to = self.tron.to_hex(to)
67-
_from = self.tron.to_hex(account)
66+
_to = self.tron.address.to_hex(to)
67+
_from = self.tron.address.to_hex(account)
6868
_token_id = self.tron.from_utf8(token_id)
6969

7070
if _to == _from:
@@ -98,7 +98,7 @@ def update_account(self, account_name, account):
9898

9999
response = self.tron.full_node.request('/wallet/updateaccount', {
100100
'account_name': string_utf8_to_hex(account_name),
101-
'owner_address': self.tron.to_hex(account)
101+
'owner_address': self.tron.address.to_hex(account)
102102
}, 'post')
103103

104104
if 'Error' in response:

tronapi/tron.py

Lines changed: 74 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from Crypto.Hash import keccak
2929

3030
from tronapi import utils
31-
from tronapi.account import Address, GenerateAccount
31+
from tronapi.account import Address, GenerateAccount, Account, PrivateKey
3232
from tronapi.event import Event
3333
from tronapi.exceptions import InvalidTronError, TronError
3434
from tronapi.provider import HttpProvider
@@ -75,19 +75,55 @@ def __init__(self,
7575
self.__set_solidity_node(solidity_node)
7676

7777
self._default_block = None
78-
self.private_key = private_key
78+
self._private_key = private_key
7979
self.default_address = Address(base58=None, hex=None)
8080

8181
self.events = Event(self, event_server)
8282
self.transaction = TransactionBuilder(self)
8383

84+
def set_private_key(self, private_key) -> None:
85+
"""Set a private key used with the TronAPI instance,
86+
used for obtaining the address, signing transactions etc...
87+
88+
Args:
89+
private_key (str): Private key
90+
91+
Example:
92+
>>> tron.set_private_key('da146...f0d0')
93+
94+
Warning:
95+
Do not use this with any web/user facing TronAPI instances.
96+
This will leak the private key.
97+
98+
"""
99+
100+
try:
101+
check = PrivateKey(private_key).public_key
102+
except ValueError:
103+
raise TronError('Invalid private key provided')
104+
105+
self._private_key = str(private_key).lower()
106+
84107
def set_address(self, address):
108+
"""Sets the address used with all Tron API's. Will not sign any transactions.
109+
110+
Args:
111+
address (str) Tron Address
112+
113+
Example:
114+
>>> tron.set_address('TSkTw9Hd3oaJULL3er1UNfzASkunE9yA8f')
115+
"""
85116

86117
if not self.is_address(address):
87-
raise ValueError('Invalid address provided')
118+
raise InvalidTronError('Invalid address provided')
88119

89-
_hex = self.to_hex(address)
90-
_base58 = self.from_hex(address)
120+
_hex = self.address.to_hex(address)
121+
_base58 = self.address.from_hex(address)
122+
_private_base58 = self.address.from_private_key(self._private_key)
123+
124+
# check the addresses
125+
if self._private_key and _private_base58 != _base58:
126+
self._private_key = None
91127

92128
self.default_address = Address(hex=_hex, base58=_base58)
93129

@@ -117,6 +153,18 @@ def __set_solidity_node(self, provider) -> None:
117153
self.solidity_node = provider
118154
self.solidity_node.status_page = '/walletsolidity/getnowblock'
119155

156+
@property
157+
def address(self):
158+
"""Helper object that allows you to convert
159+
between hex/base58 and private key representations of a TRON address.
160+
161+
Note:
162+
If you wish to convert generic data to hexadecimal strings,
163+
please use the function tron.to_hex.
164+
165+
"""
166+
return Account()
167+
120168
@property
121169
def default_block(self):
122170
return self._default_block
@@ -263,7 +311,7 @@ def get_account_resource(self, address=None):
263311
raise InvalidTronError('Invalid address provided')
264312

265313
return self.full_node.request('/wallet/getaccountresource', {
266-
'address': self.to_hex(address)
314+
'address': self.address.to_hex(address)
267315
})
268316

269317
def get_account(self, address=None):
@@ -281,7 +329,7 @@ def get_account(self, address=None):
281329
raise InvalidTronError('Invalid address provided')
282330

283331
return self.solidity_node.request('/walletsolidity/getaccount', {
284-
'address': self.to_hex(address)
332+
'address': self.address.to_hex(address)
285333
}, 'post')
286334

287335
def get_balance(self, address=None, from_sun=False):
@@ -338,7 +386,9 @@ def get_transactions_related(self, address, direction='all', limit=30, offset=0)
338386
raise InvalidTronError('Invalid offset provided')
339387

340388
response = self.solidity_node.request('/walletextension/gettransactions{0}this'.format(direction), {
341-
'account': {'address': self.to_hex(address)},
389+
'account': {
390+
'address': self.address.to_hex(address)
391+
},
342392
'limit': limit,
343393
'offset': offset
344394
}, 'post')
@@ -417,7 +467,7 @@ def get_band_width(self, address=None):
417467
raise InvalidTronError('Invalid address provided')
418468

419469
return self.full_node.request('/wallet/getaccountnet', {
420-
'address': self.to_hex(address)
470+
'address': self.address.to_hex(address)
421471
}, 'post')
422472

423473
def get_transaction_count(self):
@@ -518,7 +568,7 @@ def sign(self, transaction, message=None):
518568
Signed Transaction contract data
519569
520570
"""
521-
if not self.private_key:
571+
if not self._private_key:
522572
raise TronError('Missing private key')
523573

524574
if 'signature' in transaction:
@@ -529,7 +579,7 @@ def sign(self, transaction, message=None):
529579

530580
return self.full_node.request('/wallet/gettransactionsign', {
531581
'transaction': transaction,
532-
'privateKey': self.private_key
582+
'privateKey': self._private_key
533583
}, 'post')
534584

535585
def broadcast(self, signed_transaction):
@@ -594,8 +644,8 @@ def register_account(self, address, new_account_address):
594644
595645
"""
596646
return self.full_node.request('/wallet/createaccount', {
597-
'owner_address': self.to_hex(address),
598-
'account_address': self.to_hex(new_account_address)
647+
'owner_address': self.address.to_hex(address),
648+
'account_address': self.address.to_hex(new_account_address)
599649
}, 'post')
600650

601651
@staticmethod
@@ -613,8 +663,9 @@ def apply_for_super_representative(self, address, url):
613663
url (str): official website address
614664
615665
"""
666+
616667
return self.full_node.request('/wallet/createwitness', {
617-
'owner_address': self.to_hex(address),
668+
'owner_address': self.address.to_hex(address),
618669
'url': self.string_utf8_to_hex(url)
619670
}, 'post')
620671

@@ -647,8 +698,10 @@ def get_tokens_issued_by_address(self, address):
647698
if not self.is_address(address):
648699
raise InvalidTronError('Invalid address provided')
649700

701+
address = self.address.to_hex(address)
702+
650703
return self.full_node.request('/wallet/getassetissuebyaccount', {
651-
'address': self.to_hex(address)
704+
'address': address
652705
}, 'post')
653706

654707
def get_token_from_id(self, token_id):
@@ -774,7 +827,7 @@ def get_contract(self, contract_address):
774827
if not self.is_address(contract_address):
775828
raise InvalidTronError('Invalid contract address provided')
776829

777-
contract_address = self.to_hex(contract_address)
830+
contract_address = self.address.to_hex(contract_address)
778831

779832
return self.full_node.request('/wallet/getcontract', {
780833
'value': contract_address
@@ -789,7 +842,7 @@ def validate_address(self, address, is_hex=False):
789842
790843
"""
791844
if is_hex:
792-
address = self.to_hex(address)
845+
address = self.address.to_hex(address)
793846

794847
return self.full_node.request('/wallet/validateaddress', {
795848
'address': address
@@ -874,7 +927,7 @@ def proposal_approve(self, owner_address, proposal_id, is_add_approval=True):
874927
raise InvalidTronError('Invalid proposalID provided')
875928

876929
return self.full_node.request('/wallet/proposalapprove', {
877-
'owner_address': self.to_hex(owner_address),
930+
'owner_address': self.address.to_hex(owner_address),
878931
'proposal_id': proposal_id,
879932
'is_add_approval': is_add_approval
880933
}, 'post')
@@ -897,7 +950,7 @@ def proposal_delete(self, owner_address, proposal_id):
897950
raise InvalidTronError('Invalid proposalID provided')
898951

899952
return self.full_node.request('/wallet/proposaldelete', {
900-
'owner_address': self.to_hex(owner_address),
953+
'owner_address': self.address.to_hex(owner_address),
901954
'proposal_id': proposal_id
902955
}, 'post')
903956

@@ -926,7 +979,7 @@ def exchange_transaction(self, owner_address, exchange_id,
926979
raise InvalidTronError('Invalid expected provided')
927980

928981
return self.full_node.request('/wallet/exchangetransaction', {
929-
'owner_address': self.to_hex(owner_address),
982+
'owner_address': self.address.to_hex(owner_address),
930983
'exchange_id': exchange_id,
931984
'token_id': token_id,
932985
'quant': quant,
@@ -970,7 +1023,7 @@ def exchange_create(self, owner_address, first_token_id, second_token_id,
9701023
raise InvalidTronError('Invalid amount provided')
9711024

9721025
return self.full_node.request('/wallet/exchangecreate', {
973-
'owner_address': self.to_hex(owner_address),
1026+
'owner_address': self.address.to_hex(owner_address),
9741027
'first_token_id': first_token_id,
9751028
'first_token_balance': first_token_balance,
9761029
'second_token_id': second_token_id,
@@ -1060,32 +1113,6 @@ def from_sun(amount):
10601113
"""
10611114
return abs(amount) / 1e6
10621115

1063-
@staticmethod
1064-
def to_hex(address):
1065-
"""Helper function that will convert a generic value to hex
1066-
1067-
Args:
1068-
address (str): address
1069-
1070-
"""
1071-
if utils.is_hex(address):
1072-
return address.lower().replace('0x', '41', 2)
1073-
1074-
return base58.b58decode_check(address).hex().upper()
1075-
1076-
@staticmethod
1077-
def from_hex(address):
1078-
"""Helper function that will convert a generic value from hex
1079-
1080-
Args:
1081-
address (str): address
1082-
1083-
"""
1084-
if not utils.is_hex(address):
1085-
return address
1086-
1087-
return base58.b58encode_check(bytes.fromhex(address))
1088-
10891116
@staticmethod
10901117
def sha3(string, prefix=False):
10911118
"""Helper function that will sha3 any value using keccak256

0 commit comments

Comments
 (0)