[Python] Cryptographically-Verified Class-Based AST in Python

Discussão em 'Python' iniciado por Stack, Maio 4, 2025.

  1. Stack

    Stack Membro Participativo

    This is likely a niche question. Imagine we have a syntax tree built recursively using custom Python classes, e.g.:

    class Sentence:
    ...

    class And:
    ...

    class Or:
    ...

    class Not:
    ...

    expr = And(
    Sentence("It's sunny"),
    Or(
    Sentence("It's Raining"),
    Not("We're having a picnic")
    )
    )


    I want to write a recursive validation function to validate certain properties of such expressions at run-time. For example, that an expression is in fact built using only a fixed set/subset of these classes, e.g. perhaps that an expression does not include Not class. I want to do so in such a way that if I am passed an untrusted expression instance, generated by python code I do not control (e.g. unpickling a pickled object), the result of the validation is guaranteed to be correct (if validation completes and passes).

    Example:

    >>> expr = <a bunch of hacky code creating a mock expression to fool me>
    >>> validate(expr)
    ValidationError: `And` class failed cryptographic validation. Expression has been tampered with.


    Assume, for the sake of argument, we can sandbox evaluation of our validation function to prevent this untrusted code from accessing or modifying certain global variables / functions, e.g. using RestrictedPython, and can otherwise guarantee the result of this evaluation will be a string or other safe type. Is there a way to write such a validation function?

    Note that this question both about block-chain-style cryptography, as well as the python language. If this is too involved, I would happy for some references also.

    Continue reading...

Compartilhe esta Página