Skip to content

Commit 910a6cb

Browse files
authored
refactor: class based network module (#162)
1 parent 2b91995 commit 910a6cb

12 files changed

Lines changed: 104 additions & 97 deletions

File tree

crypto/configuration/network.py

Lines changed: 18 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,26 @@
1-
from datetime import datetime
2-
from typing import Type, TypedDict, Union
3-
from crypto.networks.mainnet import Mainnet
1+
from crypto.networks.abstract_network import AbstractNetwork
42
from crypto.networks.testnet import Testnet
53

6-
class NetworkType(TypedDict):
7-
epoch: datetime
8-
wif: str
9-
chain_id: int
4+
class Network:
5+
_network: AbstractNetwork
106

11-
network: NetworkType = {
12-
'epoch': Testnet.epoch,
13-
'wif': Testnet.wif,
14-
'chain_id': Testnet.chain_id,
15-
}
7+
@classmethod
8+
def set_network(cls, network: AbstractNetwork) -> None:
9+
"""Set what network you want to use in the crypto library
1610
17-
def set_network(network_object: Union[Type[Mainnet], Type[Testnet]]) -> None:
18-
"""Set what network you want to use in the crypto library
11+
Args:
12+
network_object: Testnet, Devnet, Mainnet
13+
"""
1914

20-
Args:
21-
network_object: Testnet, Devnet, Mainnet
22-
"""
23-
global network
15+
cls._network = network
2416

25-
network = {
26-
'epoch': network_object.epoch,
27-
'wif': network_object.wif,
28-
'chain_id': network_object.chain_id,
29-
}
17+
@classmethod
18+
def get_network(cls) -> AbstractNetwork:
19+
"""Get settings for a selected network
3020
31-
def get_network() -> NetworkType:
32-
"""Get settings for a selected network, default network is devnet
21+
Returns:
22+
AbstractNetwork: network settings (default network is testnet)
23+
"""
24+
return cls._network
3325

34-
Returns:
35-
dict: network settings (default network is devnet)
36-
"""
37-
return network
38-
39-
def set_custom_network(epoch: datetime, wif: str, chain_id: int) -> None:
40-
"""Set custom network
41-
42-
Args:
43-
epoch (datetime): chains epoch time
44-
wif (str): chains wif
45-
chain_id (int): chain id
46-
"""
47-
global network
48-
49-
network = {
50-
'epoch': epoch,
51-
'wif': wif,
52-
'chain_id': chain_id
53-
}
26+
Network.set_network(Testnet())

crypto/identity/private_key.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from Cryptodome.Hash import keccak
55
from base58 import b58decode
66

7-
from crypto.configuration.network import get_network
7+
from crypto.configuration.network import Network
88
from crypto.enums.constants import Constants
99

1010
class PrivateKey(object):
@@ -76,7 +76,7 @@ def from_wif(cls, wif: str):
7676
wif = b58decode(wif).hex()
7777

7878
version = wif[0:2]
79-
if version != get_network()['wif']:
79+
if version != Network.get_network().wif():
8080
raise ValueError(f"Invalid network version: {version}")
8181

8282
private_key = wif[2:66]

crypto/identity/wif.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from binary.unsigned_integer.writer import write_bit8
77

8-
from crypto.configuration.network import get_network
8+
from crypto.configuration.network import Network
99

1010
def wif_from_passphrase(passphrase: str, network_wif: Optional[str] = None):
1111
"""Get wif from passphrase
@@ -18,9 +18,9 @@ def wif_from_passphrase(passphrase: str, network_wif: Optional[str] = None):
1818
string: wif
1919
"""
2020
if not network_wif:
21-
network = get_network()
21+
network = Network.get_network()
2222

23-
network_wif = network['wif']
23+
network_wif = network.wif()
2424

2525
private_key = hashlib.sha256(passphrase.encode())
2626
seed = write_bit8(int(network_wif, 16)) + private_key.digest() + write_bit8(0x01)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from abc import ABC, abstractmethod
2+
3+
class AbstractNetwork(ABC):
4+
@abstractmethod
5+
def chain_id(self) -> int:
6+
"""Return the chain ID of the network."""
7+
8+
@abstractmethod
9+
def epoch(self) -> str:
10+
"""Return the epoch time of the network."""
11+
12+
@abstractmethod
13+
def wif(self) -> str:
14+
"""Return the WIF (Wallet Import Format) of the network."""

crypto/networks/mainnet.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1-
from datetime import datetime
1+
from crypto.networks.abstract_network import AbstractNetwork
22

3-
class Mainnet(object):
4-
epoch = datetime(2017, 3, 21, 13, 00, 00)
5-
wif = 'ba'
6-
chain_id = 10000
3+
class Mainnet(AbstractNetwork):
4+
def chain_id(self):
5+
return 10000
6+
7+
def epoch(self):
8+
return '2017-03-21T13:00:00.000Z'
9+
10+
def wif(self):
11+
return 'ba'

crypto/networks/testnet.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1-
from datetime import datetime
1+
from crypto.networks.abstract_network import AbstractNetwork
22

3-
class Testnet(object):
4-
epoch = datetime(2017, 3, 21, 13, 00, 00)
5-
wif = 'ba'
6-
chain_id = 10000
3+
class Testnet(AbstractNetwork):
4+
def chain_id(self):
5+
return 10000
6+
7+
def epoch(self):
8+
return '2017-03-21T13:00:00.000Z'
9+
10+
def wif(self):
11+
return 'ba'

crypto/transactions/builder/base.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
from typing import Optional
2-
from crypto.configuration.network import get_network
1+
from crypto.configuration.network import Network
32
from crypto.identity.private_key import PrivateKey
43
from crypto.transactions.types.abstract_transaction import AbstractTransaction
54

@@ -11,7 +10,7 @@ def __init__(self, data: dict):
1110
'senderPublicKey': '',
1211
'gasPrice': '5',
1312
'nonce': '1',
14-
'network': get_network()['chain_id'],
13+
'network': Network.get_network().chain_id(),
1514
'gasLimit': 1_000_000,
1615
'data': '',
1716

crypto/transactions/types/abstract_transaction.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
import json
22
from typing import Optional
33

4-
from crypto.configuration.network import get_network
54
from crypto.enums.constants import Constants
65
from crypto.enums.contract_abi_type import ContractAbiType
76
from crypto.identity.address import address_from_public_key
87
from crypto.identity.private_key import PrivateKey
98
from crypto.utils.transaction_utils import TransactionUtils
109
from coincurve import PublicKey
11-
from crypto.utils.abi_decoder import AbiDecoder
1210

1311
class AbstractTransaction:
1412
def __init__(self, data: dict):

crypto/utils/slot.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
1-
from datetime import datetime
1+
from datetime import datetime, timezone
22

3-
from crypto.configuration.network import get_network
3+
from crypto.configuration.network import Network
44

55

6-
def get_time():
6+
def get_time() -> int:
77
"""Get the time difference between now and network start.
88
99
Returns:
1010
int: difference in seconds
1111
"""
12-
now = datetime.utcnow()
13-
network = get_network()
14-
seconds = int((now - network['epoch']).total_seconds())
12+
now = datetime.now(timezone.utc)
13+
14+
seconds = int((now - get_epoch()).total_seconds())
15+
1516
return seconds
1617

1718

1819
def get_epoch():
19-
network = get_network()
20-
return network['epoch']
20+
epoch_str = Network.get_network().epoch()
21+
if epoch_str.endswith("Z"):
22+
epoch_str = epoch_str[:-1] + "+00:00"
23+
24+
return datetime.fromisoformat(epoch_str)
Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,44 @@
11
from datetime import datetime
22

3-
from crypto.configuration.network import get_network, set_custom_network, set_network
3+
from crypto.configuration.network import Network
4+
from crypto.networks.abstract_network import AbstractNetwork
45
from crypto.networks.testnet import Testnet
56
from crypto.networks.mainnet import Mainnet
67

8+
class CustomNetwork(AbstractNetwork):
9+
def epoch(self):
10+
return "2024-01-01T13:00:00.000Z"
11+
12+
def wif(self):
13+
return "82"
14+
15+
def chain_id(self):
16+
return 20000
717

818
def test_get_network():
9-
result = get_network()
10-
assert result['chain_id'] == 10000
19+
result = Network.get_network()
20+
assert result.chain_id() == 10000
1121

1222
def test_set_network():
1323
# mainnet
14-
set_network(Mainnet)
15-
result = get_network()
16-
assert result['wif'] == 'ba'
17-
assert result['chain_id'] == 10000
24+
Network.set_network(Mainnet())
25+
result = Network.get_network()
26+
assert result.wif() == 'ba'
27+
assert result.chain_id() == 10000
1828

1929
# testnet
20-
set_network(Testnet)
21-
result = get_network()
22-
assert result['wif'] == 'ba'
23-
assert result['chain_id'] == 10000
30+
Network.set_network(Testnet())
31+
result = Network.get_network()
32+
assert result.wif() == 'ba'
33+
assert result.chain_id() == 10000
2434

25-
set_network(Testnet) # set back to Testnet so other tests don't fail
35+
Network.set_network(Testnet()) # set back to Testnet so other tests don't fail
2636

2737
def test_set_custom_network():
28-
epoch_time = datetime(2017, 1, 1, 13, 00, 00)
29-
set_custom_network(epoch_time, '82', 10000)
30-
result = get_network()
31-
assert result['wif'] == '82'
32-
assert result['epoch'] == epoch_time
33-
assert result['chain_id'] == 10000
34-
35-
set_network(Testnet) # set back to Testnet so other tests don't fail
38+
Network.set_network(CustomNetwork())
39+
result = Network.get_network()
40+
assert result.wif() == '82'
41+
assert result.epoch() == "2024-01-01T13:00:00.000Z"
42+
assert result.chain_id() == 20000
43+
44+
Network.set_network(Testnet()) # set back to Testnet so other tests don't fail

0 commit comments

Comments
 (0)