spiderweave 1.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,40 @@
1
+ """
2
+ SpiderWeave SDK
3
+ ---------------
4
+ A cross-table hash architecture for tamper-proof blockchain data integrity.
5
+
6
+ Invented by: Priyanshu Chauhan / PlayWebit
7
+
8
+ Usage:
9
+ from spiderweave import SpiderWeave
10
+ from spiderweave.adapters.supabase_adapter import SupabaseAdapter
11
+ from spiderweave.adapters.playwebit_adapter import PlayWebitAdapter
12
+ """
13
+
14
+ from spiderweave.spider_chain import SpiderWeave
15
+ from spiderweave.spider_hash import SpiderHashEngine
16
+ from spiderweave.chain_sequencer import ChainSequencer
17
+ from spiderweave.exceptions import (
18
+ SpiderWeaveError,
19
+ TamperDetectedError,
20
+ ChainBrokenError,
21
+ AdapterNotConfiguredError,
22
+ InvalidHashError,
23
+ TableNotRegisteredError
24
+ )
25
+
26
+ __version__ = "1.0.0"
27
+ __author__ = "Priyanshu Chauhan"
28
+ __license__ = "MIT"
29
+
30
+ __all__ = [
31
+ "SpiderWeave",
32
+ "SpiderHashEngine",
33
+ "ChainSequencer",
34
+ "SpiderWeaveError",
35
+ "TamperDetectedError",
36
+ "ChainBrokenError",
37
+ "AdapterNotConfiguredError",
38
+ "InvalidHashError",
39
+ "TableNotRegisteredError"
40
+ ]
@@ -0,0 +1,17 @@
1
+ """SpiderWeave SDK — Adapters"""
2
+
3
+ from spiderweave.adapters.base_adapter import BaseDBAdapter
4
+ from spiderweave.adapters.base_blockchain_adapter import BaseBlockchainAdapter
5
+ from spiderweave.adapters.supabase_adapter import SupabaseAdapter
6
+ from spiderweave.adapters.postgres_adapter import PostgresAdapter
7
+ from spiderweave.adapters.playwebit_adapter import PlayWebitAdapter
8
+ from spiderweave.adapters.evm_adapter import EVMAdapter
9
+
10
+ __all__ = [
11
+ "BaseDBAdapter",
12
+ "BaseBlockchainAdapter",
13
+ "SupabaseAdapter",
14
+ "PostgresAdapter",
15
+ "PlayWebitAdapter",
16
+ "EVMAdapter"
17
+ ]
@@ -0,0 +1,133 @@
1
+ """
2
+ adapters/base_adapter.py
3
+ ------------------------
4
+ Base Database Adapter — SpiderWeave SDK
5
+
6
+ Defines the interface every database adapter must implement.
7
+ If you can write these 5 methods for your database,
8
+ SpiderWeave works with it automatically.
9
+
10
+ Supported out of the box:
11
+ - Supabase (supabase_adapter.py)
12
+ - PostgreSQL / MySQL (postgres_adapter.py)
13
+
14
+ To add your own database, subclass BaseDBAdapter and
15
+ implement the 5 methods below. That's it.
16
+ """
17
+
18
+ from abc import ABC, abstractmethod
19
+ from typing import List, Dict, Optional
20
+
21
+
22
+ class BaseDBAdapter(ABC):
23
+ """
24
+ Abstract interface for database adapters.
25
+
26
+ Every database adapter must implement these 5 methods.
27
+ SpiderWeave calls these methods internally — you never
28
+ need to call them directly in your application code.
29
+ """
30
+
31
+ @abstractmethod
32
+ def get_row_hash(self, table: str, row_id: str) -> str:
33
+ """
34
+ Get the current hash of a single row.
35
+
36
+ This is how SpiderWeave reads the "fingerprint" of
37
+ each row in each table. If the row changes, the hash
38
+ changes, and the Spider Hash breaks.
39
+
40
+ Args:
41
+ table: Table name (e.g. "wallets", "nfts")
42
+ row_id: Primary key value of the row
43
+
44
+ Returns:
45
+ 64-character hex hash of the row data.
46
+ Return "0" * 64 if row doesn't exist.
47
+
48
+ Example implementation:
49
+ row = db.query(f"SELECT * FROM {table} WHERE id = %s", row_id)
50
+ return sha256(json.dumps(row, sort_keys=True)).hexdigest()
51
+ """
52
+ pass
53
+
54
+ @abstractmethod
55
+ def get_table_chain(self, table: str, row_id: str) -> List[Dict]:
56
+ """
57
+ Get the hash history for a specific row over time.
58
+
59
+ Used to reconstruct how a row changed across events.
60
+
61
+ Args:
62
+ table: Table name
63
+ row_id: Primary key value
64
+
65
+ Returns:
66
+ List of { timestamp, hash, event_type } dicts,
67
+ ordered oldest → newest.
68
+ """
69
+ pass
70
+
71
+ @abstractmethod
72
+ def get_chain_history(
73
+ self,
74
+ chain_id: str,
75
+ before_timestamp: Optional[int] = None,
76
+ limit: int = 50
77
+ ) -> List[Dict]:
78
+ """
79
+ Get Spider Hash event history for a chain.
80
+
81
+ Args:
82
+ chain_id: Chain identifier (token_id, user_id, etc.)
83
+ before_timestamp: Only return events before this time (ms)
84
+ limit: Max events to return
85
+
86
+ Returns:
87
+ List of { chain_id, spider_hash, event_type, timestamp }
88
+ ordered newest → oldest.
89
+ """
90
+ pass
91
+
92
+ @abstractmethod
93
+ def save_chain_event(self, event: Dict) -> None:
94
+ """
95
+ Save a Spider Hash event to your database.
96
+
97
+ Called by ChainSequencer after every new Spider Hash
98
+ is calculated and anchored on-chain.
99
+
100
+ Args:
101
+ event: {
102
+ "chain_id": str,
103
+ "spider_hash": str,
104
+ "event_type": str,
105
+ "timestamp": int,
106
+ "metadata": dict
107
+ }
108
+ """
109
+ pass
110
+
111
+ @abstractmethod
112
+ def get_rows_for_event(
113
+ self,
114
+ table_config: List[Dict],
115
+ event_context: Dict
116
+ ) -> Dict[str, Dict]:
117
+ """
118
+ Fetch all relevant rows for a Spider Hash calculation.
119
+
120
+ Given a list of registered tables and an event context
121
+ (e.g. { "user_id": "0xabc", "token_id": "xyz" }),
122
+ return the current row data from each table.
123
+
124
+ Args:
125
+ table_config: List of registered table definitions
126
+ [{ "name": "wallets", "lookup_key": "user_id" }, ...]
127
+ event_context: Dict of values to look up rows with
128
+ (e.g. { "user_id": "0xabc", "token_id": "xyz" })
129
+
130
+ Returns:
131
+ Dict of { table_name: row_data_dict }
132
+ """
133
+ pass
@@ -0,0 +1,85 @@
1
+ """
2
+ adapters/base_blockchain_adapter.py
3
+ ------------------------------------
4
+ Base Blockchain Adapter — SpiderWeave SDK
5
+
6
+ Defines the interface every blockchain adapter must implement.
7
+ If you can write these 3 methods for your blockchain,
8
+ SpiderWeave anchors to it automatically.
9
+
10
+ Supported out of the box:
11
+ - PlayWebit (playwebit_adapter.py)
12
+ - Ethereum / EVM chains (evm_adapter.py)
13
+
14
+ To add your own blockchain, subclass BaseBlockchainAdapter
15
+ and implement the 3 methods below.
16
+ """
17
+
18
+ from abc import ABC, abstractmethod
19
+ from typing import Dict, Optional
20
+
21
+
22
+ class BaseBlockchainAdapter(ABC):
23
+ """
24
+ Abstract interface for blockchain adapters.
25
+
26
+ SpiderWeave calls these 3 methods to anchor and verify
27
+ Spider Hashes on-chain. Implement them for your blockchain.
28
+ """
29
+
30
+ @abstractmethod
31
+ def anchor_hash(
32
+ self,
33
+ spider_hash: str,
34
+ chain_id: str,
35
+ event_type: str,
36
+ metadata: Optional[Dict] = None
37
+ ) -> str:
38
+ """
39
+ Write a Spider Hash onto the blockchain.
40
+
41
+ This is the on-chain anchoring step. The Spider Hash
42
+ becomes immutable proof of the database state at this moment.
43
+
44
+ Args:
45
+ spider_hash: The 64-char Spider Hash to anchor
46
+ chain_id: Identifier for this chain (token_id, user_id, etc.)
47
+ event_type: Human-readable event label ("mint", "transfer", etc.)
48
+ metadata: Optional extra data to include in the transaction
49
+
50
+ Returns:
51
+ Transaction hash (proof of anchoring)
52
+ """
53
+ pass
54
+
55
+ @abstractmethod
56
+ def verify_on_chain(self, tx_hash: str) -> Dict:
57
+ """
58
+ Verify a Spider Hash exists on-chain.
59
+
60
+ Args:
61
+ tx_hash: Transaction hash returned by anchor_hash()
62
+
63
+ Returns:
64
+ {
65
+ "verified": bool,
66
+ "spider_hash": str,
67
+ "block_number": int,
68
+ "timestamp": int
69
+ }
70
+ """
71
+ pass
72
+
73
+ @abstractmethod
74
+ def get_anchored_hashes(self, chain_id: str, limit: int = 50) -> list:
75
+ """
76
+ Get all Spider Hashes anchored on-chain for a given chain_id.
77
+
78
+ Args:
79
+ chain_id: Chain identifier
80
+ limit: Max results to return
81
+
82
+ Returns:
83
+ List of { tx_hash, spider_hash, event_type, timestamp, block_number }
84
+ """
85
+ pass
@@ -0,0 +1,162 @@
1
+ """
2
+ adapters/evm_adapter.py
3
+ ------------------------
4
+ EVM Blockchain Adapter — SpiderWeave SDK
5
+
6
+ Works with any EVM-compatible blockchain:
7
+ - Ethereum mainnet / testnets
8
+ - Polygon
9
+ - BNB Chain
10
+ - Avalanche
11
+ - Any chain with an RPC endpoint
12
+
13
+ Install dependency:
14
+ pip install web3
15
+
16
+ Usage:
17
+ from spiderweave.adapters.evm_adapter import EVMAdapter
18
+
19
+ # Ethereum
20
+ adapter = EVMAdapter(
21
+ rpc_url="https://mainnet.infura.io/v3/YOUR_KEY",
22
+ private_key="0x..." # Optional, for signing transactions
23
+ )
24
+
25
+ # Polygon
26
+ adapter = EVMAdapter(rpc_url="https://polygon-rpc.com")
27
+ """
28
+
29
+ import json
30
+ import time
31
+ import hashlib
32
+ from typing import Dict, Optional, List
33
+
34
+ from spiderweave.adapters.base_blockchain_adapter import BaseBlockchainAdapter
35
+
36
+
37
+ class EVMAdapter(BaseBlockchainAdapter):
38
+ """
39
+ EVM-compatible blockchain implementation of BaseBlockchainAdapter.
40
+
41
+ Anchors Spider Hashes by writing them as transaction input data
42
+ on any EVM-compatible chain. Uses web3.py under the hood.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ rpc_url: str,
48
+ private_key: Optional[str] = None,
49
+ contract_address: Optional[str] = None
50
+ ):
51
+ """
52
+ Args:
53
+ rpc_url: RPC endpoint for your EVM chain
54
+ private_key: Private key for signing transactions (optional)
55
+ If not provided, operates in read-only mode
56
+ contract_address: Optional SpiderWeave smart contract address
57
+ for structured on-chain storage
58
+ """
59
+ try:
60
+ from web3 import Web3
61
+ self.w3 = Web3(Web3.HTTPProvider(rpc_url))
62
+ except ImportError:
63
+ raise ImportError(
64
+ "web3 package not installed. Run: pip install web3"
65
+ )
66
+
67
+ self.rpc_url = rpc_url
68
+ self.private_key = private_key
69
+ self.contract_address = contract_address
70
+
71
+ if not self.w3.is_connected():
72
+ raise ConnectionError(f"Could not connect to EVM node at {rpc_url}")
73
+
74
+ def anchor_hash(
75
+ self,
76
+ spider_hash: str,
77
+ chain_id: str,
78
+ event_type: str,
79
+ metadata: Optional[Dict] = None
80
+ ) -> str:
81
+ """
82
+ Anchor a Spider Hash on an EVM chain.
83
+
84
+ Encodes the Spider Hash as transaction input data.
85
+ This creates an immutable on-chain record of the hash.
86
+
87
+ If no private key is provided, returns a simulated tx hash
88
+ (useful for testing).
89
+ """
90
+ if not self.private_key:
91
+ return self._simulate_tx_hash(spider_hash)
92
+
93
+ from web3 import Web3
94
+
95
+ payload = {
96
+ "type": "spider_hash",
97
+ "hash": spider_hash,
98
+ "chain_id": chain_id,
99
+ "event": event_type,
100
+ "ts": int(time.time() * 1000)
101
+ }
102
+
103
+ account = self.w3.eth.account.from_key(self.private_key)
104
+ data = "0x" + json.dumps(payload).encode().hex()
105
+
106
+ tx = {
107
+ "from": account.address,
108
+ "to": self.contract_address or account.address,
109
+ "value": 0,
110
+ "data": data,
111
+ "gas": 100000,
112
+ "gasPrice": self.w3.eth.gas_price,
113
+ "nonce": self.w3.eth.get_transaction_count(account.address),
114
+ "chainId": self.w3.eth.chain_id
115
+ }
116
+
117
+ signed = self.w3.eth.account.sign_transaction(tx, self.private_key)
118
+ tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction)
119
+ return tx_hash.hex()
120
+
121
+ def verify_on_chain(self, tx_hash: str) -> Dict:
122
+ """Verify a Spider Hash transaction exists on the EVM chain."""
123
+ try:
124
+ receipt = self.w3.eth.get_transaction_receipt(tx_hash)
125
+ tx = self.w3.eth.get_transaction(tx_hash)
126
+ block = self.w3.eth.get_block(receipt.blockNumber)
127
+
128
+ return {
129
+ "verified": receipt.status == 1,
130
+ "spider_hash": self._extract_hash_from_tx(tx),
131
+ "block_number": receipt.blockNumber,
132
+ "timestamp": block.timestamp
133
+ }
134
+
135
+ except Exception as e:
136
+ return {"verified": False, "error": str(e)}
137
+
138
+ def get_anchored_hashes(self, chain_id: str, limit: int = 50) -> List[Dict]:
139
+ """
140
+ Get anchored Spider Hashes from the EVM chain.
141
+
142
+ Note: For full history queries, you need an indexed node
143
+ or a subgraph. This method returns an empty list if no
144
+ contract address is set.
145
+ """
146
+ if not self.contract_address:
147
+ return []
148
+ return []
149
+
150
+ def _extract_hash_from_tx(self, tx) -> Optional[str]:
151
+ """Try to extract Spider Hash from transaction input data."""
152
+ try:
153
+ data = bytes.fromhex(tx.input[2:]).decode("utf-8")
154
+ payload = json.loads(data)
155
+ return payload.get("hash")
156
+ except Exception:
157
+ return None
158
+
159
+ def _simulate_tx_hash(self, spider_hash: str) -> str:
160
+ """Generate a deterministic mock tx hash for testing."""
161
+ data = f"{spider_hash}{time.time()}"
162
+ return "0x" + hashlib.sha256(data.encode()).hexdigest()
@@ -0,0 +1,137 @@
1
+ """
2
+ adapters/playwebit_adapter.py
3
+ ------------------------------
4
+ PlayWebit Blockchain Adapter — SpiderWeave SDK
5
+
6
+ Connects SpiderWeave to the PlayWebit Network (chain ID 4968).
7
+
8
+ Usage:
9
+ from spiderweave.adapters.playwebit_adapter import PlayWebitAdapter
10
+
11
+ adapter = PlayWebitAdapter(
12
+ node_url="https://priyanshu23456-cipherv.hf.space"
13
+ )
14
+ """
15
+
16
+ import json
17
+ import time
18
+ import hashlib
19
+ from typing import Dict, Optional, List
20
+
21
+ from spiderweave.adapters.base_blockchain_adapter import BaseBlockchainAdapter
22
+
23
+
24
+ class PlayWebitAdapter(BaseBlockchainAdapter):
25
+ """
26
+ PlayWebit Network implementation of BaseBlockchainAdapter.
27
+
28
+ Communicates with the PlayWebit node via its REST API
29
+ to anchor and verify Spider Hashes on-chain.
30
+ """
31
+
32
+ def __init__(self, node_url: str, authority_wallet: Optional[str] = None):
33
+ """
34
+ Args:
35
+ node_url: URL of the PlayWebit node
36
+ e.g. "https://priyanshu23456-cipherv.hf.space"
37
+ authority_wallet: Optional authority wallet address for signing
38
+ """
39
+ self.node_url = node_url.rstrip("/")
40
+ self.authority_wallet = authority_wallet
41
+ self.chain_id = 4968
42
+ self.currency = "PLWB"
43
+
44
+ def anchor_hash(
45
+ self,
46
+ spider_hash: str,
47
+ chain_id: str,
48
+ event_type: str,
49
+ metadata: Optional[Dict] = None
50
+ ) -> str:
51
+ """
52
+ Anchor a Spider Hash on PlayWebit via a transaction.
53
+
54
+ Creates a zero-value transaction with the Spider Hash
55
+ embedded in the transaction data field.
56
+ """
57
+ try:
58
+ import requests
59
+
60
+ payload = {
61
+ "type": "spider_hash_anchor",
62
+ "spider_hash": spider_hash,
63
+ "chain_id": chain_id,
64
+ "event_type": event_type,
65
+ "metadata": metadata or {},
66
+ "timestamp": int(time.time() * 1000)
67
+ }
68
+
69
+ response = requests.post(
70
+ f"{self.node_url}/api/anchor_spider_hash",
71
+ json=payload,
72
+ timeout=30
73
+ )
74
+
75
+ if response.status_code == 200:
76
+ data = response.json()
77
+ return data.get("tx_hash", self._generate_mock_tx_hash(spider_hash))
78
+
79
+ raise RuntimeError(
80
+ f"PlayWebit node returned {response.status_code}: {response.text}"
81
+ )
82
+
83
+ except ImportError:
84
+ raise ImportError("requests package not installed. Run: pip install requests")
85
+
86
+ def verify_on_chain(self, tx_hash: str) -> Dict:
87
+ """Verify a Spider Hash transaction exists on PlayWebit."""
88
+ try:
89
+ import requests
90
+
91
+ response = requests.get(
92
+ f"{self.node_url}/api/transaction/{tx_hash}",
93
+ timeout=30
94
+ )
95
+
96
+ if response.status_code == 200:
97
+ data = response.json()
98
+ return {
99
+ "verified": True,
100
+ "spider_hash": data.get("spider_hash"),
101
+ "block_number": data.get("block_number"),
102
+ "timestamp": data.get("timestamp")
103
+ }
104
+
105
+ return {
106
+ "verified": False,
107
+ "spider_hash": None,
108
+ "block_number": None,
109
+ "timestamp": None
110
+ }
111
+
112
+ except Exception as e:
113
+ return {"verified": False, "error": str(e)}
114
+
115
+ def get_anchored_hashes(self, chain_id: str, limit: int = 50) -> List[Dict]:
116
+ """Get all Spider Hashes anchored for a chain_id on PlayWebit."""
117
+ try:
118
+ import requests
119
+
120
+ response = requests.get(
121
+ f"{self.node_url}/api/spider_hashes/{chain_id}",
122
+ params={"limit": limit},
123
+ timeout=30
124
+ )
125
+
126
+ if response.status_code == 200:
127
+ return response.json().get("hashes", [])
128
+
129
+ return []
130
+
131
+ except Exception:
132
+ return []
133
+
134
+ def _generate_mock_tx_hash(self, spider_hash: str) -> str:
135
+ """Fallback tx hash if node doesn't return one."""
136
+ data = f"{spider_hash}{time.time()}"
137
+ return "0x" + hashlib.sha256(data.encode()).hexdigest()