Skip to content

Commit

Permalink
fixes after rewview
Browse files Browse the repository at this point in the history
  • Loading branch information
gabi-vuls committed Apr 16, 2024
1 parent 957d101 commit 66daa32
Showing 10 changed files with 86 additions and 99 deletions.
16 changes: 8 additions & 8 deletions testing-suite/staking-v4/README.md
Original file line number Diff line number Diff line change
@@ -6,21 +6,21 @@
## How to run:

### 1) Create a virtual env
### `python3 -m venv ./venv`
### `source ./venv/bin/activate`
`python3 -m venv ./venv`
`source ./venv/bin/activate`

### 2) Install all dependencies
### `pip3 install -r ./req.txt`
`pip3 install -r ./req.txt`

### 3) Export PythonPath
### `export PYTHONPATH=.`
`export PYTHONPATH=.`

### 4) Make sure [chain-simulator](https://github.com/multiversx/mx-chain-simulator-go) is:
- Running
- Running with a correct config (specific config can be found at the begging of every `/scenarios/_test.py`)
- If you run chain-simulator on different port, you can edit it in `/scenarios/config.py`
- Running with a correct config (specific config can be found at the begging of every `./scenarios/_test.py`)
- If you run chain-simulator on different port, you can edit it in `./scenarios/config.py`

### 5) RUN
### `pytest scenarios/` - to run all scenarios
### `pytest scenarios/_17.py` - to run a specific scenario
`pytest scenarios/` - to run all scenarios
`pytest scenarios/_17.py` - to run a specific scenario

21 changes: 11 additions & 10 deletions testing-suite/staking-v4/chain_commander.py
Original file line number Diff line number Diff line change
@@ -8,34 +8,35 @@



def SetEgldToAddress(egld_ammount, erd_address):
def setEgldToAddress(egld_ammount, erd_address):
details = {
'address': f'{erd_address}',
'balance': f'{egld_ammount}'
}

details_list = [details]
json_structure = json.dumps(details_list)
req = requests.post(DEFAULT_PROXY + "/simulator/set-state", data=json_structure)
response = requests.post(f"{DEFAULT_PROXY}/simulator/set-state", data=json_structure)
response.raise_for_status()

return req.text
return response.text


def addBlocks(nr_of_blocks):
req = requests.post(DEFAULT_PROXY + f"/simulator/generate-blocks/{nr_of_blocks}")
req = requests.post(f"{DEFAULT_PROXY}/simulator/generate-blocks/{nr_of_blocks}")
return req.text


def addBlocksUntilEpochReached(epoch_to_be_reached: int):
req = requests.post(DEFAULT_PROXY + f"/simulator/generate-blocks-until-epoch-reached/{str(epoch_to_be_reached)}")
req = requests.post(f"{DEFAULT_PROXY}/simulator/generate-blocks-until-epoch-reached/{str(epoch_to_be_reached)}")
return req.text


def addBlocksUntilTxSucceeded(tx_hash) -> str:
print("Checking: ", tx_hash)
counter = 0

while counter < MAX_NR_OF_BLOCKS_UNTIL_TX_SHOULD_BE_EXECUTED:
while counter < MAX_NUM_OF_BLOCKS_UNTIL_TX_SHOULD_BE_EXECUTED:
addBlocks(1)

time.sleep(WAIT_UNTIL_API_REQUEST_IN_SEC)
@@ -52,17 +53,17 @@ def is_chain_online() -> bool:
while not flag:
time.sleep(1)
try:
response = requests.get("http://localhost:8085/network/status/0")
response = requests.get(f"{DEFAULT_PROXY}/network/status/0")
print(response)
flag = True
except requests.exceptions.ConnectionError:
print("not jet")
print("Chain not started jet")

return flag


def force_reset_validator_statistics():
req = requests.post(DEFAULT_PROXY + f"/simulator/force-reset-validator-statistics")
req = requests.post(f"{DEFAULT_PROXY}/simulator/force-reset-validator-statistics")
print(req.text)

return req.text
@@ -75,7 +76,7 @@ def addKey(private_keys: list) -> str:
}

json_structure = json.dumps(post_body)
req = requests.post(DEFAULT_PROXY + f"/simulator/add-keys", data=json_structure)
req = requests.post(f"{DEFAULT_PROXY}/simulator/add-keys", data=json_structure)

return req.text

2 changes: 1 addition & 1 deletion testing-suite/staking-v4/config.py
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@


PROXY_PUBLIC_TESTNET = "https://testnet-gateway.multiversx.com"
PROXY_PUBLIC_DEVNET = "https://devnet-gateway.elrond.com"
PROXY_PUBLIC_DEVNET = "https://devnet-gateway.multiversx.com"
PROXY_CHAIN_SIMULATOR = "http://localhost:8085"

DEFAULT_PROXY = PROXY_CHAIN_SIMULATOR
4 changes: 2 additions & 2 deletions testing-suite/staking-v4/constants.py
Original file line number Diff line number Diff line change
@@ -8,10 +8,10 @@
WAIT_UNTIL_API_REQUEST_IN_SEC = 0.5

# chain
MAX_NR_OF_BLOCKS_UNTIL_TX_SHOULD_BE_EXECUTED = 8
MAX_NUM_OF_BLOCKS_UNTIL_TX_SHOULD_BE_EXECUTED = 8

# staking_v4
EPOCH_WITH_STAKING_V35 = 3
EPOCH_WITH_STAKING_V3_5 = 3
EPOCH_STAKING_QUEUE_BECOMES_AUCTION_LIST = 4
EPOCH_SHUFFLING_FROM_ELIGIBLE_TO_AUCTION_LIST = 5
EPOCH_STAKING_V4_FULLY_FUNCTIONAL = 6
19 changes: 11 additions & 8 deletions testing-suite/staking-v4/core/validatorKey.py
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@
from constants import *
from chain_commander import *


class ValidatorKey:
def __init__(self, path: Path) -> None:
self.path = path
@@ -40,16 +41,18 @@ def get_state(self) -> str:
# sometimes it needs a second until cache is resetting
time.sleep(1)

req = requests.get(DEFAULT_PROXY + "/validator/statistics")
response = req.text
response = requests.get(f"{DEFAULT_PROXY}/validator/statistics")
response.raise_for_status()
parsed = response.json()

if self.public_address() in response:
state = response.split(self.public_address())
state = state[1].split('"validatorStatus":')
state = state[1].split('"')
return state[1]
else:
general_data = parsed.get("data")
general_statistics = general_data.get("statistics")
key_data = general_statistics.get(self.public_address())
if key_data is None:
return "Key not present in validator/statistics"
else:
status = key_data.get("validatorStatus")
return status

# using getOwner vm-query
def belongs_to(self, address: str) -> bool:
13 changes: 7 additions & 6 deletions testing-suite/staking-v4/core/wallet.py
Original file line number Diff line number Diff line change
@@ -29,15 +29,16 @@ def public_address(self) -> str:
return address

def get_balance(self) -> int:
req = requests.get(DEFAULT_PROXY + f"/address/{self.public_address()}")
response = requests.get(f"{DEFAULT_PROXY}/address/{self.public_address()}/balance")
response.raise_for_status()
parsed = response.json()

balance = req.text
balance = balance.split('"balance":')
balance = balance[1].split(',')
balance = balance[0].replace('"', "")
general_data = parsed.get("data")
balance = general_data.get("balance")

return balance


def set_balance(self, egld_ammount):
details = {
'address': f'{self.public_address()}',
@@ -46,7 +47,7 @@ def set_balance(self, egld_ammount):

details_list = [details]
json_structure = json.dumps(details_list)
req = requests.post(DEFAULT_PROXY + "/simulator/set-state", data=json_structure)
req = requests.post(f"{DEFAULT_PROXY}/simulator/set-state", data=json_structure)

return req.text

102 changes: 42 additions & 60 deletions testing-suite/staking-v4/get_info.py
Original file line number Diff line number Diff line change
@@ -8,16 +8,6 @@
import time
from constants import *

def getBalance(address):
req = requests.get(DEFAULT_PROXY + f"/address/{address}")

balance = req.text
balance = balance.split('"balance":')
balance = balance[1].split(',')
balance = balance[0].replace('"', "")

return balance


def getPublicAddressFromPem(pem: Path) -> str:
f = open(pem)
@@ -34,44 +24,40 @@ def getPublicAddressFromPem(pem: Path) -> str:


def getStatusOfTx(tx_hash: str) -> str:
req = requests.get(DEFAULT_PROXY + f"/transaction/{tx_hash}/process-status")
response = requests.get(f"{DEFAULT_PROXY}/transaction/{tx_hash}/process-status")
response.raise_for_status()
parsed = response.json()

status = req.text

if "transaction not found" in status:
if "transaction not found" in response.text:
return "expired"

status = status.split('"status":')
status = status[1].split('"')

return status[1]
general_data = parsed.get("data")
status = general_data.get("status")
return status


def getDelegationContractAddressFromTx(tx_hash):
delegation_contract_address = ""
req = requests.get(DEFAULT_PROXY + f"/transaction/{tx_hash}?withResults=True")

response = req.text
response = response.split('"logs":')
response = response[1].split("identifier")
for element in response:
if "delegate" in element:
element = element.split('"topics":["')
element = element[1].split(",")
element = element[4].split('"')
for _ in element:
if len(_) > 3:
delegation_contract_address = _
response = requests.get(f"{DEFAULT_PROXY}/transaction/{tx_hash}?withResults=True")
response.raise_for_status()
parsed = response.json()

general_data = parsed.get("data")
transaction_data = general_data.get("transaction")
logs_data = transaction_data.get("logs")
events_data = logs_data.get("events")
first_set_of_events = events_data[0]
topics = first_set_of_events.get("topics")
delegation_contract_address = topics[1]

delegation_contract_address = base64ToHex(delegation_contract_address)
delegation_contract_address = Address.from_hex(delegation_contract_address, "erd").to_bech32()

return delegation_contract_address
return delegation_contract_address


def getBLSKeysStatus(owner_public_key_in_hex: list[str]):
key_status_pair = {}
key_status_temp_list = []

post_body = {
"scAddress": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqplllst77y4l",
@@ -80,20 +66,16 @@ def getBLSKeysStatus(owner_public_key_in_hex: list[str]):
}

json_structure = json.dumps(post_body)
req = requests.post(DEFAULT_PROXY + "/vm-values/query", data=json_structure)

# get returnData
response = req.text
response = requests.post(f"{DEFAULT_PROXY}/vm-values/query", data=json_structure)
response.raise_for_status()
parsed = response.json()

if '"returnData":null' in response:
if '"returnData":null' in response.text:
return None

response = response.split('"returnData":')
response = response[1].split('"returnCode"')
response = response[0].split('"')
for element in response:
if len(element) > 3:
key_status_temp_list.append(element)
general_data = parsed.get("data")
tx_response_data = general_data.get("data")
key_status_temp_list = tx_response_data.get("returnData")

# convert all elements from list to hex and add to final dict:
for i in range(0, len(key_status_temp_list), 2):
@@ -115,19 +97,18 @@ def getOwner(public_validator_key: list[str]) -> str:
}

json_structure = json.dumps(post_body)
req = requests.post(DEFAULT_PROXY + "/vm-values/query", data=json_structure)
response = requests.post(f"{DEFAULT_PROXY}/vm-values/query", data=json_structure)
response.raise_for_status()
parsed = response.json()

# get returnData
response = req.text

if '"returnMessage":"owner address is nil"' in response:
if '"returnMessage":"owner address is nil"' in response.text:
return "validatorKey not staked"

response = response.split('"returnData":')
response = response[1].split('returnCode')
response = response[0].split('"')
general_data = parsed.get("data")
tx_response_data = general_data.get("data")
address_list = tx_response_data.get("returnData")
address = address_list[0]

address = response[1]
address = base64ToHex(address)
address = Address.from_hex(address, "erd").to_bech32()

@@ -138,7 +119,7 @@ def checkIfErrorIsPresentInTx(error, tx_hash) -> bool:
flag = False
error_bytes = stringToBase64(error)

req = requests.get(DEFAULT_PROXY + f"/transaction/{tx_hash}?withResults=True")
req = requests.get(f"{DEFAULT_PROXY}/transaction/{tx_hash}?withResults=True")
response = req.text

if error_bytes.decode() in response:
@@ -159,13 +140,14 @@ def getTotalStaked(owner: str):
}

json_structure = json.dumps(post_body)
req = requests.post(DEFAULT_PROXY + "/vm-values/query", data=json_structure)
response = requests.post(f"{DEFAULT_PROXY}/vm-values/query", data=json_structure)
response.raise_for_status()
parsed = response.json()

response = req.text
response = response.split('"returnData":')
response = response[1].split('returnCode')
response = response[0].split('"')
general_data = parsed.get("data")
tx_response_data = general_data.get("data")
total_staked_list = tx_response_data.get("returnData")
total_staked = total_staked_list[0]

total_staked = response[1]
total_staked = base64ToString(total_staked)
return total_staked
2 changes: 1 addition & 1 deletion testing-suite/staking-v4/helpers.py
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
import string


def stringToHex(value):
def decimalToHex(value: int):
hex_value = f'{value:x}'
if len(hex_value) % 2 > 0:
hex_value = "0" + hex_value
2 changes: 1 addition & 1 deletion testing-suite/staking-v4/scenarios/_48.py
Original file line number Diff line number Diff line change
@@ -32,7 +32,7 @@ def chain_start():


def main():
print("Happy testing!")
print("Happy testing")


def test_48():
4 changes: 2 additions & 2 deletions testing-suite/staking-v4/staking.py
Original file line number Diff line number Diff line change
@@ -17,7 +17,7 @@ def stake(wallet: Wallet, validatorKeys: list[ValidatorKey]):

# nr of nodes staked
nr_of_nodes_staked = len(validatorKeys)
nr_of_nodes_staked = stringToHex(nr_of_nodes_staked)
nr_of_nodes_staked = decimalToHex(nr_of_nodes_staked)

# load needed data for stake transactions signatures
stake_signature_and_public_key = ''
@@ -60,7 +60,7 @@ def stake(wallet: Wallet, validatorKeys: list[ValidatorKey]):
def malicious_stake(wallet: Wallet, validatorKeys: list[ValidatorKey], AMOUNT_DEFICIT="0", TX_DATA_MANIPULATOR=False):
# nr of nodes staked
nr_of_nodes_staked = len(validatorKeys)
nr_of_nodes_staked = stringToHex(nr_of_nodes_staked)
nr_of_nodes_staked = decimalToHex(nr_of_nodes_staked)

# load needed data for stake transactions signatures
stake_signature_and_public_key = ''

0 comments on commit 66daa32

Please sign in to comment.