signinwithethereum 5.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: signinwithethereum
3
+ Version: 5.0.0
4
+ Summary: A Python implementation of Sign in with Ethereum (EIP-4361).
5
+ Project-URL: Homepage, https://siwe.xyz
6
+ Project-URL: Repository, https://github.com/signinwithethereum/siwe-py
7
+ Project-URL: EIP, https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4361.md
8
+ Author-email: Jalil Wahdatehagh <jalil@ethfollow.xyz>, "Spruce Systems, Inc." <hello@spruceid.com>, Payton Garland <payton.r.g@gmail.com>
9
+ License-Expression: MIT OR Apache-2.0
10
+ License-File: LICENSE-APACHE
11
+ License-File: LICENSE-MIT
12
+ Keywords: EIP-4361,SIWE,Sign in with Ethereum
13
+ Requires-Python: <4.0,>=3.10
14
+ Requires-Dist: abnf<3,>=2.2
15
+ Requires-Dist: eth-account<0.14,>=0.13.1
16
+ Requires-Dist: eth-utils>=2.2.0
17
+ Requires-Dist: pydantic-core<3,>=2
18
+ Requires-Dist: pydantic<3,>=2.7
19
+ Requires-Dist: typing-extensions<5,>=4
20
+ Requires-Dist: web3<8,>=7.3.0
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Sign in with Ethereum
24
+
25
+ This package provides a Python implementation of EIP-4361: Sign in With Ethereum.
26
+
27
+ ## Installation
28
+
29
+ SIWE can be easily installed in any Python project with pip:
30
+
31
+ ```bash
32
+ pip install signinwithethereum
33
+ ```
34
+
35
+ The distribution is published as `signinwithethereum`, but the import name remains `siwe`:
36
+
37
+ ```python
38
+ from siwe import SiweMessage
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ SIWE provides a `SiweMessage` class which implements EIP-4361.
44
+
45
+ ### Parsing a SIWE Message
46
+
47
+ Parsing is done by initializing a `SiweMessage` object with an EIP-4361 formatted string:
48
+
49
+ ```python
50
+ from siwe import SiweMessage
51
+ message = SiweMessage.from_message(message=eip_4361_string)
52
+ ```
53
+
54
+ Or to initialize a `SiweMessage` as a `pydantic.BaseModel` right away:
55
+
56
+ ```python
57
+ message = SiweMessage(domain="login.xyz", address="0x1234...", ...)
58
+ ```
59
+
60
+ ### Verifying and Authenticating a SIWE Message
61
+
62
+ Verification and authentication is performed via EIP-191, using the `address` field of the `SiweMessage` as the expected signer. The validate method checks message structural integrity, signature address validity, and time-based validity attributes.
63
+
64
+ ```python
65
+ try:
66
+ message.verify(signature="0x...")
67
+ # You can also specify other checks (e.g. the nonce or domain expected).
68
+ except siwe.VerificationError:
69
+ # Invalid
70
+ ```
71
+
72
+ ### Serialization of a SIWE Message
73
+
74
+ `SiweMessage` instances can also be serialized as their EIP-4361 string representations via the `prepare_message` method:
75
+
76
+ ```python
77
+ print(message.prepare_message())
78
+ ```
79
+
80
+ ## Example
81
+
82
+ Parsing and verifying a `SiweMessage` is easy:
83
+
84
+ ```python
85
+ try:
86
+ message = SiweMessage.from_message(eip_4361_string)
87
+ message.verify(signature, nonce="abcdef", domain="example.com")
88
+ except ValueError:
89
+ # Invalid message format
90
+ print("Authentication attempt rejected.")
91
+ except siwe.ExpiredMessage:
92
+ print("Authentication attempt rejected.")
93
+ except siwe.DomainMismatch:
94
+ print("Authentication attempt rejected.")
95
+ except siwe.NonceMismatch:
96
+ print("Authentication attempt rejected.")
97
+ except siwe.InvalidSignature:
98
+ print("Authentication attempt rejected.")
99
+
100
+ # Message has been verified. Authentication complete. Continue with authorization/other.
101
+ ```
102
+
103
+ ## Testing
104
+
105
+ ```bash
106
+ git submodule update --init
107
+ uv sync
108
+ uv run pytest
109
+ ```
110
+
111
+ ## See Also
112
+
113
+ - [Sign in with Ethereum: TypeScript](https://github.com/signinwithethereum/siwe)
114
+ - [SIWE website: siwe.xyz](https://siwe.xyz)
115
+ - [EIP-4361 Specification Draft](https://eips.ethereum.org/EIPS/eip-4361)
116
+ - [EIP-191 Specification](https://eips.ethereum.org/EIPS/eip-191)
117
+
118
+ ## Disclaimer
119
+
120
+ Our Python library for Sign in with Ethereum has not yet undergone a formal
121
+ security audit. We welcome continued feedback on the usability, architecture,
122
+ and security of this implementation.
@@ -0,0 +1,13 @@
1
+ siwe/__init__.py,sha256=l7ZRqcHQXcWqbUJUHumm7SHOt3NqrcK9vAKMeIqB3UU,435
2
+ siwe/defs.py,sha256=wH7W-OVGQSgcTjSNYbGWER-TAq09e6jWEKeBevcOsXM,1209
3
+ siwe/parsed.py,sha256=VXUhklj5MCYZY1KKNakDYCXF3rFEWrbWUHZ2NTKW2mI,2626
4
+ siwe/siwe.py,sha256=F09eukEHD8tiaQJKzntidXUYH15IIicynvj_hN4NF3Y,22419
5
+ siwe/grammars/__init__.py,sha256=w3i2cTy4zVDr58VSGrxkuzVY1DzoEFt60ZQtJNSkIfE,24
6
+ siwe/grammars/eip4361.py,sha256=XcRtoGidsPLFvI3Dks_mVci6VOndBPcEN293T7S__mU,1854
7
+ siwe/grammars/rfc3339.py,sha256=EwK6EMOff5KGIDSD7-DiXe6KNTjR_iHNcWsZ7gViO6Q,949
8
+ siwe/grammars/rfc5234.py,sha256=BJ9EOy5Wl4L2psxheJ0uOEG9LzQ3z4ZHPpU3R5YZ20g,510
9
+ signinwithethereum-5.0.0.dist-info/METADATA,sha256=170eVT0yNckN-SCzi2ONyyElL4fVWLXA52jS64mamqU,3661
10
+ signinwithethereum-5.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
11
+ signinwithethereum-5.0.0.dist-info/licenses/LICENSE-APACHE,sha256=Cn59LpMtrlU-8kjQ-NmfrCfZpWs5_MPJT-nlC5PwipQ,11385
12
+ signinwithethereum-5.0.0.dist-info/licenses/LICENSE-MIT,sha256=nkBJgLCQh_LQSiUmlc7zoBsOW_gfzZxQilNPNytiWD0,1093
13
+ signinwithethereum-5.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2021 Spruce Systems, Inc.
190
+ Copyright (c) 2026 EthID.org
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,26 @@
1
+ Copyright (c) 2021 Spruce Systems, Inc.
2
+ Copyright (c) 2026 EthID.org
3
+
4
+ Permission is hereby granted, free of charge, to any
5
+ person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the
7
+ Software without restriction, including without
8
+ limitation the rights to use, copy, modify, merge,
9
+ publish, distribute, sublicense, and/or sell copies of
10
+ the Software, and to permit persons to whom the Software
11
+ is furnished to do so, subject to the following
12
+ conditions:
13
+
14
+ The above copyright notice and this permission notice
15
+ shall be included in all copies or substantial portions
16
+ of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
19
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
20
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
21
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
22
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
25
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26
+ DEALINGS IN THE SOFTWARE.
siwe/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """Library for EIP-4361 Sign in with Ethereum."""
2
+
3
+ # flake8: noqa: F401
4
+ from .siwe import (
5
+ EIP6492_MAGIC_SUFFIX,
6
+ ChainIdMismatch,
7
+ DomainMismatch,
8
+ ExpiredMessage,
9
+ InvalidSignature,
10
+ ISO8601Datetime,
11
+ MalformedSession,
12
+ NonceMismatch,
13
+ NotYetValidMessage,
14
+ RequestIdMismatch,
15
+ SchemeMismatch,
16
+ SiweMessage,
17
+ UriMismatch,
18
+ VerificationError,
19
+ generate_nonce,
20
+ is_eip6492_signature,
21
+ )
siwe/defs.py ADDED
@@ -0,0 +1,25 @@
1
+ """Regexes for the various fields."""
2
+
3
+ SCHEME = "((?P<scheme>([a-zA-Z][a-zA-Z0-9\\+\\-\\.]*))://)?"
4
+ DOMAIN = "(?P<domain>([^/?#]+)) wants you to sign in with your Ethereum account:\\n"
5
+ ADDRESS = "(?P<address>0x[a-zA-Z0-9]{40})\\n\\n"
6
+ STATEMENT = "((?P<statement>[^\\n]*)\\n)?\\n"
7
+ URI = "(([^ :/?#]+):)?(//([^ /?#]*))?([^ ?#]*)(\\?([^ #]*))?(#(.*))?"
8
+ URI_LINE = f"URI: (?P<uri>{URI}?)\\n"
9
+ VERSION = "Version: (?P<version>1)\\n"
10
+ CHAIN_ID = "Chain ID: (?P<chainId>[0-9]+)\\n"
11
+ NONCE = "Nonce: (?P<nonce>[a-zA-Z0-9]{8,})\\n"
12
+ DATETIME = (
13
+ "([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]"
14
+ "([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(.[0-9]+)?"
15
+ "(([Zz])|([+|-]([01][0-9]|2[0-3]):[0-5][0-9]))"
16
+ )
17
+ ISSUED_AT = f"Issued At: (?P<issuedAt>{DATETIME})"
18
+ EXPIRATION_TIME = f"(\\nExpiration Time: (?P<expirationTime>{DATETIME}))?"
19
+ NOT_BEFORE = f"(\\nNot Before: (?P<notBefore>{DATETIME}))?"
20
+ REQUEST_ID = "(\\nRequest ID: (?P<requestId>[-._~!$&'()*+,;=:@%a-zA-Z0-9]*))?"
21
+ RESOURCES = f"(\\nResources:(?P<resources>(\\n- {URI})*))?"
22
+ REGEX_MESSAGE = (
23
+ f"^{SCHEME}{DOMAIN}{ADDRESS}{STATEMENT}{URI_LINE}{VERSION}{CHAIN_ID}{NONCE}"
24
+ f"{ISSUED_AT}{EXPIRATION_TIME}{NOT_BEFORE}{REQUEST_ID}{RESOURCES}$"
25
+ )
@@ -0,0 +1 @@
1
+ """ABNF definitions."""
@@ -0,0 +1,54 @@
1
+ """Top-level ABNF definition."""
2
+
3
+ from typing import ClassVar, List
4
+
5
+ from abnf.grammars import rfc3986
6
+ from abnf.grammars.misc import load_grammar_rules
7
+ from abnf.parser import Rule as _Rule
8
+
9
+ from . import rfc3339, rfc5234
10
+
11
+
12
+ @load_grammar_rules(
13
+ [
14
+ # RFC 3986
15
+ ("URI", rfc3986.Rule("URI")),
16
+ ("authority", rfc3986.Rule("authority")),
17
+ ("scheme", rfc3986.Rule("scheme")),
18
+ ("reserved", rfc3986.Rule("reserved")),
19
+ ("unreserved", rfc3986.Rule("unreserved")),
20
+ ("reserved", rfc3986.Rule("reserved")),
21
+ ("pchar", rfc3986.Rule("pchar")),
22
+ # RFC 5234
23
+ ("LF", rfc5234.Rule("LF")),
24
+ ("HEXDIG", rfc5234.Rule("HEXDIG")),
25
+ ("ALPHA", rfc5234.Rule("ALPHA")),
26
+ ("DIGIT", rfc5234.Rule("DIGIT")),
27
+ # RFC 3339
28
+ ("date-time", rfc3339.Rule("date-time")),
29
+ ]
30
+ )
31
+ class Rule(_Rule):
32
+ """Rules from EIP-4361."""
33
+
34
+ grammar: ClassVar[List] = [
35
+ 'sign-in-with-ethereum = [ scheme "://" ] domain %s" wants you to sign in with '
36
+ 'your Ethereum account:" LF address LF LF [ statement LF ] LF %s"URI: " uri LF '
37
+ '%s"Version: " version LF %s"Chain ID: " chain-id LF %s"Nonce: " nonce LF %s"'
38
+ 'Issued At: " issued-at [ LF %s"Expiration Time: " expiration-time ] [ LF %s"'
39
+ 'Not Before: " not-before ] [ LF %s"Request ID: " request-id ] [ LF %s"'
40
+ 'Resources:" resources ]',
41
+ "domain = authority",
42
+ 'address = "0x" 40HEXDIG',
43
+ 'statement = *( reserved / unreserved / " " )',
44
+ "uri = URI",
45
+ 'version = "1"',
46
+ "nonce = 8*( ALPHA / DIGIT )",
47
+ "issued-at = date-time",
48
+ "expiration-time = date-time",
49
+ "not-before = date-time",
50
+ "request-id = *pchar",
51
+ "chain-id = 1*DIGIT",
52
+ "resources = *( LF resource )",
53
+ 'resource = "- " URI',
54
+ ]
@@ -0,0 +1,34 @@
1
+ """Date ABNF definition."""
2
+
3
+ from typing import ClassVar, List
4
+
5
+ from abnf.grammars.misc import load_grammar_rules
6
+ from abnf.parser import Rule as _Rule
7
+
8
+ from . import rfc5234
9
+
10
+
11
+ @load_grammar_rules(
12
+ [
13
+ # RFC 5234
14
+ ("DIGIT", rfc5234.Rule("DIGIT")),
15
+ ]
16
+ )
17
+ class Rule(_Rule):
18
+ """Rules from RFC 3339."""
19
+
20
+ grammar: ClassVar[List] = [
21
+ "date-fullyear = 4DIGIT",
22
+ "date-month = 2DIGIT",
23
+ "date-mday = 2DIGIT",
24
+ "time-hour = 2DIGIT",
25
+ "time-minute = 2DIGIT",
26
+ "time-second = 2DIGIT",
27
+ 'time-secfrac = "." 1*DIGIT',
28
+ 'time-numoffset = ( "+" / "-" ) time-hour ":" time-minute',
29
+ 'time-offset = "Z" / time-numoffset',
30
+ 'partial-time = time-hour ":" time-minute ":" time-second [ time-secfrac ]',
31
+ 'full-date = date-fullyear "-" date-month "-" date-mday',
32
+ "full-time = partial-time time-offset",
33
+ 'date-time = full-date "T" full-time',
34
+ ]
@@ -0,0 +1,20 @@
1
+ """Primitive ABNF definition."""
2
+
3
+ from typing import ClassVar, List
4
+
5
+ from abnf.grammars.misc import load_grammar_rules
6
+ from abnf.parser import Rule as _Rule
7
+
8
+
9
+ @load_grammar_rules()
10
+ class Rule(_Rule):
11
+ """Rules from RFC 5234."""
12
+
13
+ grammar: ClassVar[List] = [
14
+ "ALPHA = %x41-5A / %x61-7A ; A-Z / a-z",
15
+ "LF = %x0A \
16
+ ; linefeed",
17
+ "DIGIT = %x30-39 \
18
+ ; 0-9",
19
+ 'HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"',
20
+ ]
siwe/parsed.py ADDED
@@ -0,0 +1,78 @@
1
+ """SIWE message parsers."""
2
+
3
+ import re
4
+
5
+ import abnf
6
+
7
+ from .defs import REGEX_MESSAGE
8
+ from .grammars import eip4361
9
+
10
+
11
+ class RegExpParsedMessage:
12
+ """Regex parsed SIWE message."""
13
+
14
+ def __init__(self, message: str):
15
+ """Parse a SIWE message."""
16
+ expr = re.compile(REGEX_MESSAGE)
17
+ match = re.match(REGEX_MESSAGE, message)
18
+
19
+ if not match:
20
+ raise ValueError("Message did not match the regular expression.")
21
+
22
+ self.scheme = match.group(expr.groupindex["scheme"])
23
+ self.domain = match.group(expr.groupindex["domain"])
24
+ self.address = match.group(expr.groupindex["address"])
25
+ self.statement = match.group(expr.groupindex["statement"])
26
+ self.uri = match.group(expr.groupindex["uri"])
27
+ self.version = match.group(expr.groupindex["version"])
28
+ self.nonce = match.group(expr.groupindex["nonce"])
29
+ self.chain_id = match.group(expr.groupindex["chainId"])
30
+ self.issued_at = match.group(expr.groupindex["issuedAt"])
31
+ self.expiration_time = match.group(expr.groupindex["expirationTime"])
32
+ self.not_before = match.group(expr.groupindex["notBefore"])
33
+ self.request_id = match.group(expr.groupindex["requestId"])
34
+ self.resources = match.group(expr.groupindex["resources"])
35
+ if self.resources is None:
36
+ pass
37
+ elif self.resources:
38
+ self.resources = self.resources.split("\n- ")[1:]
39
+ else:
40
+ self.resources = []
41
+
42
+
43
+ class ABNFParsedMessage:
44
+ """ABNF parsed SIWE message."""
45
+
46
+ def __init__(self, message: str):
47
+ """Parse a SIWE message."""
48
+ parser = eip4361.Rule("sign-in-with-ethereum")
49
+ try:
50
+ node = parser.parse_all(message)
51
+ except abnf.ParseError as e:
52
+ raise ValueError from e
53
+
54
+ for child in node.children:
55
+ if child.name in [
56
+ "scheme",
57
+ "domain",
58
+ "address",
59
+ "statement",
60
+ "uri",
61
+ "version",
62
+ "nonce",
63
+ "chain-id",
64
+ "issued-at",
65
+ "expiration-time",
66
+ "not-before",
67
+ "request-id",
68
+ "resources",
69
+ ]:
70
+ setattr(self, child.name.replace("-", "_"), child.value)
71
+
72
+ if child.name == "resources":
73
+ resources = []
74
+ for resource in child.children:
75
+ resources.extend(
76
+ [r.value for r in resource.children if r.name == "uri"]
77
+ )
78
+ self.resources = resources
siwe/siwe.py ADDED
@@ -0,0 +1,545 @@
1
+ """Main module for SIWE messages construction and validation."""
2
+
3
+ import secrets
4
+ import string
5
+ from datetime import datetime, timezone
6
+ from enum import Enum
7
+ from typing import Iterable, List, Optional
8
+
9
+ import abnf
10
+ from abnf.grammars import rfc3986
11
+ from eth_account.messages import SignableMessage, _hash_eip191_message, encode_defunct
12
+ from pydantic import (
13
+ BaseModel,
14
+ BeforeValidator,
15
+ Field,
16
+ NonNegativeInt,
17
+ field_validator,
18
+ model_validator,
19
+ )
20
+ from pydantic_core import core_schema
21
+ from typing_extensions import Annotated
22
+ from web3 import HTTPProvider, Web3
23
+ from web3.exceptions import BadFunctionCallOutput, ContractLogicError, Web3RPCError
24
+
25
+ from .grammars import eip4361
26
+ from .parsed import ABNFParsedMessage, RegExpParsedMessage
27
+
28
+ EIP1271_CONTRACT_ABI = [
29
+ {
30
+ "inputs": [
31
+ {"internalType": "bytes32", "name": "_message", "type": "bytes32"},
32
+ {"internalType": "bytes", "name": "_signature", "type": "bytes"},
33
+ ],
34
+ "name": "isValidSignature",
35
+ "outputs": [{"internalType": "bytes4", "name": "", "type": "bytes4"}],
36
+ "stateMutability": "view",
37
+ "type": "function",
38
+ }
39
+ ]
40
+ EIP1271_MAGICVALUE = "1626ba7e"
41
+
42
+ # 32-byte magic suffix appended to EIP-6492 wrapped signatures
43
+ EIP6492_MAGIC_SUFFIX = (
44
+ "6492649264926492649264926492649264926492649264926492649264926492"
45
+ )
46
+
47
+ # Deployment bytecode for the off-chain universal signature validator.
48
+ # Used via eth_call (no actual deployment) to verify EOA, ERC-1271,
49
+ # and EIP-6492 signatures in a single call.
50
+ # Source: EIP-6492 reference implementation
51
+ EIP6492_VALIDATOR_BYTECODE = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572" # noqa: E501
52
+
53
+
54
+ def is_eip6492_signature(signature: str) -> bool:
55
+ """Check if a hex-encoded signature ends with the EIP-6492 magic suffix."""
56
+ if not isinstance(signature, str):
57
+ return False
58
+ sig = signature[2:] if signature.startswith("0x") else signature
59
+ return len(sig) >= 64 and sig.endswith(EIP6492_MAGIC_SUFFIX)
60
+
61
+
62
+ _ALPHANUMERICS = string.ascii_letters + string.digits
63
+
64
+
65
+ def generate_nonce() -> str:
66
+ """Generate a cryptographically sound nonce."""
67
+ return "".join(secrets.choice(_ALPHANUMERICS) for _ in range(17))
68
+
69
+
70
+ class VerificationError(Exception):
71
+ """Top-level validation and verification exception."""
72
+
73
+ pass
74
+
75
+
76
+ class InvalidSignature(VerificationError):
77
+ """The signature does not match the message."""
78
+
79
+ pass
80
+
81
+
82
+ class ExpiredMessage(VerificationError):
83
+ """The message is not valid any more."""
84
+
85
+ pass
86
+
87
+
88
+ class NotYetValidMessage(VerificationError):
89
+ """The message is not yet valid."""
90
+
91
+ pass
92
+
93
+
94
+ class SchemeMismatch(VerificationError):
95
+ """The message does not contain the expected scheme."""
96
+
97
+ pass
98
+
99
+
100
+ class DomainMismatch(VerificationError):
101
+ """The message does not contain the expected domain."""
102
+
103
+ pass
104
+
105
+
106
+ class NonceMismatch(VerificationError):
107
+ """The message does not contain the expected nonce."""
108
+
109
+ pass
110
+
111
+
112
+ class UriMismatch(VerificationError):
113
+ """The message does not contain the expected URI."""
114
+
115
+ pass
116
+
117
+
118
+ class ChainIdMismatch(VerificationError):
119
+ """The message does not contain the expected chain ID."""
120
+
121
+ pass
122
+
123
+
124
+ class RequestIdMismatch(VerificationError):
125
+ """The message does not contain the expected request ID."""
126
+
127
+ pass
128
+
129
+
130
+ class MalformedSession(VerificationError):
131
+ """A message could not be constructed as it is missing certain fields."""
132
+
133
+ def __init__(self, missing_fields: Iterable[str]):
134
+ """Construct the exception with the missing fields."""
135
+ self.missing_fields = missing_fields
136
+
137
+
138
+ class VersionEnum(str, Enum):
139
+ """EIP-4361 versions."""
140
+
141
+ one = "1"
142
+
143
+ def __str__(self):
144
+ """EIP-4361 representation of the enum field."""
145
+ return self.value
146
+
147
+
148
+ def _validate_rfc3986_uri(value: str) -> str:
149
+ """Validate a URI string per RFC 3986."""
150
+ try:
151
+ rfc3986.Rule("URI").parse_all(value)
152
+ except abnf.ParseError as err:
153
+ raise ValueError(f"Invalid URI: {value}") from err
154
+ return value
155
+
156
+
157
+ def _validate_eip4361_rule(rule_name: str, value: str) -> str:
158
+ """Validate a string against an EIP-4361 ABNF rule."""
159
+ try:
160
+ eip4361.Rule(rule_name).parse_all(value)
161
+ except abnf.ParseError as err:
162
+ raise ValueError(f"Invalid {rule_name}: {value}") from err
163
+ return value
164
+
165
+
166
+ AnyUrlStr = Annotated[str, BeforeValidator(_validate_rfc3986_uri)]
167
+
168
+
169
+ def datetime_from_iso8601_string(val: str) -> datetime:
170
+ """Convert an ISO-8601 Datetime string into a valid datetime object."""
171
+ _validate_eip4361_rule("issued-at", val)
172
+ return datetime.fromisoformat(val.replace(".000Z", "Z").replace("Z", "+00:00"))
173
+
174
+
175
+ # NOTE: Do not override the original string, but ensure we do timestamp validation
176
+ class ISO8601Datetime(str):
177
+ """A special field class used to denote ISO-8601 Datetime strings."""
178
+
179
+ def __init__(self, val: str):
180
+ """Validate ISO-8601 string."""
181
+ # NOTE: `self` is already this class, we are just running our validation here
182
+ datetime_from_iso8601_string(val)
183
+
184
+ @classmethod
185
+ def __get_pydantic_core_schema__(cls, source, handler):
186
+ """Create valid pydantic schema object for this type."""
187
+ return core_schema.no_info_after_validator_function(
188
+ cls, core_schema.str_schema()
189
+ )
190
+
191
+ @classmethod
192
+ def from_datetime(
193
+ cls, dt: datetime, timespec: str = "milliseconds"
194
+ ) -> "ISO8601Datetime":
195
+ """Create an ISO-8601 formatted string from a datetime object."""
196
+ # NOTE: Only a useful classmethod for creating these objects
197
+ return ISO8601Datetime(
198
+ dt.astimezone(tz=timezone.utc)
199
+ .isoformat(timespec=timespec)
200
+ .replace("+00:00", "Z")
201
+ )
202
+
203
+ @property
204
+ def _datetime(self) -> datetime:
205
+ return datetime_from_iso8601_string(self)
206
+
207
+
208
+ def utc_now() -> datetime:
209
+ """Get the current datetime as UTC timezone."""
210
+ return datetime.now(tz=timezone.utc)
211
+
212
+
213
+ class SiweMessage(BaseModel):
214
+ """A Sign-in with Ethereum (EIP-4361) message."""
215
+
216
+ scheme: Optional[str] = Field(None, pattern=r"^[a-zA-Z][a-zA-Z0-9+\-.]*$")
217
+ """RFC 3986 URI scheme for the authority that is requesting the signing."""
218
+ domain: str = Field(pattern=r"^[^\s/?#]+$")
219
+ """RFC 4501 dns authority that is requesting the signing."""
220
+ address: str
221
+ """Ethereum address performing the signing conformant to capitalization encoded
222
+ checksum specified in EIP-55 where applicable.
223
+ """
224
+ uri: AnyUrlStr
225
+ """RFC 3986 URI referring to the resource that is the subject of the signing."""
226
+ version: VersionEnum
227
+ """Current version of the message."""
228
+ chain_id: NonNegativeInt
229
+ """EIP-155 Chain ID to which the session is bound, and the network where Contract
230
+ Accounts must be resolved.
231
+ """
232
+ issued_at: ISO8601Datetime
233
+ """ISO 8601 datetime string of the current time."""
234
+ nonce: str = Field(min_length=8, pattern="^[a-zA-Z0-9]+$")
235
+ """Randomized token used to prevent replay attacks, at least 8 alphanumeric
236
+ characters. Use generate_nonce() to generate a secure nonce and store it for
237
+ verification later.
238
+ """
239
+ statement: Optional[str] = None
240
+ """Human-readable ASCII assertion that the user will sign, and it must not contain
241
+ `\n`.
242
+ """
243
+ expiration_time: Optional[ISO8601Datetime] = None
244
+ """ISO 8601 datetime string that, if present, indicates when the signed
245
+ authentication message is no longer valid.
246
+ """
247
+ not_before: Optional[ISO8601Datetime] = None
248
+ """ISO 8601 datetime string that, if present, indicates when the signed
249
+ authentication message will become valid.
250
+ """
251
+ request_id: Optional[str] = None
252
+ """System-specific identifier that may be used to uniquely refer to the sign-in
253
+ request.
254
+ """
255
+ resources: Optional[List[AnyUrlStr]] = None
256
+ """List of information or references to information the user wishes to have resolved
257
+ as part of authentication by the relying party. They are expressed as RFC 3986 URIs
258
+ separated by `\n- `.
259
+ """
260
+ warnings: List[str] = Field(default_factory=list, exclude=True)
261
+ """Non-fatal warnings from validation (e.g. unchecksummed address)."""
262
+
263
+ @field_validator("address")
264
+ @classmethod
265
+ def validate_address(cls, v: str) -> str:
266
+ """Validate the address is well-formed hex with a correct EIP-55 checksum.
267
+
268
+ All-lowercase and all-uppercase addresses are accepted (they are valid
269
+ but unchecksummed — a warning is added by the model validator). Mixed-
270
+ case addresses must pass the EIP-55 checksum or they are rejected.
271
+ """
272
+ if len(v) != 42 or not v.startswith("0x"):
273
+ raise ValueError(f"Invalid Ethereum address format: {v}")
274
+ hex_part = v[2:]
275
+ if not all(c in "0123456789abcdefABCDEF" for c in hex_part):
276
+ raise ValueError(f"Invalid Ethereum address: non-hex characters: {v}")
277
+ if (
278
+ hex_part != hex_part.lower()
279
+ and hex_part != hex_part.upper()
280
+ and not Web3.is_checksum_address(v)
281
+ ):
282
+ raise ValueError("invalid EIP-55 address")
283
+ return v
284
+
285
+ @field_validator("statement")
286
+ @classmethod
287
+ def validate_statement(cls, v: Optional[str]) -> Optional[str]:
288
+ """Validate statement using the EIP-4361 grammar."""
289
+ if v is not None:
290
+ _validate_eip4361_rule("statement", v)
291
+ return v
292
+
293
+ @field_validator("request_id")
294
+ @classmethod
295
+ def validate_request_id(cls, v: Optional[str]) -> Optional[str]:
296
+ """Validate request ID using the EIP-4361 grammar."""
297
+ if v is not None:
298
+ _validate_eip4361_rule("request-id", v)
299
+ return v
300
+
301
+ @model_validator(mode="after")
302
+ def _check_address_warnings(self) -> "SiweMessage":
303
+ """Add a warning when the address is not EIP-55 checksummed."""
304
+ hex_part = self.address[2:]
305
+ if (
306
+ hex_part == hex_part.lower() or hex_part == hex_part.upper()
307
+ ) and not Web3.is_checksum_address(self.address):
308
+ self.warnings.append(
309
+ f"Address is not EIP-55 checksummed: {self.address}"
310
+ )
311
+ return self
312
+
313
+ @classmethod
314
+ def from_message(cls, message: str, abnf: bool = True) -> "SiweMessage":
315
+ """Parse a message in its EIP-4361 format."""
316
+ if abnf:
317
+ parsed_message = ABNFParsedMessage(message=message)
318
+ else:
319
+ parsed_message = RegExpParsedMessage(message=message)
320
+
321
+ # TODO There is some redundancy in the checks when deserialising a message.
322
+ return cls(**parsed_message.__dict__)
323
+
324
+ def prepare_message(self) -> str:
325
+ """Serialize to the EIP-4361 format for signing.
326
+
327
+ It can then be passed to an EIP-191 signing function.
328
+
329
+ :return: EIP-4361 formatted message, ready for EIP-191 signing.
330
+ """
331
+ header = f"{self.domain} wants you to sign in with your Ethereum account:"
332
+ if self.scheme:
333
+ header = f"{self.scheme}://{header}"
334
+
335
+ uri_field = f"URI: {self.uri}"
336
+
337
+ prefix = "\n".join([header, self.address])
338
+
339
+ version_field = f"Version: {self.version}"
340
+
341
+ chain_field = f"Chain ID: {self.chain_id}"
342
+
343
+ nonce_field = f"Nonce: {self.nonce}"
344
+
345
+ suffix_array = [uri_field, version_field, chain_field, nonce_field]
346
+
347
+ issued_at_field = f"Issued At: {self.issued_at}"
348
+ suffix_array.append(issued_at_field)
349
+
350
+ if self.expiration_time:
351
+ expiration_time_field = f"Expiration Time: {self.expiration_time}"
352
+ suffix_array.append(expiration_time_field)
353
+
354
+ if self.not_before:
355
+ not_before_field = f"Not Before: {self.not_before}"
356
+ suffix_array.append(not_before_field)
357
+
358
+ if self.request_id is not None:
359
+ request_id_field = f"Request ID: {self.request_id}"
360
+ suffix_array.append(request_id_field)
361
+
362
+ if self.resources is not None:
363
+ resources_field = "\n".join(
364
+ ["Resources:"] + [f"- {resource}" for resource in self.resources]
365
+ )
366
+ suffix_array.append(resources_field)
367
+
368
+ suffix = "\n".join(suffix_array)
369
+
370
+ if self.statement is not None:
371
+ prefix = "\n\n".join([prefix, self.statement])
372
+ else:
373
+ prefix += "\n"
374
+
375
+ return "\n\n".join([prefix, suffix])
376
+
377
+ def verify(
378
+ self,
379
+ signature: Optional[str],
380
+ *,
381
+ scheme: Optional[str] = None,
382
+ domain: Optional[str] = None,
383
+ nonce: Optional[str] = None,
384
+ uri: Optional[str] = None,
385
+ chain_id: Optional[int] = None,
386
+ request_id: Optional[str] = None,
387
+ timestamp: Optional[datetime] = None,
388
+ provider: Optional[HTTPProvider] = None,
389
+ strict: bool = False,
390
+ ) -> None:
391
+ """Verify the validity of the message and its signature.
392
+
393
+ :param signature: Signature to check against the current message.
394
+ :param scheme: Scheme expected to be in the current message.
395
+ :param domain: Domain expected to be in the current message.
396
+ :param nonce: Nonce expected to be in the current message.
397
+ :param uri: URI expected to be in the current message.
398
+ :param chain_id: Chain ID expected to be in the current message.
399
+ :param request_id: Request ID expected to be in the current message.
400
+ :param timestamp: Timestamp used to verify the expiry date and other dates
401
+ fields. Uses the current time by default.
402
+ :param provider: A Web3 provider able to perform a contract check. This is
403
+ required if support for Smart Contract Wallets that implement EIP-1271 or
404
+ EIP-6492 is needed.
405
+ :param strict: When True, requires uri and chain_id parameters to be provided.
406
+ :return: None if the message is valid and raises an exception otherwise
407
+ """
408
+ if strict:
409
+ if uri is None:
410
+ raise VerificationError("Strict mode requires uri parameter")
411
+ if chain_id is None:
412
+ raise VerificationError("Strict mode requires chain_id parameter")
413
+ if domain is None:
414
+ raise VerificationError("Strict mode requires domain parameter")
415
+
416
+ message = encode_defunct(text=self.prepare_message())
417
+ w3 = Web3(provider=provider)
418
+
419
+ if scheme is not None and self.scheme != scheme:
420
+ raise SchemeMismatch()
421
+ if domain is not None and self.domain != domain:
422
+ raise DomainMismatch()
423
+ if nonce is not None and self.nonce != nonce:
424
+ raise NonceMismatch()
425
+ if uri is not None and str(self.uri) != uri:
426
+ raise UriMismatch()
427
+ if chain_id is not None and self.chain_id != chain_id:
428
+ raise ChainIdMismatch()
429
+ if request_id is not None and self.request_id != request_id:
430
+ raise RequestIdMismatch()
431
+
432
+ if timestamp is None:
433
+ verification_time = utc_now()
434
+ else:
435
+ verification_time = timestamp
436
+ if verification_time.tzinfo is None:
437
+ verification_time = verification_time.replace(tzinfo=timezone.utc)
438
+ if (
439
+ self.expiration_time is not None
440
+ and verification_time >= self.expiration_time._datetime
441
+ ):
442
+ raise ExpiredMessage()
443
+ if (
444
+ self.not_before is not None
445
+ and verification_time < self.not_before._datetime
446
+ ):
447
+ raise NotYetValidMessage()
448
+
449
+ try:
450
+ address = w3.eth.account.recover_message(message, signature=signature)
451
+ except Exception:
452
+ # Any exception from recover_message (wrong length, bad hex, bad
453
+ # v/r/s, wrong type, None, etc.) means the signature cannot be
454
+ # validated as an EOA signature — fall through to EIP-1271/6492.
455
+ address = None
456
+
457
+ if (address is None or address.lower() != self.address.lower()) and (
458
+ provider is None
459
+ or not check_contract_wallet_signature(
460
+ address=self.address,
461
+ message=message,
462
+ signature=signature,
463
+ chain_id=self.chain_id,
464
+ w3=w3,
465
+ )
466
+ ):
467
+ raise InvalidSignature()
468
+
469
+
470
+ def check_contract_wallet_signature(
471
+ address: str,
472
+ message: SignableMessage,
473
+ signature: str,
474
+ chain_id: int,
475
+ w3: Web3,
476
+ ) -> bool:
477
+ """Verify a signature via EIP-1271 or EIP-6492.
478
+
479
+ :param address: The address of the contract
480
+ :param message: The EIP-4361 formatted message
481
+ :param signature: The EIP-1271 or EIP-6492 signature
482
+ :param chain_id: The chain ID from the SIWE message
483
+ :param w3: A Web3 provider able to perform a contract check.
484
+ :return: True if the signature is valid per EIP-1271/EIP-6492.
485
+ """
486
+ try:
487
+ provider_chain_id = w3.eth.chain_id
488
+ except Web3RPCError:
489
+ raise InvalidSignature(
490
+ "Unable to verify contract wallet signature: RPC error"
491
+ ) from None
492
+ if provider_chain_id != chain_id:
493
+ raise ChainIdMismatch(
494
+ f"Provider chain ID {provider_chain_id} does not match "
495
+ f"message chain ID {chain_id}"
496
+ )
497
+
498
+ hash_ = _hash_eip191_message(message)
499
+
500
+ if is_eip6492_signature(signature):
501
+ return _check_eip6492_signature(address, hash_, signature, w3)
502
+
503
+ return _check_eip1271_signature(address, hash_, signature, w3)
504
+
505
+
506
+ def _check_eip6492_signature(
507
+ address: str, hash_: bytes, signature: str, w3: Web3
508
+ ) -> bool:
509
+ """Verify an EIP-6492 signature using the universal validator bytecode."""
510
+ try:
511
+ raw = signature[2:] if signature.startswith("0x") else signature
512
+ sig_bytes = bytes.fromhex(raw)
513
+ except (AttributeError, TypeError, ValueError):
514
+ return False
515
+ encoded = w3.codec.encode(
516
+ ["address", "bytes32", "bytes"],
517
+ [Web3.to_checksum_address(address), hash_, sig_bytes],
518
+ )
519
+ data = bytes.fromhex(EIP6492_VALIDATOR_BYTECODE[2:]) + encoded
520
+ try:
521
+ result = w3.eth.call({"data": "0x" + data.hex()})
522
+ return result[-1:] == b"\x01"
523
+ except (BadFunctionCallOutput, ContractLogicError, Web3RPCError):
524
+ return False
525
+
526
+
527
+ def _check_eip1271_signature(
528
+ address: str, hash_: bytes, signature: str, w3: Web3
529
+ ) -> bool:
530
+ """Verify an EIP-1271 signature via isValidSignature contract call."""
531
+ try:
532
+ # For message hashes stored on-chain for Safe wallets, the signatures
533
+ # are always "0x" and should be passed in as-is.
534
+ raw = signature[2:] if signature.startswith("0x") else signature
535
+ sig_bytes = signature if signature == "0x" else bytes.fromhex(raw)
536
+ except (AttributeError, TypeError, ValueError):
537
+ return False
538
+ contract = w3.eth.contract(
539
+ address=Web3.to_checksum_address(address), abi=EIP1271_CONTRACT_ABI
540
+ )
541
+ try:
542
+ response = contract.caller.isValidSignature(hash_, sig_bytes)
543
+ return response.hex() == EIP1271_MAGICVALUE
544
+ except (BadFunctionCallOutput, ContractLogicError, Web3RPCError):
545
+ return False