### Install Project Documentation Dependencies and Build HTML Docs (Bash) Source: https://github.com/lapets/shamirs/blob/main/README.rst Installs the necessary packages for generating documentation and then builds the HTML documentation using Sphinx. This command first installs the documentation extras and then navigates to the docs directory to run Sphinx. ```bash python -m pip install ".[docs]" cd docs sphinx-apidoc -f -E --templatedir=_templates -o _source .. && make html ``` -------------------------------- ### Install Testing Dependencies and Run Pytest (Bash) Source: https://github.com/lapets/shamirs/blob/main/README.rst Installs the testing dependencies for the project and then executes all unit tests using pytest. Coverage is also measured during this process. ```bash python -m pip install ".[test]" python -m pytest ``` -------------------------------- ### Installing Development Dependencies with Pip Source: https://github.com/lapets/shamirs/blob/main/README.rst Shows how to install optional development dependencies for the Shamirs project, such as documentation and linting tools, using pip and pyproject.toml. ```bash python -m pip install "'.[docs,lint]" ``` -------------------------------- ### Install Shamirs Package Source: https://github.com/lapets/shamirs/blob/main/README.rst Installs the shamirs library using pip. This command should be run in a terminal or command prompt. ```bash python -m pip install shamirs ``` -------------------------------- ### Generate Documentation with Sphinx Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Instructions for generating project documentation using Sphinx. This involves installing the documentation dependencies, navigating to the docs directory, and running Sphinx commands. ```bash python -m pip install "'.[docs]" cd docs sphinx-apidoc -f -E --templatedir=_templates -o _source .. && make html ``` -------------------------------- ### Install Linting Dependencies and Run Pylint (Bash) Source: https://github.com/lapets/shamirs/blob/main/README.rst Installs the Pylint dependency and then runs Pylint on the source code to enforce style conventions. This helps maintain code quality and consistency. ```bash python -m pip install ".[lint]" python -m pylint src/shamirs ``` -------------------------------- ### Enforce Style Conventions with Pylint Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Instructions for installing linting dependencies and running Pylint to enforce code style conventions across the Shamirs project. Pylint checks are performed on the source files. ```bash python -m pip install "'.[lint]" python -m pylint src/shamirs ``` -------------------------------- ### Create and Interpolate Secret Shares in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Demonstrates how to use the `shares` function to create secret shares from a plaintext integer and the `interpolate` function to reconstruct the original plaintext. Shows examples with default and custom parameters like quantity, modulus, and threshold. ```python >>> ss = shamirs.shares(123, quantity=3) >>> len(ss) 3 >>> shamirs.interpolate(ss) 123 >>> ss = shamirs.shares(456, quantity=20, modulus=15485867, threshold=10) >>> shamirs.interpolate(ss[5:15], threshold=10) 456 ``` -------------------------------- ### Run Unit Tests with Pytest Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Commands to install test dependencies and execute unit tests using pytest for the Shamirs library. Pytest is configured via the `pyproject.toml` file. ```bash python -m pip install "'.[test]" python -m pytest ``` -------------------------------- ### Handle Default and Explicit Threshold in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Demonstrates how the reconstruction threshold is handled. When omitted, the default threshold is equal to the number of shares requested. Examples show reconstruction with the default threshold and with an explicitly specified threshold. ```python >>> (r, s, t) = shamirs.shares(123, 3) >>> shamirs.interpolate([r, s, t]) # Three shares (at threshold). 123 >>> shamirs.interpolate([r, s]) # Two shares (below threshold). 119174221476707020724653887077758571505 >>> (r, s, t) = shamirs.shares(123, 3, threshold=2) >>> shamirs.interpolate([r, s]) # Two shares (at threshold). 123 >>> shamirs.interpolate([s, t]) # Two shares (at threshold). 123 >>> shamirs.interpolate([r, t]) # Two shares (at threshold). 123 ``` -------------------------------- ### Represent and Access Individual Secret Shares in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Illustrates the usage of the `share` class to represent individual secret shares. Shows how to create a share object and access its components (index, value, modulus) directly or via tuple indices. Also demonstrates casting a share object to an integer to get its value. ```python >>> s = shamirs.share(1, 2, 3) >>> s.index 1 >>> s.value 2 >>> s.modulus 3 >>> [s[0], s[1], s[2]] [1, 2, 3] >>> int(s) # Share value. 2 ``` -------------------------------- ### Tag and Push Git for Publishing (Bash) Source: https://github.com/lapets/shamirs/blob/main/README.rst Creates a Git tag for the version being published and pushes it to the origin. This is a prerequisite for publishing the package to PyPI. ```bash git tag ?.?.? git push origin ?.?.? ``` -------------------------------- ### Share Encoding and Decoding with Shamirs Source: https://github.com/lapets/shamirs/blob/main/README.rst Demonstrates conversion of Shamirs share objects to and from bytes-like objects and Base64 strings for serialization and transport. ```python >>> shamirs.share.from_base64('AQAAAAIAAADkAPED').to_bytes().hex() '0100000002000000e400f103' >>> [s.to_base64() for s in shamirs.shares(123, 3, 1009)] ['AQAAAAIAAADkAPED', 'AgAAAAIAAABRAfED', 'AwAAAAIAAADCAfED'] ``` -------------------------------- ### Get Integer Representation of Share Field Element (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Returns the least nonnegative residue of the field element corresponding to the secret share. This is achieved by casting the share object to an integer. ```python from shamirs import share s = share(123, 456, 1021) print(int(s)) ``` -------------------------------- ### Add and Multiply Shares in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Shows how to use the `shamirs.add` and `shamirs.mul` helper functions for performing addition and scalar multiplication on collections of shares. These functions facilitate rapid prototyping and testing. ```python >>> ss = shamirs.shares(123, 3) >>> ts = shamirs.shares(456, 3) >>> shamirs.interpolate(shamirs.add(ss, ts)) 579 >>> shamirs.interpolate(shamirs.mul(ss, 2)) 246 ``` -------------------------------- ### Modulus Specification for Shamirs Shares Source: https://github.com/lapets/shamirs/blob/main/README.rst Illustrates how to explicitly set the modulus when creating Shamirs shares or how the default 128-bit modulus is applied. Also shows modulus retrieval from share objects. ```python >>> (r, s, t) = shamirs.shares(123, 3) >>> r.modulus == (2 ** 127) - 1 True >>> (r, s, t) = shamirs.shares(123, 3, modulus=1009) >>> r.modulus 1009 ``` -------------------------------- ### Run Unit Tests with Doctest (Bash) Source: https://github.com/lapets/shamirs/blob/main/README.rst Executes unit tests embedded within the source files using the doctest module. This is an alternative method to running tests compared to pytest. ```bash python src/shamirs/shamirs.py -v ``` -------------------------------- ### Perform Addition of Secret Shares with Modulus and Compactness (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Demonstrates the usage of the add function for performing addition on secret shares. It showcases how to handle individual shares, iterables of shares, and the `modulus` and `compact` parameters. This function is primarily for testing and succinct operations. ```Python from shamirs import shares, interpolate, add, share # Example 1: Adding two sets of shares with modulus ss = shares(123, 3, modulus=1009) ts = shares(456, 3, modulus=1009) print(interpolate(add(ss, ts))) # Example 2: Adding shares from combined iterables print(interpolate(add([*ss, *ts]))) # Example 3: Adding compact shares with explicit modulus and compactness ss_compact = shares(123, 3, modulus=1009, compact=True) ts_compact = shares(456, 3, modulus=1009, compact=True) print(interpolate(add([*ss_compact, *ts_compact], modulus=1009, compact=True))) # Example 4: Adding shares where modulus is inferred from compact shares print(add(share(2, 123), share(2, 456), modulus=1009)) # Example 5: Adding shares with explicit compactness flag print(add(share(2, 123, 1009), share(2, 456, 1009), compact=True)) # Example 6: Adding shares with explicit modulus and compactness flag print(add(share(2, 123), share(2, 456), modulus=1009, compact=True)) # Example 7: Adding shares with explicit modulus and non-compact flag print(add(share(2, 123), share(2, 456), modulus=1009, compact=False)) # Example 8: Demonstrating single share return when applicable print(add(share(2, 123, 1009), share(2, 456, 1009))) ``` -------------------------------- ### Extending Share with Modulus Source: https://github.com/lapets/shamirs/blob/main/README.rst Demonstrates how to add a modulus to a two-component `share` object using the modulus operator (`%`). This allows for the extension of a compact share to include its modulus. ```python import shamirs s = shamirs.share(1, 2) extended_s = s % 3 print(extended_s) t = shamirs.share(1, 2) t %= 3 print(t) ``` -------------------------------- ### Sum Multiple Share Sets using sum() Source: https://context7.com/lapets/shamirs/llms.txt Demonstrates how to sum multiple sets of Shamirs shares using the built-in sum() function. This involves creating shares for different numbers and then combining them using zip and sum. It requires the shamirs library. ```python import shamirs ts = [shamirs.shares(n, quantity=3) for n in [123, 456, 789]] result = shamirs.interpolate([sum(ss) for ss in zip(*ts)]) print(result) # Output: 1368 ``` -------------------------------- ### Share and Reconstruct Secret Source: https://github.com/lapets/shamirs/blob/main/README.rst Demonstrates the basic usage of the shamirs library. The `shares` function splits an integer into a specified number of shares, and the `interpolate` function reconstructs the original integer from a given set of shares. Optionally, a modulus and threshold can be specified. ```python import shamirs # Share a secret ss = shamirs.shares(123, quantity=3) print(len(ss)) # Reconstruct the secret print(shamirs.interpolate(ss)) # Share with specific modulus and threshold ss = shamirs.shares(456, quantity=20, modulus=15485867, threshold=10) print(shamirs.interpolate(ss[5:15], threshold=10)) ``` -------------------------------- ### Share Arithmetic Operations with Shamirs Source: https://github.com/lapets/shamirs/blob/main/README.rst Demonstrates addition and scalar multiplication of Shamirs shares using special methods and helper functions. Supports operations with and without an explicit modulus. ```python >>> (r, s, t) = shamirs.shares(123, 3) >>> (u, v, w) = shamirs.shares(456, 3) >>> shamirs.interpolate([r + u, s + v, t + w]) 579 >>> (r, s, t) = shamirs.shares(123, 3) >>> r *= 2 >>> s *= 2 >>> t *= 2 >>> shamirs.interpolate([r, s, t]) 246 ``` ```python >>> ss = shamirs.shares(123, 3) >>> ts = shamirs.shares(456, 3) >>> shamirs.interpolate(shamirs.add(ss, ts)) 579 >>> shamirs.interpolate(shamirs.mul(ss, 2)) 246 ``` ```python >>> (r, s, t) = shamirs.shares(123, 3, modulus=1009, compact=True) >>> (u, v, w) = shamirs.shares(456, 3, modulus=1009, compact=True) >>> shamirs.interpolate( ... [ ... shamirs.add(r, u, modulus=1009), ... shamirs.add(s, v, modulus=1009), ... shamirs.add(t, w, modulus=1009) ... ], ... modulus=1009 ... ) 579 >>> shamirs.interpolate( ... [ ... shamirs.mul(r, 2, modulus=1009), ... shamirs.mul(s, 2, modulus=1009), ... shamirs.mul(t, 2, modulus=1009) ... ], ... modulus=1009 ... ) 246 ``` -------------------------------- ### Interpolate Shares with Optional Threshold in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Demonstrates how to interpolate shares using the `shamirs.interpolate` function. The `threshold` argument can optionally be provided to potentially reduce the number of arithmetic operations during reconstruction. ```python >>> ss = shamirs.shares(123, 256, threshold=2) >>> shamirs.interpolate(ss) # Slower. 123 >>> shamirs.interpolate(ss, threshold=2) # Faster. 123 ``` -------------------------------- ### Base64 Serialization (to_base64 / from_base64) Source: https://context7.com/lapets/shamirs/llms.txt Illustrates converting Shamirs shares to and from Base64 strings using `to_base64()` and `from_base64()`. This method is suitable for text-based storage or transmission, such as in configuration files or network protocols. It supports single shares and lists of shares. ```python import shamirs # Serialize share to Base64 s = shamirs.share(123, 456, 1021) b64 = s.to_base64() print(b64) # Output: ewAAAAIAAADIAf0D # Deserialize from Base64 restored = shamirs.share.from_base64(b64) print((restored.index, restored.value, restored.modulus)) # Output: (123, 456, 1021) # Serialize multiple shares shares_list = shamirs.shares(123, 3, 1009) encoded = [s.to_base64() for s in shares_list] print(encoded) # Output: ['AQAAAAIAAADkAPED', 'AgAAAAIAAABRAfED', 'AwAAAAIAAADCAfED'] # Round-trip conversion original = shamirs.share(123, 2**100, (2**127) - 1) restored = shamirs.share.from_base64(original.to_base64()) print((restored.index, restored.value, restored.modulus) == (123, 2**100, (2**127) - 1)) # Output: True ``` -------------------------------- ### Perform Arithmetic Operations on Shares in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Illustrates how to perform addition of `share` objects and multiplication of `share` objects by a scalar using Python's built-in operators, which are enabled by special methods like `__add__` and `__mul__`. ```python >>> (r, s, t) = shamirs.shares(123, 3) >>> (u, v, w) = shamirs.shares(456, 3) >>> shamirs.interpolate([r + u, s + v, t + w]) 579 >>> (r, s, t) = shamirs.shares(123, 3) >>> r *= 2 >>> s *= 2 >>> t *= 2 >>> shamirs.interpolate([r, s, t]) 246 ``` -------------------------------- ### Handle Invalid Parameter Values in Shamirs Add Function (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Illustrates how the `add` function handles various invalid parameter inputs, leading to `TypeError`, `ValueError`, or other exceptions. This demonstrates the function's validation mechanisms for arguments, modulus, and compactness. ```Python from shamirs import shares, interpolate, add, share try: add([], 123) except TypeError as e: print(f"Caught expected error: {e}") try: add(modulus=123) except TypeError as e: print(f"Caught expected error: {e}") try: add([share(2, 123, 1009)], 'abc') except TypeError as e: print(f"Caught expected error: {e}") try: ss_test = shares(123, 3, 1009) ts_test = shares(456, 3, 1009) add([*ss_test, *ts_test], modulus='abc') except TypeError as e: print(f"Caught expected error: {e}") try: add(shares(123, 3, 1223) + shares(123, 3, 1021)) except ValueError as e: print(f"Caught expected error: {e}") try: add(shares(123, 3, 1223) + shares(123, 3, 1223), modulus=1021) except ValueError as e: print(f"Caught expected error: {e}") try: add(shares(123, 3, 1223) + shares(123, 3, 1223), compact='abc') except TypeError as e: print(f"Caught expected error: {e}") try: add(shares(123, 3, compact=True) + shares(123, 3, compact=True)) except ValueError as e: print(f"Caught expected error: {e}") ``` -------------------------------- ### Compact Share Creation Source: https://github.com/lapets/shamirs/blob/main/README.rst Shows how to create compact secret shares that do not include the modulus component, reducing memory footprint. This is achieved by setting the `compact` argument to `True` in the `shares` function. ```python import shamirs shares_compact = shamirs.shares(123, quantity=3, modulus=1009, compact=True) print(shares_compact) ``` -------------------------------- ### Create a New Share with a Specified Modulus (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Returns a new share object that is a copy of the original but with the specified modulus component. Raises a ValueError if the original share already has a different modulus. ```python from shamirs import share s = share(2, 123) % 1009 print(s) try: share(2, 10, 17) % 1009 except ValueError as e: print(e) # Same modulus is permitted print(share(2, 123, 1009) % 1009) ``` -------------------------------- ### String Representation of Share (__repr__) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Returns the unambiguous string representation of a share object, suitable for debugging. This representation mirrors the constructor call and includes the modulus only if it was provided during share creation. ```python >>> share(123, 456, 1021) share(123, 456, 1021) >>> share(123, 456) share(123, 456) ``` -------------------------------- ### Create Compact Secret Shares in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Shows how to create secret shares without including the modulus component by setting the `compact` argument to `True` in the `shares` function. This results in `share` objects with only two components: index and value. ```python >>> shamirs.shares(123, quantity=3, modulus=1009, compact=True) [share(1, 649), share(2, 778), share(3, 510)] ``` -------------------------------- ### Reverse Add Shamir Secret Shares and Integers (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Demonstrates the reverse addition operation for Shamir's secret shares, where an integer appears on the left side of the addition operator. This mirrors the functionality of `__add__` for cases like `0 + share`. ```python >>> 0 + share(123, 456, 1021) share(123, 456, 1021) >>> ts = [shares(n, quantity=3) for n in [123, 456, 789]] >>> interpolate([sum(ss) for ss in zip(*ts)]) 1368 ``` -------------------------------- ### Reconstruct Secret from Shares (Python) Source: https://context7.com/lapets/shamirs/llms.txt Calculates the original integer plaintext from a sequence of secret shares using Lagrange interpolation. Shares can be provided in any order and supports threshold-based reconstruction and performance optimizations by specifying the threshold. ```python import shamirs # Create shares and reconstruct ss = shamirs.shares(5, quantity=3, modulus=31) result = shamirs.interpolate(ss) print(result) # Output: 5 # Works with shares in any order result = shamirs.interpolate(reversed(ss)) print(result) # Output: 5 # Threshold-based reconstruction ss = shamirs.shares(123, quantity=20, modulus=1223, threshold=12) # First 12 shares are sufficient print(shamirs.interpolate(ss[:12], threshold=12)) # Output: 123 # Last 12 shares also work print(shamirs.interpolate(ss[8:], threshold=12)) # Output: 123 # Performance optimization: specify threshold when known large_shares = shamirs.shares(123, quantity=256, threshold=2) # Faster with explicit threshold shamirs.interpolate(large_shares, threshold=2) # Output: 123 # Function aliases (all equivalent to interpolate) shamirs.reconstruct(ss[:12], threshold=12) # Output: 123 shamirs.recover(ss[:12], threshold=12) # Output: 123 shamirs.reveal(ss[:12], threshold=12) # Output: 123 ``` -------------------------------- ### Binary Serialization (to_bytes / from_bytes) Source: https://context7.com/lapets/shamirs/llms.txt Details the conversion of Shamirs shares to and from byte-like objects using `to_bytes()` and `from_bytes()`. This is essential for storing or transmitting shares persistently. It handles both standard and compact shares, with or without an explicit modulus. ```python import shamirs # Serialize share to bytes s = shamirs.share(123, 456, 1021) binary = s.to_bytes() print(binary.hex()) # Output: 7b00000002000000c801fd03 # Deserialize from bytes restored = shamirs.share.from_bytes(binary) print((restored.index, restored.value, restored.modulus)) # Output: (123, 456, 1021) # Works with large values s = shamirs.share(123, 2**100, (2**127) - 1) restored = shamirs.share.from_bytes(s.to_bytes()) print(restored.index) # Output: 123 print(restored.value == 2**100) # Output: True # Compact shares without modulus s = shamirs.share(123, 2**100) restored = shamirs.share.from_bytes(s.to_bytes()) print((restored.index, restored.value) == (123, 2**100)) # Output: True ``` -------------------------------- ### Scalar Multiplication of Shares (mul) Source: https://context7.com/lapets/shamirs/llms.txt Explains how to multiply Shamirs secret shares by an integer scalar using the `mul` function or standard multiplication operators. This operation can be performed in-place or as a new operation, and supports compact shares with an explicit modulus. ```python import shamirs # Multiply shares by scalar ss = shamirs.shares(123, quantity=3, modulus=1009) doubled = shamirs.mul(ss, scalar=2) print(shamirs.interpolate(doubled)) # Output: 246 # Using * operator on individual shares (r, s, t) = shamirs.shares(123, 3) result = shamirs.interpolate([r * 2, s * 2, t * 2]) print(result) # Output: 246 # In-place multiplication (r, s, t) = shamirs.shares(123, 3) r *= 2 s *= 2 t *= 2 print(shamirs.interpolate([r, s, t])) # Output: 246 # Scalar on left side also works (r, s, t) = shamirs.shares(123, 3) result = shamirs.interpolate([2 * r, 2 * s, 2 * t]) print(result) # Output: 246 # Multiply compact shares ss = shamirs.shares(123, 3, modulus=1009, compact=True) result = shamirs.mul(ss, scalar=3, modulus=1009) print(shamirs.interpolate(result, modulus=1009)) # Output: 369 ``` -------------------------------- ### Share Addition API Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md This API allows for the addition of two secret shares or a secret share with an integer zero. It handles various scenarios including modulus operations, type checking, and index/modulus consistency. ```APIDOC ## Share Addition API ### Description This endpoint enables the addition of secret shares. It supports adding a share with another share or with the integer zero. The operation respects modulus arithmetic and ensures consistency in share indices and moduli. ### Method POST (Implicit - operations performed on share objects) ### Endpoint N/A (Operations are performed on share objects within the application) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **other** (Union[share, int]) - Required - The secret share or integer value to be added to the current share. ### Request Example ```json { "operation": "add", "share1": { "value": "...", "index": 1, "modulus": 1021 }, "operand": { "type": "share", "value": "...", "index": 1, "modulus": 1021 } } ``` or ```json { "operation": "add", "share1": { "value": "...", "index": 1, "modulus": 1021 }, "operand": { "type": "int", "value": 0 } } ``` ### Response #### Success Response (200) - **result_share** (share) - The resulting secret share after addition. #### Response Example ```json { "result_share": { "value": "...", "index": 1, "modulus": 1021 } } ``` ### Error Handling - **TypeError**: Raised if both operands are not shares. - **ValueError**: Raised if both shares do not have a modulus component or if shares have different indices or moduli. ### Notes - Share addition is consistent across all shares. - If the sum exceeds the maximum representable value, the plaintext will wrap around the modulus. - Both operands must be shares that have a modulus component. - Any attempt to add shares represented using different finite fields or with different indices raises an exception. ``` -------------------------------- ### Add Shamir Secret Shares and Integers (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Demonstrates adding two secret shares or a secret share with an integer. Supports addition with the integer 0 for base cases in functions like `sum()`. Handles value wrapping around the modulus and raises errors for incompatible share types or different moduli/indices. ```python >>> (r, s, t) = shares(123, 3) >>> (u, v, w) = shares(456, 3) >>> interpolate([r + u, s + v, t + w]) 579 >>> r += u >>> s += v >>> w += t >>> interpolate([r, s, w]) 579 >>> share(123, 456, 1021) + 0 share(123, 456, 1021) >>> ts = [shares(n, quantity=3) for n in [123, 456, 789]] >>> interpolate([sum(ss) for ss in zip(*ts)]) 1368 >>> (a, b) = shares(1020, quantity=2, modulus=1021) >>> (c, d) = shares(2, quantity=2, modulus=1021) >>> interpolate([a + c, b + d]) == (1020 + 2) % 1021 == 1 True >>> share(2, 123, 1009) + 'abc' Traceback (most recent call last): ... TypeError: both operands must be shares >>> share(1, 123) + share(2, 456, 1009) Traceback (most recent call last): ... ValueError: both shares must have a modulus component >>> (r, s, t) = shares(2, quantity=3, modulus=5) >>> (u, v, w) = shares(3, quantity=3, modulus=7) >>> r + u Traceback (most recent call last): ... ValueError: shares being added must have the same index and modulus >>> (r, s, t) = shares(2, quantity=3, modulus=5) >>> (u, v, w) = shares(3, quantity=3, modulus=5) >>> r + v Traceback (most recent call last): ... ValueError: shares being added must have the same index and modulus >>> for quantity in range(2, 20): ... for operations in range(2, 20): ... vs = [ ... int.from_bytes(secrets.token_bytes(2), 'little') ... for _ in range(operations) ... ] ... sss = [shares(v, quantity) for v in vs] ... assert(interpolate([sum(ss) for ss in zip(*sss)]) == sum(vs)) ``` -------------------------------- ### Secret Reconstruction with Shamirs Interpolation Source: https://github.com/lapets/shamirs/blob/main/README.rst Shows how to reconstruct a secret using Shamirs' interpolate function, highlighting the requirement for an explicit modulus when using compact shares and the effect of the threshold. ```python >>> (r, s, t) = shamirs.shares(123, 3, modulus=1009, compact=True) >>> shamirs.interpolate([r, s, t]) Traceback (most recent call last): ... ValueError: modulus is not found in share objects and is not provided as an argument >>> shamirs.interpolate([r, s, t], modulus=1009) 123 ``` ```python >>> (r, s, t) = shamirs.shares(123, 3) >>> shamirs.interpolate([r, s, t]) # Three shares (at threshold). 123 >>> shamirs.interpolate([r, s]) # Two shares (below threshold). 119174221476707020724653887077758571505 >>> (r, s, t) = shamirs.shares(123, 3, threshold=2) >>> shamirs.interpolate([r, s]) # Two shares (at threshold). 123 >>> shamirs.interpolate([s, t]) # Two shares (at threshold). 123 >>> shamirs.interpolate([r, t]) # Two shares (at threshold). 123 ``` ```python >>> ss = shamirs.shares(123, 256, threshold=2) >>> shamirs.interpolate(ss) # Slower. 123 >>> shamirs.interpolate(ss, threshold=2) # Faster. 123 ``` -------------------------------- ### Modular Arithmetic Operations on Shares in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Illustrates performing addition and scalar multiplication on shares with a specified modulus. The `shamirs.add` and `shamirs.mul` functions can be used with the `modulus` argument for modular arithmetic. ```python >>> (r, s, t) = shamirs.shares(123, 3, modulus=1009, compact=True) >>> (u, v, w) = shamirs.shares(456, 3, modulus=1009, compact=True) >>> shamirs.interpolate( ... [ ... shamirs.add(r, u, modulus=1009), ... shamirs.add(s, v, modulus=1009), ... shamirs.add(t, w, modulus=1009) ... ], ... modulus=1009 ... ) 579 >>> shamirs.interpolate( ... [ ... shamirs.mul(r, 2, modulus=1009), ... shamirs.mul(s, 2, modulus=1009), ... shamirs.mul(t, 2, modulus=1009) ... ], ... modulus=1009 ... ) 246 ``` -------------------------------- ### Add Compact Shares with Explicit Modulus Source: https://context7.com/lapets/shamirs/llms.txt Shows how to add compact Shamirs shares, which requires explicitly providing the modulus. This function is useful for performing addition operations on encrypted data without decryption. ```python import shamirs ss = shamirs.shares(123, 3, modulus=1009, compact=True) ts = shamirs.shares(456, 3, modulus=1009, compact=True) result = shamirs.add([*ss, *ts], modulus=1009, compact=True) print(shamirs.interpolate(result, modulus=1009)) # Output: 579 ``` -------------------------------- ### Extend Share Objects with Modulus in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Demonstrates how to add a modulus component to a two-component `share` object using the modulus operator (`%`). This operation is supported by the `__mod__` special method. ```python >>> s = shamirs.share(1, 2) >>> s % 3 share(1, 2, 3) >>> t = shamirs.share(1, 2) >>> t %= 3 >>> t share(1, 2, 3) ``` -------------------------------- ### Share Object Representation Source: https://github.com/lapets/shamirs/blob/main/README.rst Illustrates the structure and access methods for individual secret share objects. A `share` object can have two or three integer components (index, value, and optionally modulus). Components can be accessed by index or attribute name. ```python import shamirs s = shamirs.share(1, 2, 3) print(s.index) print(s.value) print(s.modulus) print([s[0], s[1], s[2]]) print(int(s)) # Share value. ``` -------------------------------- ### Split Secret into Shares (Python) Source: https://context7.com/lapets/shamirs/llms.txt Transforms an integer plaintext into a specified number of secret shares. The original plaintext can be recovered using the `interpolate` function when enough shares are provided. Supports setting quantity, threshold, modulus, and compact share format. ```python import shamirs # Basic usage: split secret 123 into 3 shares (all 3 required to reconstruct) secret_shares = shamirs.shares(123, quantity=3) print(len(secret_shares)) # Output: 3 # Each share contains index, value, and modulus s = secret_shares[0] print(f"Index: {s.index}, Value: {s.value}, Modulus: {s.modulus}") # Reconstruct the original secret original = shamirs.interpolate(secret_shares) print(original) # Output: 123 # Advanced: Create 20 shares where only 10 are needed (threshold) shares_with_threshold = shamirs.shares(456, quantity=20, modulus=15485867, threshold=10) # Any 10 shares can reconstruct the secret reconstructed = shamirs.interpolate(shares_with_threshold[5:15], threshold=10) print(reconstructed) # Output: 456 # Compact shares without embedded modulus (saves memory) compact_shares = shamirs.shares(123, quantity=3, modulus=1009, compact=True) # Must provide modulus explicitly when reconstructing shamirs.interpolate(compact_shares, modulus=1009) # Output: 123 ``` -------------------------------- ### String Representation of Share (__str__) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Returns the string representation of a share object. This representation includes the index, value, and modulus if the modulus is present. If the modulus is not set, it is omitted from the string representation. ```python >>> str(share(123, 456, 1021)) 'share(123, 456, 1021)' >>> str(share(123, 456)) 'share(123, 456)' ``` -------------------------------- ### Reconstruct Plaintext from Compact Shares in Python Source: https://github.com/lapets/shamirs/blob/main/docs/index.md Explains the requirement to explicitly provide the modulus when reconstructing plaintext from compact `share` objects using the `interpolate` function. If the modulus is not provided, a `ValueError` is raised. ```python >>> (r, s, t) = shamirs.shares(123, 3, modulus=1009, compact=True) >>> shamirs.interpolate([r, s, t]) Traceback (most recent call last): ... ValueError: modulus is not found in share objects and is not provided as an argument >>> shamirs.interpolate([r, s, t], modulus=1009) 123 ``` -------------------------------- ### Access Share Components by Attribute Name (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Allows accessing the index, value, and modulus components of a share object using named attributes. If a modulus was not provided during share creation, accessing s.modulus will raise an AttributeError. ```python from shamirs import share s = share(1, 2, 3) print(s.index) print(s.value) print(s.modulus) s_no_mod = share(1, 2) try: print(s_no_mod.modulus) except AttributeError as e: print(e) ``` -------------------------------- ### Create a Secret Share Object in Python Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Constructs a secret share object with index, value, and an optional prime modulus. The index must be a 32-bit positive integer, the value must be non-negative and less than the modulus, and the modulus must be at least 2. Raises TypeError for non-integer inputs and ValueError for invalid numeric inputs. ```python share(1, 123, 1009) share(1, 123) share(4294967296, 123, (2**127) - 1) # Raises ValueError: index must be a positive integer requiring at most 32 bits share(2, -123, (2**127) - 1) # Raises ValueError: share value must be a nonnegative integer share(2, 2000, 1009) # Raises ValueError: share value must be strictly less than the prime modulus share(2, 123, 1) # Raises ValueError: prime modulus must be at least 2 share('abc', 123, 1009) # Raises TypeError: index must be an integer share(2, 'abc', 1009) # Raises TypeError: value must be an integer share(2, 123, 'abc') # Raises TypeError: prime modulus must be an integer ``` -------------------------------- ### Reconstruct Secret Shares (Alias) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md An alias for the `interpolate` function, providing an alternative way to reconstruct secret plaintexts from shares. ```APIDOC ## POST /shamirs/reconstruct ### Description Alias for the `interpolate` function. Reconstructs an integer plaintext from a sequence of secret shares. ### Method POST ### Endpoint /shamirs/reconstruct ### Parameters #### Request Body - **shares** (Iterable[share]) - Required - An iterable of secret shares from which to reconstruct a plaintext. - **modulus** (Optional[int]) - Optional - The modulus to use when performing interpolation. - **threshold** (Optional[int]) - Optional - The minimum number of shares required to reconstruct a plaintext. ### Request Example ```json { "shares": [ {"coefficient": 1, "point": 2, "modulus": 31}, {"coefficient": 3, "point": 4, "modulus": 31} ], "modulus": 31, "threshold": 2 } ``` ### Response #### Success Response (200) - **plaintext** (int) - The reconstructed integer plaintext. #### Response Example ```json { "plaintext": 5 } ``` ``` -------------------------------- ### Encode Share to Base64 (to_base64) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Returns a Base64 string encoding of the share object. This method encodes all present share information, including the index, value, and modulus. It is useful for transmitting or storing share data in text-based formats. ```python >>> share(123, 456, 1021).to_base64() 'ewAAAAIAAADIAf0D' >>> share.from_base64(share(3, 2**100, (2**127) - 1).to_base64()).value == 2**100 True >>> share.from_base64(share(3, 2**100).to_base64()).value == 2**100 True ``` -------------------------------- ### Recover Secret Shares (Alias) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md An alias for the `interpolate` function, providing another alternative to reconstruct secret plaintexts from shares. ```APIDOC ## POST /shamirs/recover ### Description Alias for the `interpolate` function. Reconstructs an integer plaintext from a sequence of secret shares. ### Method POST ### Endpoint /shamirs/recover ### Parameters #### Request Body - **shares** (Iterable[share]) - Required - An iterable of secret shares from which to reconstruct a plaintext. - **modulus** (Optional[int]) - Optional - The modulus to use when performing interpolation. - **threshold** (Optional[int]) - Optional - The minimum number of shares required to reconstruct a plaintext. ### Request Example ```json { "shares": [ {"coefficient": 1, "point": 2, "modulus": 31}, {"coefficient": 3, "point": 4, "modulus": 31} ], "modulus": 31, "threshold": 2 } ``` ### Response #### Success Response (200) - **plaintext** (int) - The reconstructed integer plaintext. #### Response Example ```json { "plaintext": 5 } ``` ``` -------------------------------- ### Alias Functions for Interpolation (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md Provides alternative function names (reconstruct, recover, reveal) that are direct aliases for the 'interpolate' function. These aliases offer different semantic naming for the same secret reconstruction functionality using Lagrange interpolation. ```python from shamirs import reconstruct, recover, reveal, shares # Example using reconstruct (alias for interpolate) print(reconstruct(shares(5, 3, modulus=31))) # Example using recover (alias for interpolate) print(recover(shares(5, 3, modulus=31))) # Example using reveal (alias for interpolate) print(reveal(shares(5, 3, modulus=31))) ``` -------------------------------- ### Generate Secret Shares using Shamir's Algorithm (Python) Source: https://github.com/lapets/shamirs/blob/main/docs/_source/shamirs.md The `shares` function transforms an integer plaintext into a specified number of secret shares. These shares can later be used with the `interpolate` function to recover the original plaintext. It supports customizable modulus and threshold values, and an option for compact shares. ```python from shamirs import shares, interpolate # Example 1: Basic usage with default modulus shares_default_mod = shares(123, 100) print(f"Number of shares generated: {len(shares_default_mod)}") # Example 2: With a specified modulus shares_mod_31 = shares(1, 3, modulus=31) print(f"Number of shares generated with modulus 31: {len(shares_mod_31)}") # Example 3: With a different modulus shares_mod_41 = shares(17, 10, modulus=41) print(f"Number of shares generated with modulus 41: {len(shares_mod_41)}") # Example 4: Default modulus check (r, s, t) = shares(123, 3) print(f"Default modulus check: {r.modulus == (2 ** 127) - 1}") # Example 5: Reconstruction with default threshold (r, s, t) = shares(123, 3) reconstructed_default = interpolate([r, s, t]) print(f"Reconstructed plaintext (default threshold): {reconstructed_default}") # Example 6: Reconstruction below threshold reconstructed_below_threshold = interpolate([r, s]) print(f"Reconstruction attempt below threshold: {reconstructed_below_threshold == 123}") # Example 7: Reconstruction with explicit threshold (r, s, t) = shares(123, 3, threshold=2) reconstructed_explicit = interpolate([r, s]) print(f"Reconstructed plaintext (explicit threshold=2): {reconstructed_explicit}") # Example 8: Compact shares (modulus not included) compact_shares = shares(17, 2, modulus=41, compact=True) try: print(compact_shares[0].modulus) except AttributeError as e: print(f"Compact share attribute error: {e}") # Example 9: Invalid plaintext greater than modulus try: shares(256, 3, modulus=31) except ValueError as e: print(f"Error for plaintext > modulus: {e}") # Example 10: Invalid plaintext type try: shares('abc', 3, 17) except TypeError as e: print(f"Error for invalid plaintext type: {e}") # Example 11: Invalid quantity type try: shares(1, 'abc', 17) except TypeError as e: print(f"Error for invalid quantity type: {e}") # Example 12: Invalid modulus type try: shares(1, 3, 'abc') except TypeError as e: print(f"Error for invalid modulus type: {e}") # Example 13: Invalid threshold type try: shares(1, 3, 7, 'abc') except TypeError as e: print(f"Error for invalid threshold type: {e}") # Example 14: Invalid compact type try: shares(1, 3, 7, compact='abc') except TypeError as e: print(f"Error for invalid compact type: {e}") # Example 15: Negative plaintext try: shares(-2, 3, 17) except ValueError as e: print(f"Error for negative plaintext: {e}") # Example 16: Quantity less than 2 try: shares(1, 1, 17) except ValueError as e: print(f"Error for quantity < 2: {e}") # Example 17: Quantity too large (bit representation) try: shares(1, 2**32, 17) except ValueError as e: print(f"Error for large quantity: {e}") # Example 18: Quantity too large (modulus constraint) try: shares(1, 2**32, (2**127) - 1) except ValueError as e: print(f"Error for quantity > modulus: {e}") # Example 19: Modulus less than 2 try: shares(1, 3, 1) except ValueError as e: print(f"Error for modulus < 2: {e}") # Example 20: Threshold greater than quantity try: shares(1, quantity=3, modulus=11, threshold=7) except ValueError as e: print(f"Error for threshold > quantity: {e}") # Example 21: More shares generated than needed for threshold shares_more_than_threshold = shares(1, quantity=7, modulus=11, threshold=3) print(f"Number of shares generated (threshold=3, quantity=7): {len(shares_more_than_threshold)}") ```