diff --git a/duniterpy/helpers/money.py b/duniterpy/helpers/money.py new file mode 100644 index 0000000000000000000000000000000000000000..b6dd171f9b2a5a8cf6af2577898646d10ce21f69 --- /dev/null +++ b/duniterpy/helpers/money.py @@ -0,0 +1,26 @@ +from typing import Union, Type, Any +from duniterpy.grammars.output import SIG, CSV, CLTV, XHX, ConditionType + + +def output_available( + condition: Type[ConditionType], comparison: Any, value: Union[str, int] +) -> bool: + """ + Check if output source is available + Currently only handle unique condition without composition + + operator.lt(a, b) is equivalent to a < b + operator.le(a, b) is equivalent to a <= b + operator.gt(a, b) is equivalent to a > b + operator.ge(a, b) is equivalent to a >= b + """ + if type(condition.left) == SIG: + return comparison(condition.left.pubkey, value) + if type(condition.left) == CSV: + return comparison(int(condition.left.time), value) + if type(condition.left) == CLTV: + return comparison(int(condition.left.timestamp), value) + if type(condition.left) == XHX: + return comparison(condition.left.sha_hash, value) + else: + return False diff --git a/tests/helpers/money.py b/tests/helpers/money.py new file mode 100644 index 0000000000000000000000000000000000000000..66c8c90f1337ebe244ad90e647df19f1587e3e6f --- /dev/null +++ b/tests/helpers/money.py @@ -0,0 +1,43 @@ +import unittest +from operator import eq, ne, lt, ge +from duniterpy.helpers.money import output_available +from duniterpy.grammars.output import SIG, XHX, CLTV, CSV +from duniterpy.documents.transaction import OutputSource + + +class TestHelpersMoney(unittest.TestCase): + def test_output_available(self): + """ + Only tests for single condition without operators + """ + # SIG + pubkey = "GB8iMAzq1DNmFe3ZxFTBQkGhq4fszTg1gZvx3XCkZXYH" + sig_condition = SIG.token(pubkey).compose() + condition = OutputSource.condition_from_text(sig_condition) + + self.assertTrue(output_available(condition, eq, pubkey)) + self.assertFalse(output_available(condition, ne, pubkey)) + + # XHX + sha_hash = "309BC5E644F797F53E5A2065EAF38A173437F2E6" + xhx_condition = XHX.token(sha_hash).compose() + condition = OutputSource.condition_from_text(xhx_condition) + + self.assertTrue(output_available(condition, eq, sha_hash)) + self.assertFalse(output_available(condition, ne, sha_hash)) + + # CSV + time = 1654300 + csv_condition = CSV.token(time).compose() + condition = OutputSource.condition_from_text(csv_condition) + + self.assertTrue(output_available(condition, ge, time)) + self.assertFalse(output_available(condition, lt, time)) + + # CLTV + timestamp = 2594024 + cltv_condition = CLTV.token(timestamp).compose() + condition = OutputSource.condition_from_text(cltv_condition) + + self.assertTrue(output_available(condition, ge, timestamp)) + self.assertFalse(output_available(condition, lt, timestamp))