xian-tech-linter 0.3.1__tar.gz

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,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: xian-tech-linter
3
+ Version: 0.3.1
4
+ Summary: Smart contract linter for the Xian blockchain
5
+ Author-email: Xian Network <info@xian.org>
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: pyflakes<4,>=3.2
9
+ Requires-Dist: pydantic<3,>=2
10
+ Requires-Dist: xian-tech-contracting<2,>=1.0.1
11
+ Provides-Extra: server
12
+ Requires-Dist: fastapi<1,>=0.115.6; extra == "server"
13
+ Requires-Dist: uvicorn<1,>=0.34; extra == "server"
14
+
15
+ # xian-linter
16
+
17
+ `xian-linter` is a Python linter specifically for Xian smart contracts. It
18
+ combines PyFlakes with the structured linter exposed by `xian-contracting`, so
19
+ rule violations include stable error codes and source positions.
20
+
21
+ The published PyPI package name is `xian-tech-linter`. The import package and
22
+ console command remain `xian_linter` and `xian-linter`.
23
+
24
+ ## Quick Start
25
+
26
+ Base package:
27
+
28
+ ```bash
29
+ pip install xian-tech-linter
30
+ ```
31
+
32
+ Inline use:
33
+
34
+ ```python
35
+ from xian_linter import lint_code_inline
36
+
37
+ errors = lint_code_inline("def transfer():\n pass\n")
38
+ ```
39
+
40
+ ## Principles
41
+
42
+ - Keep the package focused on contract linting, not runtime execution.
43
+ - Expose the same rule surface in both inline and server modes.
44
+ - Prefer stable error codes and positions so tooling can build on top of the
45
+ linter reliably.
46
+ - Keep server mode optional. The core package should still be useful as a local
47
+ linting dependency.
48
+
49
+ ## Key Directories
50
+
51
+ - `xian_linter/`: package code, server entrypoints, and inline API
52
+ - `tests/`: package and server-mode coverage
53
+ - `docs/`: repo-local notes and backlog
54
+
55
+ ## Validation
56
+
57
+ ```bash
58
+ uv sync --group dev
59
+ uv run ruff check .
60
+ uv run ruff format --check .
61
+ uv run pytest
62
+ ```
63
+
64
+ ## Related Docs
65
+
66
+ - [AGENTS.md](AGENTS.md)
67
+ - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
68
+ - [docs/BACKLOG.md](docs/BACKLOG.md)
69
+ - [docs/README.md](docs/README.md)
70
+
71
+ ## Usage Modes
72
+
73
+ - Inline/programmatic usage:
74
+
75
+ ```python
76
+ from xian_linter import lint_code_inline
77
+
78
+ errors = lint_code_inline("def transfer():\n pass\n")
79
+ ```
80
+
81
+ - Standalone server mode:
82
+
83
+ ```bash
84
+ pip install "xian-tech-linter[server]"
85
+ xian-linter
86
+ uvicorn xian_linter.server:create_app --factory --host 0.0.0.0 --port 8000
87
+ ```
@@ -0,0 +1,73 @@
1
+ # xian-linter
2
+
3
+ `xian-linter` is a Python linter specifically for Xian smart contracts. It
4
+ combines PyFlakes with the structured linter exposed by `xian-contracting`, so
5
+ rule violations include stable error codes and source positions.
6
+
7
+ The published PyPI package name is `xian-tech-linter`. The import package and
8
+ console command remain `xian_linter` and `xian-linter`.
9
+
10
+ ## Quick Start
11
+
12
+ Base package:
13
+
14
+ ```bash
15
+ pip install xian-tech-linter
16
+ ```
17
+
18
+ Inline use:
19
+
20
+ ```python
21
+ from xian_linter import lint_code_inline
22
+
23
+ errors = lint_code_inline("def transfer():\n pass\n")
24
+ ```
25
+
26
+ ## Principles
27
+
28
+ - Keep the package focused on contract linting, not runtime execution.
29
+ - Expose the same rule surface in both inline and server modes.
30
+ - Prefer stable error codes and positions so tooling can build on top of the
31
+ linter reliably.
32
+ - Keep server mode optional. The core package should still be useful as a local
33
+ linting dependency.
34
+
35
+ ## Key Directories
36
+
37
+ - `xian_linter/`: package code, server entrypoints, and inline API
38
+ - `tests/`: package and server-mode coverage
39
+ - `docs/`: repo-local notes and backlog
40
+
41
+ ## Validation
42
+
43
+ ```bash
44
+ uv sync --group dev
45
+ uv run ruff check .
46
+ uv run ruff format --check .
47
+ uv run pytest
48
+ ```
49
+
50
+ ## Related Docs
51
+
52
+ - [AGENTS.md](AGENTS.md)
53
+ - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
54
+ - [docs/BACKLOG.md](docs/BACKLOG.md)
55
+ - [docs/README.md](docs/README.md)
56
+
57
+ ## Usage Modes
58
+
59
+ - Inline/programmatic usage:
60
+
61
+ ```python
62
+ from xian_linter import lint_code_inline
63
+
64
+ errors = lint_code_inline("def transfer():\n pass\n")
65
+ ```
66
+
67
+ - Standalone server mode:
68
+
69
+ ```bash
70
+ pip install "xian-tech-linter[server]"
71
+ xian-linter
72
+ uvicorn xian_linter.server:create_app --factory --host 0.0.0.0 --port 8000
73
+ ```
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "xian-tech-linter"
7
+ version = "0.3.1"
8
+ description = "Smart contract linter for the Xian blockchain"
9
+ readme = "README.md"
10
+ authors = [{ name = "Xian Network", email = "info@xian.org" }]
11
+ requires-python = ">=3.12"
12
+ dependencies = [
13
+ "pyflakes>=3.2,<4",
14
+ "pydantic>=2,<3",
15
+ "xian-tech-contracting>=1.0.1,<2",
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ server = [
20
+ "fastapi>=0.115.6,<1",
21
+ "uvicorn>=0.34,<1",
22
+ ]
23
+
24
+ [project.scripts]
25
+ xian-linter = "xian_linter.server:run_server"
26
+
27
+ [dependency-groups]
28
+ dev = [
29
+ "pytest>=9.0.2,<10",
30
+ "ruff>=0.15.6,<0.16",
31
+ ]
32
+
33
+ [tool.uv.sources]
34
+ xian-tech-contracting = { path = "../xian-contracting", editable = true }
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["."]
38
+
39
+ [tool.ruff]
40
+ line-length = 80
41
+ target-version = "py312"
42
+ exclude = ["contract.py", "contract.py.b64", "contract.py.gz"]
43
+
44
+ [tool.ruff.lint]
45
+ select = ["E", "F", "I"]
46
+ ignore = ["E501"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,35 @@
1
+ from xian_linter import lint_code_inline
2
+
3
+
4
+ def test_inline_contracting_error_is_structured():
5
+ errors = lint_code_inline(
6
+ """
7
+ class Bad:
8
+ pass
9
+ """
10
+ )
11
+ assert errors
12
+ assert any(error.code == "E006" for error in errors)
13
+ assert any(error.position is not None for error in errors)
14
+
15
+
16
+ def test_pyflakes_warning_survives_merge():
17
+ errors = lint_code_inline(
18
+ """
19
+ @export
20
+ def f(x: int):
21
+ return missing_name
22
+ """
23
+ )
24
+ assert any(error.code == "W001" for error in errors)
25
+
26
+
27
+ def test_runtime_zk_name_is_whitelisted():
28
+ errors = lint_code_inline(
29
+ """
30
+ @export
31
+ def verify(vk_id: str, proof_hex: str, public_inputs: list):
32
+ return zk.verify_groth16(vk_id, proof_hex, public_inputs)
33
+ """
34
+ )
35
+ assert not any(error.code == "W001" for error in errors)
@@ -0,0 +1,3 @@
1
+ from .linter import lint_code_inline
2
+
3
+ __all__ = ["lint_code_inline"]
@@ -0,0 +1,4 @@
1
+ from xian_linter.server import run_server
2
+
3
+ if __name__ == "__main__":
4
+ run_server()
@@ -0,0 +1,179 @@
1
+ """Xian smart-contract linter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import re
7
+ from functools import lru_cache
8
+ from io import StringIO
9
+ from typing import Iterable
10
+
11
+ from contracting.compilation.linter import (
12
+ Linter as ContractingLinter,
13
+ )
14
+ from contracting.compilation.linter import (
15
+ LintError as ContractingLintError,
16
+ )
17
+ from pydantic import BaseModel
18
+ from pyflakes.api import check as pyflakes_check
19
+ from pyflakes.reporter import Reporter
20
+
21
+ MAX_CODE_SIZE = 1_000_000
22
+
23
+ DEFAULT_WHITELIST = frozenset(
24
+ {
25
+ "Any",
26
+ "ForeignHash",
27
+ "ForeignVariable",
28
+ "Hash",
29
+ "LogEvent",
30
+ "Variable",
31
+ "block_hash",
32
+ "block_num",
33
+ "chain_id",
34
+ "construct",
35
+ "crypto",
36
+ "ctx",
37
+ "datetime",
38
+ "decimal",
39
+ "export",
40
+ "hashlib",
41
+ "importlib",
42
+ "now",
43
+ "random",
44
+ "zk",
45
+ }
46
+ )
47
+
48
+
49
+ class PositionModel(BaseModel):
50
+ line: int
51
+ col: int
52
+ end_line: int
53
+ end_col: int
54
+
55
+
56
+ class LintErrorModel(BaseModel):
57
+ code: str
58
+ message: str
59
+ severity: str = "error"
60
+ position: PositionModel | None = None
61
+
62
+
63
+ class LintResponse(BaseModel):
64
+ success: bool
65
+ errors: list[LintErrorModel]
66
+
67
+
68
+ def _contracting_to_model(error: ContractingLintError) -> LintErrorModel:
69
+ return LintErrorModel(
70
+ code=error.code.value,
71
+ message=error.message,
72
+ position=PositionModel(
73
+ line=error.line,
74
+ col=error.col,
75
+ end_line=error.end_line,
76
+ end_col=error.end_col,
77
+ ),
78
+ )
79
+
80
+
81
+ _PYFLAKES_PATTERN = re.compile(r"<string>:(\d+):(\d+):\s*(.+)")
82
+
83
+
84
+ def _parse_pyflakes(output: str, whitelist: frozenset[str]):
85
+ errors = []
86
+ for line in output.splitlines():
87
+ line = line.strip()
88
+ if not line:
89
+ continue
90
+ match = _PYFLAKES_PATTERN.match(line)
91
+ if not match:
92
+ continue
93
+ lineno, col, message = (
94
+ int(match.group(1)),
95
+ int(match.group(2)),
96
+ match.group(3),
97
+ )
98
+ if any(pattern in message for pattern in whitelist):
99
+ continue
100
+ errors.append(
101
+ LintErrorModel(
102
+ code="W001",
103
+ message=message,
104
+ severity="warning",
105
+ position=PositionModel(
106
+ line=lineno,
107
+ col=col - 1,
108
+ end_line=lineno,
109
+ end_col=col - 1,
110
+ ),
111
+ )
112
+ )
113
+ return errors
114
+
115
+
116
+ def _run_contracting(code: str):
117
+ linter = ContractingLinter()
118
+ errors = linter.check(code)
119
+ if not errors:
120
+ return []
121
+ return [_contracting_to_model(error) for error in errors]
122
+
123
+
124
+ def _run_pyflakes(code: str, whitelist: frozenset[str]):
125
+ stdout = StringIO()
126
+ stderr = StringIO()
127
+ reporter = Reporter(stdout, stderr)
128
+ pyflakes_check(code, "<string>", reporter)
129
+ return _parse_pyflakes(stdout.getvalue() + stderr.getvalue(), whitelist)
130
+
131
+
132
+ async def lint_code(code: str, whitelist: frozenset[str] | None = None):
133
+ whitelist = whitelist or DEFAULT_WHITELIST
134
+ loop = asyncio.get_running_loop()
135
+ contracting_task = loop.run_in_executor(None, _run_contracting, code)
136
+ pyflakes_task = loop.run_in_executor(None, _run_pyflakes, code, whitelist)
137
+ contracting_errors, pyflakes_errors = await asyncio.gather(
138
+ contracting_task,
139
+ pyflakes_task,
140
+ )
141
+ errors = contracting_errors + pyflakes_errors
142
+ errors.sort(
143
+ key=lambda error: (
144
+ error.position.line if error.position else 0,
145
+ error.position.col if error.position else 0,
146
+ )
147
+ )
148
+ return errors
149
+
150
+
151
+ def lint_code_sync(code: str, whitelist: frozenset[str] | None = None):
152
+ whitelist = whitelist or DEFAULT_WHITELIST
153
+ errors = _run_contracting(code) + _run_pyflakes(code, whitelist)
154
+ errors.sort(
155
+ key=lambda error: (
156
+ error.position.line if error.position else 0,
157
+ error.position.col if error.position else 0,
158
+ )
159
+ )
160
+ return errors
161
+
162
+
163
+ def lint_code_inline(
164
+ code: str,
165
+ whitelist_patterns: Iterable[str] | None = None,
166
+ ):
167
+ whitelist = (
168
+ frozenset(whitelist_patterns)
169
+ if whitelist_patterns is not None
170
+ else DEFAULT_WHITELIST
171
+ )
172
+ return lint_code_sync(code, whitelist)
173
+
174
+
175
+ @lru_cache(maxsize=100)
176
+ def get_whitelist_patterns(patterns_str: str | None = None):
177
+ if not patterns_str:
178
+ return DEFAULT_WHITELIST
179
+ return frozenset(patterns_str.split(","))
@@ -0,0 +1,134 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import gzip
5
+
6
+ from .linter import (
7
+ MAX_CODE_SIZE,
8
+ LintErrorModel,
9
+ LintResponse,
10
+ get_whitelist_patterns,
11
+ lint_code,
12
+ )
13
+
14
+
15
+ def _load_server_dependencies():
16
+ try:
17
+ import uvicorn
18
+ from fastapi import FastAPI, HTTPException, Request
19
+ except ImportError as exc:
20
+ raise RuntimeError(
21
+ "Install xian-linter with the 'server' extra to run the HTTP service."
22
+ ) from exc
23
+
24
+ return FastAPI, HTTPException, Request, uvicorn
25
+
26
+
27
+ def create_app():
28
+ FastAPI, HTTPException, Request, _ = _load_server_dependencies()
29
+ app = FastAPI(title="Xian Contract Linter")
30
+
31
+ @app.post("/lint_base64")
32
+ async def lint_base64(request: Request) -> LintResponse:
33
+ raw_data = await request.body()
34
+
35
+ if not raw_data:
36
+ raise HTTPException(status_code=400, detail="Empty request body")
37
+ if len(raw_data) > MAX_CODE_SIZE:
38
+ raise HTTPException(status_code=400, detail="Code size too large")
39
+
40
+ whitelist = get_whitelist_patterns(
41
+ request.query_params.get("whitelist_patterns")
42
+ )
43
+
44
+ try:
45
+ code = base64.b64decode(
46
+ raw_data.decode("utf-8", errors="replace")
47
+ ).decode("utf-8", errors="replace")
48
+ if not code.strip():
49
+ raise HTTPException(status_code=400, detail="Empty code")
50
+ errors = await lint_code(code, whitelist)
51
+ return LintResponse(success=len(errors) == 0, errors=errors)
52
+ except HTTPException:
53
+ raise
54
+ except Exception as exc:
55
+ return LintResponse(
56
+ success=False,
57
+ errors=[
58
+ LintErrorModel(
59
+ code="E000",
60
+ message=f"Processing error: {exc}",
61
+ )
62
+ ],
63
+ )
64
+
65
+ @app.post("/lint_gzip")
66
+ async def lint_gzip(request: Request) -> LintResponse:
67
+ raw_data = await request.body()
68
+
69
+ if not raw_data:
70
+ raise HTTPException(status_code=400, detail="Empty request body")
71
+ if len(raw_data) > MAX_CODE_SIZE:
72
+ raise HTTPException(status_code=400, detail="Code size too large")
73
+
74
+ whitelist = get_whitelist_patterns(
75
+ request.query_params.get("whitelist_patterns")
76
+ )
77
+
78
+ try:
79
+ code = gzip.decompress(raw_data).decode("utf-8", errors="replace")
80
+ if not code.strip():
81
+ raise HTTPException(status_code=400, detail="Empty code")
82
+ errors = await lint_code(code, whitelist)
83
+ return LintResponse(success=len(errors) == 0, errors=errors)
84
+ except HTTPException:
85
+ raise
86
+ except Exception as exc:
87
+ return LintResponse(
88
+ success=False,
89
+ errors=[
90
+ LintErrorModel(
91
+ code="E000",
92
+ message=f"Processing error: {exc}",
93
+ )
94
+ ],
95
+ )
96
+
97
+ @app.post("/lint")
98
+ async def lint_raw(request: Request) -> LintResponse:
99
+ raw_data = await request.body()
100
+
101
+ if not raw_data:
102
+ raise HTTPException(status_code=400, detail="Empty request body")
103
+ if len(raw_data) > MAX_CODE_SIZE:
104
+ raise HTTPException(status_code=400, detail="Code size too large")
105
+
106
+ whitelist = get_whitelist_patterns(
107
+ request.query_params.get("whitelist_patterns")
108
+ )
109
+
110
+ try:
111
+ code = raw_data.decode("utf-8", errors="replace")
112
+ if not code.strip():
113
+ raise HTTPException(status_code=400, detail="Empty code")
114
+ errors = await lint_code(code, whitelist)
115
+ return LintResponse(success=len(errors) == 0, errors=errors)
116
+ except HTTPException:
117
+ raise
118
+ except Exception as exc:
119
+ return LintResponse(
120
+ success=False,
121
+ errors=[
122
+ LintErrorModel(
123
+ code="E000",
124
+ message=f"Processing error: {exc}",
125
+ )
126
+ ],
127
+ )
128
+
129
+ return app
130
+
131
+
132
+ def run_server() -> None:
133
+ _, _, _, uvicorn = _load_server_dependencies()
134
+ uvicorn.run(create_app(), host="0.0.0.0", port=8000)
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: xian-tech-linter
3
+ Version: 0.3.1
4
+ Summary: Smart contract linter for the Xian blockchain
5
+ Author-email: Xian Network <info@xian.org>
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: pyflakes<4,>=3.2
9
+ Requires-Dist: pydantic<3,>=2
10
+ Requires-Dist: xian-tech-contracting<2,>=1.0.1
11
+ Provides-Extra: server
12
+ Requires-Dist: fastapi<1,>=0.115.6; extra == "server"
13
+ Requires-Dist: uvicorn<1,>=0.34; extra == "server"
14
+
15
+ # xian-linter
16
+
17
+ `xian-linter` is a Python linter specifically for Xian smart contracts. It
18
+ combines PyFlakes with the structured linter exposed by `xian-contracting`, so
19
+ rule violations include stable error codes and source positions.
20
+
21
+ The published PyPI package name is `xian-tech-linter`. The import package and
22
+ console command remain `xian_linter` and `xian-linter`.
23
+
24
+ ## Quick Start
25
+
26
+ Base package:
27
+
28
+ ```bash
29
+ pip install xian-tech-linter
30
+ ```
31
+
32
+ Inline use:
33
+
34
+ ```python
35
+ from xian_linter import lint_code_inline
36
+
37
+ errors = lint_code_inline("def transfer():\n pass\n")
38
+ ```
39
+
40
+ ## Principles
41
+
42
+ - Keep the package focused on contract linting, not runtime execution.
43
+ - Expose the same rule surface in both inline and server modes.
44
+ - Prefer stable error codes and positions so tooling can build on top of the
45
+ linter reliably.
46
+ - Keep server mode optional. The core package should still be useful as a local
47
+ linting dependency.
48
+
49
+ ## Key Directories
50
+
51
+ - `xian_linter/`: package code, server entrypoints, and inline API
52
+ - `tests/`: package and server-mode coverage
53
+ - `docs/`: repo-local notes and backlog
54
+
55
+ ## Validation
56
+
57
+ ```bash
58
+ uv sync --group dev
59
+ uv run ruff check .
60
+ uv run ruff format --check .
61
+ uv run pytest
62
+ ```
63
+
64
+ ## Related Docs
65
+
66
+ - [AGENTS.md](AGENTS.md)
67
+ - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
68
+ - [docs/BACKLOG.md](docs/BACKLOG.md)
69
+ - [docs/README.md](docs/README.md)
70
+
71
+ ## Usage Modes
72
+
73
+ - Inline/programmatic usage:
74
+
75
+ ```python
76
+ from xian_linter import lint_code_inline
77
+
78
+ errors = lint_code_inline("def transfer():\n pass\n")
79
+ ```
80
+
81
+ - Standalone server mode:
82
+
83
+ ```bash
84
+ pip install "xian-tech-linter[server]"
85
+ xian-linter
86
+ uvicorn xian_linter.server:create_app --factory --host 0.0.0.0 --port 8000
87
+ ```
@@ -0,0 +1,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ tests/test_linter.py
4
+ xian_linter/__init__.py
5
+ xian_linter/__main__.py
6
+ xian_linter/linter.py
7
+ xian_linter/server.py
8
+ xian_tech_linter.egg-info/PKG-INFO
9
+ xian_tech_linter.egg-info/SOURCES.txt
10
+ xian_tech_linter.egg-info/dependency_links.txt
11
+ xian_tech_linter.egg-info/entry_points.txt
12
+ xian_tech_linter.egg-info/requires.txt
13
+ xian_tech_linter.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ xian-linter = xian_linter.server:run_server
@@ -0,0 +1,7 @@
1
+ pyflakes<4,>=3.2
2
+ pydantic<3,>=2
3
+ xian-tech-contracting<2,>=1.0.1
4
+
5
+ [server]
6
+ fastapi<1,>=0.115.6
7
+ uvicorn<1,>=0.34
@@ -0,0 +1,4 @@
1
+ dist
2
+ docs
3
+ tests
4
+ xian_linter