From 93317158cc4e16619d34b36e5eed6d9298aa940c Mon Sep 17 00:00:00 2001 From: Mohammad Ghiasi Date: Sat, 28 Aug 2021 14:00:50 +0430 Subject: [PATCH] - added convert functions to algosdk/util.py (`ipfscidv0_to_byte32` & `byte32_to_ipfscidv0`) - added `base58>=2.1.0` package to setup.py requirements - added tests to test/steps/steps.py --- algosdk/util.py | 35 +++++++++++++++++++++++++++++++++++ setup.py | 2 +- test/steps/steps.py | 12 ++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/algosdk/util.py b/algosdk/util.py index f8b349ac..614eb6e0 100644 --- a/algosdk/util.py +++ b/algosdk/util.py @@ -2,6 +2,8 @@ from . import encoding import decimal import base64 +import base58 +import binascii from nacl.signing import SigningKey, VerifyKey from nacl.exceptions import BadSignatureError from typing import Dict, Any @@ -32,6 +34,39 @@ def algos_to_microalgos(algos): """ return round(algos * constants.microalgos_to_algos_ratio) +def ipfscidv0_to_byte32(cid): + """ + Convert ipfscidv0 to 32 bytes hex string. + + Args: + cid (string): IPFS CID Version 0 + + Returns: + str: 32 Bytes long string + """ + """bytes32 is converted back into Ipfs hash format.""" + + decoded = base58.b58decode(cid) + sliced_decoded = decoded[2:] + return binascii.b2a_hex(sliced_decoded).decode("utf-8") + + +def byte32_to_ipfscidv0(hexstr): + """ + Convert 32 bytes hex string to ipfscidv0. + + Args: + hexstr (string): 32 Bytes long string + + Returns: + str: IPFS CID Version 0 + """ + + binary_str = binascii.a2b_hex(hexstr) + completed_binary_str = b'\x12 ' + binary_str + return base58.b58encode(completed_binary_str).decode("utf-8") + + def sign_bytes(to_sign, private_key): """ diff --git a/setup.py b/setup.py index d7e95771..e94ccd03 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ project_urls={ "Source": "https://github.com/algorand/py-algorand-sdk", }, - install_requires=["pynacl", "pycryptodomex>=3.6.0", "msgpack"], + install_requires=["pynacl", "pycryptodomex>=3.6.0", "msgpack", "base58>=2.1.0"], packages=setuptools.find_packages(), python_requires=">=3.5", package_data={"": ["data/langspec.json"]}, diff --git a/test/steps/steps.py b/test/steps/steps.py index f6878974..be887b46 100644 --- a/test/steps/steps.py +++ b/test/steps/steps.py @@ -626,6 +626,18 @@ def check_microalgos(context, microalgos): assert int(microalgos) == context.microalgos +@when("I convert {ipfscid} ipfscid to bytes32 hex string and back") +def convert_ipfscid(context, ipfscid): + context.ipfscid = util.byte32_to_ipfscidv0( + util.ipfscidv0_to_byte32(ipfscid) + ) + + +@then("it should still be the same ipfscid {ipfscid}") +def check_ipfscid(context, ipfscid): + assert ipfscid == context.ipfscid + + @then("I get transactions by address and round") def txns_by_addr_round(context): txns = context.acl.transactions_by_address(