-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBlockchain-Python.py
More file actions
3078 lines (2528 loc) · 119 KB
/
Blockchain-Python.py
File metadata and controls
3078 lines (2528 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# BLOCKCHAIN PYTHON - Comprehensive Development Reference - by Richard Rembert
# Python is extensively used in blockchain development for analysis, automation,
# DApp backends, trading bots, data science, and blockchain infrastructure
# ═══════════════════════════════════════════════════════════════════════════════
# 1. SETUP AND ENVIRONMENT
# ═══════════════════════════════════════════════════════════════════════════════
"""
BLOCKCHAIN PYTHON DEVELOPMENT SETUP:
1. Install Python 3.8+ and pip
2. Create virtual environment:
python -m venv blockchain_env
source blockchain_env/bin/activate # Linux/Mac
blockchain_env\Scripts\activate # Windows
3. Essential blockchain packages:
pip install web3 # Ethereum interaction
pip install bitcoin # Bitcoin utilities
pip install requests # HTTP requests
pip install pandas numpy # Data analysis
pip install matplotlib seaborn # Visualization
pip install asyncio aiohttp # Async programming
pip install websockets # Real-time data
pip install python-dotenv # Environment variables
pip install click # CLI applications
pip install celery redis # Task queues
pip install sqlalchemy # Database ORM
pip install pytest # Testing
4. Advanced packages:
pip install brownie # Smart contract development
pip install eth-brownie # Ethereum development framework
pip install py-solc-x # Solidity compiler
pip install rlp # RLP encoding/decoding
pip install eth-hash eth-keys # Cryptographic utilities
pip install coincurve # Elliptic curve cryptography
pip install pysha3 # Keccak hashing
5. API clients:
pip install python-binance # Binance API
pip install ccxt # Cryptocurrency exchange APIs
pip install alpha-vantage # Financial data
pip install cryptocompare # Crypto market data
pip install ta # Technical analysis
6. Development tools:
pip install black flake8 # Code formatting and linting
pip install mypy # Type checking
pip install jupyter # Interactive notebooks
pip install mnemonic # BIP39 mnemonic generation
"""
import os
import sys
import json
import time
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Union, Any, Tuple
from dataclasses import dataclass
from pathlib import Path
# Environment setup
from dotenv import load_dotenv
load_dotenv()
# Basic logging setup
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# ═══════════════════════════════════════════════════════════════════════════════
# 2. WEB3 AND ETHEREUM INTERACTION
# ═══════════════════════════════════════════════════════════════════════════════
from web3 import Web3, HTTPProvider, WebsocketProvider
from web3.contract import Contract
from web3.exceptions import TransactionNotFound, BlockNotFound
from web3.middleware import geth_poa_middleware
import requests
class EthereumClient:
"""Comprehensive Ethereum blockchain client"""
def __init__(self, node_url: str, private_key: Optional[str] = None):
"""
Initialize Ethereum client
Args:
node_url: RPC endpoint (Infura, Alchemy, local node)
private_key: Private key for transaction signing
"""
self.w3 = Web3(HTTPProvider(node_url))
# Add PoA middleware for testnets like Goerli
if 'goerli' in node_url.lower() or 'sepolia' in node_url.lower():
self.w3.middleware_onion.inject(geth_poa_middleware, layer=0)
self.private_key = private_key
if private_key:
self.account = self.w3.eth.account.from_key(private_key)
else:
self.account = None
# Verify connection
if not self.w3.is_connected():
raise ConnectionError("Failed to connect to Ethereum node")
logger.info(f"Connected to Ethereum network: {self.get_network_info()}")
def get_network_info(self) -> Dict[str, Any]:
"""Get network information"""
try:
chain_id = self.w3.eth.chain_id
block_number = self.w3.eth.block_number
gas_price = self.w3.eth.gas_price
return {
'chain_id': chain_id,
'latest_block': block_number,
'gas_price_gwei': self.w3.from_wei(gas_price, 'gwei'),
'is_syncing': self.w3.eth.syncing
}
except Exception as e:
logger.error(f"Error getting network info: {e}")
return {}
def get_balance(self, address: str, block: str = 'latest') -> float:
"""Get ETH balance for an address"""
try:
balance_wei = self.w3.eth.get_balance(
self.w3.to_checksum_address(address),
block
)
return self.w3.from_wei(balance_wei, 'ether')
except Exception as e:
logger.error(f"Error getting balance: {e}")
return 0.0
def get_transaction(self, tx_hash: str) -> Optional[Dict]:
"""Get transaction details"""
try:
tx = self.w3.eth.get_transaction(tx_hash)
receipt = self.w3.eth.get_transaction_receipt(tx_hash)
return {
'hash': tx['hash'].hex(),
'from': tx['from'],
'to': tx['to'],
'value': self.w3.from_wei(tx['value'], 'ether'),
'gas': tx['gas'],
'gas_price': self.w3.from_wei(tx['gasPrice'], 'gwei'),
'nonce': tx['nonce'],
'block_number': receipt['blockNumber'],
'gas_used': receipt['gasUsed'],
'status': receipt['status'],
'confirmations': self.w3.eth.block_number - receipt['blockNumber']
}
except TransactionNotFound:
logger.warning(f"Transaction not found: {tx_hash}")
return None
except Exception as e:
logger.error(f"Error getting transaction: {e}")
return None
def get_block(self, block_number: Union[int, str] = 'latest') -> Optional[Dict]:
"""Get block information"""
try:
block = self.w3.eth.get_block(block_number, full_transactions=True)
return {
'number': block['number'],
'hash': block['hash'].hex(),
'parent_hash': block['parentHash'].hex(),
'timestamp': datetime.fromtimestamp(block['timestamp']),
'gas_limit': block['gasLimit'],
'gas_used': block['gasUsed'],
'transactions_count': len(block['transactions']),
'size': block['size'],
'miner': block['miner']
}
except BlockNotFound:
logger.warning(f"Block not found: {block_number}")
return None
except Exception as e:
logger.error(f"Error getting block: {e}")
return None
def send_transaction(self, to_address: str, value_eth: float,
gas_limit: int = 21000, gas_price_gwei: Optional[float] = None) -> Optional[str]:
"""Send ETH transaction"""
if not self.account:
raise ValueError("Private key required for sending transactions")
try:
# Get current gas price if not specified
if gas_price_gwei is None:
gas_price_gwei = self.w3.from_wei(self.w3.eth.gas_price, 'gwei')
# Build transaction
transaction = {
'to': self.w3.to_checksum_address(to_address),
'value': self.w3.to_wei(value_eth, 'ether'),
'gas': gas_limit,
'gasPrice': self.w3.to_wei(gas_price_gwei, 'gwei'),
'nonce': self.w3.eth.get_transaction_count(self.account.address),
'chainId': self.w3.eth.chain_id
}
# Sign and send transaction
signed_txn = self.w3.eth.account.sign_transaction(transaction, self.private_key)
tx_hash = self.w3.eth.send_raw_transaction(signed_txn.rawTransaction)
logger.info(f"Transaction sent: {tx_hash.hex()}")
return tx_hash.hex()
except Exception as e:
logger.error(f"Error sending transaction: {e}")
return None
def wait_for_transaction(self, tx_hash: str, timeout: int = 300) -> Optional[Dict]:
"""Wait for transaction confirmation"""
try:
receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash, timeout=timeout)
logger.info(f"Transaction confirmed: {tx_hash}")
return dict(receipt)
except Exception as e:
logger.error(f"Error waiting for transaction: {e}")
return None
# Smart Contract Interaction
class ContractInteractor:
"""Interact with smart contracts"""
def __init__(self, w3: Web3, contract_address: str, abi: List[Dict]):
"""
Initialize contract interactor
Args:
w3: Web3 instance
contract_address: Contract address
abi: Contract ABI (Application Binary Interface)
"""
self.w3 = w3
self.contract = w3.eth.contract(
address=w3.to_checksum_address(contract_address),
abi=abi
)
def call_function(self, function_name: str, *args, **kwargs) -> Any:
"""Call a read-only contract function"""
try:
function = getattr(self.contract.functions, function_name)
result = function(*args, **kwargs).call()
return result
except Exception as e:
logger.error(f"Error calling function {function_name}: {e}")
return None
def send_transaction(self, function_name: str, private_key: str,
*args, gas_limit: int = 200000, **kwargs) -> Optional[str]:
"""Send a transaction to a contract function"""
try:
account = self.w3.eth.account.from_key(private_key)
function = getattr(self.contract.functions, function_name)
# Build transaction
transaction = function(*args, **kwargs).build_transaction({
'from': account.address,
'gas': gas_limit,
'gasPrice': self.w3.eth.gas_price,
'nonce': self.w3.eth.get_transaction_count(account.address),
'chainId': self.w3.eth.chain_id
})
# Sign and send
signed_txn = self.w3.eth.account.sign_transaction(transaction, private_key)
tx_hash = self.w3.eth.send_raw_transaction(signed_txn.rawTransaction)
return tx_hash.hex()
except Exception as e:
logger.error(f"Error sending transaction to {function_name}: {e}")
return None
def get_events(self, event_name: str, from_block: int = 0, to_block: str = 'latest') -> List[Dict]:
"""Get contract events"""
try:
event_filter = getattr(self.contract.events, event_name).create_filter(
fromBlock=from_block,
toBlock=to_block
)
events = event_filter.get_all_entries()
return [dict(event) for event in events]
except Exception as e:
logger.error(f"Error getting events {event_name}: {e}")
return []
# ERC-20 Token interaction
class ERC20Token(ContractInteractor):
"""ERC-20 token interaction class"""
# Standard ERC-20 ABI (minimal)
ERC20_ABI = [
{
"constant": True,
"inputs": [],
"name": "name",
"outputs": [{"name": "", "type": "string"}],
"type": "function"
},
{
"constant": True,
"inputs": [],
"name": "symbol",
"outputs": [{"name": "", "type": "string"}],
"type": "function"
},
{
"constant": True,
"inputs": [],
"name": "decimals",
"outputs": [{"name": "", "type": "uint8"}],
"type": "function"
},
{
"constant": True,
"inputs": [],
"name": "totalSupply",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
},
{
"constant": True,
"inputs": [{"name": "_owner", "type": "address"}],
"name": "balanceOf",
"outputs": [{"name": "balance", "type": "uint256"}],
"type": "function"
},
{
"constant": False,
"inputs": [
{"name": "_to", "type": "address"},
{"name": "_value", "type": "uint256"}
],
"name": "transfer",
"outputs": [{"name": "", "type": "bool"}],
"type": "function"
},
{
"anonymous": False,
"inputs": [
{"indexed": True, "name": "from", "type": "address"},
{"indexed": True, "name": "to", "type": "address"},
{"indexed": False, "name": "value", "type": "uint256"}
],
"name": "Transfer",
"type": "event"
}
]
def __init__(self, w3: Web3, token_address: str):
super().__init__(w3, token_address, self.ERC20_ABI)
# Get token info
self.name = self.call_function('name')
self.symbol = self.call_function('symbol')
self.decimals = self.call_function('decimals')
self.total_supply = self.call_function('totalSupply')
logger.info(f"Initialized ERC-20 token: {self.name} ({self.symbol})")
def get_balance(self, address: str) -> float:
"""Get token balance for an address"""
balance = self.call_function('balanceOf', self.w3.to_checksum_address(address))
if balance is not None:
return balance / (10 ** self.decimals)
return 0.0
def transfer(self, private_key: str, to_address: str, amount: float) -> Optional[str]:
"""Transfer tokens"""
amount_wei = int(amount * (10 ** self.decimals))
return self.send_transaction('transfer', private_key,
self.w3.to_checksum_address(to_address), amount_wei)
def get_transfer_events(self, from_block: int = 0) -> List[Dict]:
"""Get transfer events"""
events = self.get_events('Transfer', from_block=from_block)
processed_events = []
for event in events:
processed_events.append({
'from': event['args']['from'],
'to': event['args']['to'],
'value': event['args']['value'] / (10 ** self.decimals),
'transaction_hash': event['transactionHash'].hex(),
'block_number': event['blockNumber']
})
return processed_events
# ═══════════════════════════════════════════════════════════════════════════════
# 3. BITCOIN AND CRYPTOCURRENCY UTILITIES
# ═══════════════════════════════════════════════════════════════════════════════
import hashlib
import hmac
import base64
from bitcoin import *
from Crypto.Hash import SHA256, RIPEMD160
from Crypto.Cipher import AES
import secrets
class BitcoinWallet:
"""Bitcoin wallet utilities"""
def __init__(self, private_key: Optional[str] = None):
"""Initialize Bitcoin wallet"""
if private_key:
self.private_key = private_key
else:
self.private_key = self.generate_private_key()
self.public_key = self.private_key_to_public_key(self.private_key)
self.address = self.public_key_to_address(self.public_key)
logger.info(f"Bitcoin wallet initialized: {self.address}")
@staticmethod
def generate_private_key() -> str:
"""Generate a random private key"""
return secrets.token_hex(32)
@staticmethod
def private_key_to_public_key(private_key: str) -> str:
"""Convert private key to public key"""
return privkey_to_pubkey(private_key)
@staticmethod
def public_key_to_address(public_key: str) -> str:
"""Convert public key to Bitcoin address"""
return pubkey_to_address(public_key)
@staticmethod
def validate_address(address: str) -> bool:
"""Validate Bitcoin address"""
try:
# Simple validation - in production use more robust validation
if len(address) < 26 or len(address) > 35:
return False
# Check if address starts with valid prefixes
valid_prefixes = ['1', '3', 'bc1']
return any(address.startswith(prefix) for prefix in valid_prefixes)
except:
return False
def sign_message(self, message: str) -> str:
"""Sign a message with the private key"""
try:
signature = ecdsa_sign(message, self.private_key)
return signature
except Exception as e:
logger.error(f"Error signing message: {e}")
return ""
@staticmethod
def verify_signature(message: str, signature: str, public_key: str) -> bool:
"""Verify a message signature"""
try:
return ecdsa_verify(message, signature, public_key)
except Exception as e:
logger.error(f"Error verifying signature: {e}")
return False
class CryptographicUtils:
"""Cryptographic utilities for blockchain development"""
@staticmethod
def hash_sha256(data: Union[str, bytes]) -> str:
"""SHA-256 hash"""
if isinstance(data, str):
data = data.encode('utf-8')
return hashlib.sha256(data).hexdigest()
@staticmethod
def hash_keccak256(data: Union[str, bytes]) -> str:
"""Keccak-256 hash (used by Ethereum)"""
if isinstance(data, str):
data = data.encode('utf-8')
import sha3
return sha3.keccak_256(data).hexdigest()
@staticmethod
def hash_ripemd160(data: Union[str, bytes]) -> str:
"""RIPEMD-160 hash"""
if isinstance(data, str):
data = data.encode('utf-8')
ripemd160 = RIPEMD160.new()
ripemd160.update(data)
return ripemd160.hexdigest()
@staticmethod
def generate_mnemonic(strength: int = 128) -> str:
"""Generate BIP39 mnemonic phrase"""
from mnemonic import Mnemonic
mnemo = Mnemonic("english")
return mnemo.generate(strength=strength)
@staticmethod
def mnemonic_to_seed(mnemonic: str, passphrase: str = "") -> bytes:
"""Convert mnemonic to seed"""
from mnemonic import Mnemonic
mnemo = Mnemonic("english")
return mnemo.to_seed(mnemonic, passphrase)
@staticmethod
def encrypt_data(data: str, password: str) -> str:
"""Encrypt data with AES"""
try:
# Generate salt and key
salt = secrets.token_bytes(16)
key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
# Encrypt data
cipher = AES.new(key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(data.encode())
# Combine salt, nonce, tag, and ciphertext
encrypted = salt + cipher.nonce + tag + ciphertext
return base64.b64encode(encrypted).decode()
except Exception as e:
logger.error(f"Encryption error: {e}")
return ""
@staticmethod
def decrypt_data(encrypted_data: str, password: str) -> str:
"""Decrypt AES encrypted data"""
try:
# Decode and extract components
encrypted = base64.b64decode(encrypted_data.encode())
salt = encrypted[:16]
nonce = encrypted[16:32]
tag = encrypted[32:48]
ciphertext = encrypted[48:]
# Derive key
key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
# Decrypt
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
return data.decode()
except Exception as e:
logger.error(f"Decryption error: {e}")
return ""
# ═══════════════════════════════════════════════════════════════════════════════
# 4. BLOCKCHAIN DATA ANALYSIS
# ═══════════════════════════════════════════════════════════════════════════════
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from collections import defaultdict, Counter
import sqlite3
class BlockchainAnalyzer:
"""Blockchain data analysis and visualization"""
def __init__(self, ethereum_client: EthereumClient):
self.eth_client = ethereum_client
self.w3 = ethereum_client.w3
def analyze_address_activity(self, address: str, blocks_to_analyze: int = 1000) -> Dict:
"""Analyze activity for a specific address"""
try:
address = self.w3.to_checksum_address(address)
current_block = self.w3.eth.block_number
start_block = max(0, current_block - blocks_to_analyze)
transactions = []
eth_received = 0
eth_sent = 0
gas_used = 0
logger.info(f"Analyzing {address} from block {start_block} to {current_block}")
for block_num in range(start_block, current_block + 1):
if block_num % 100 == 0:
logger.info(f"Processing block {block_num}")
try:
block = self.w3.eth.get_block(block_num, full_transactions=True)
for tx in block['transactions']:
if tx['from'] == address or tx['to'] == address:
value_eth = self.w3.from_wei(tx['value'], 'ether')
# Get transaction receipt for gas info
try:
receipt = self.w3.eth.get_transaction_receipt(tx['hash'])
gas_cost = receipt['gasUsed'] * tx['gasPrice']
except:
gas_cost = 0
tx_data = {
'hash': tx['hash'].hex(),
'block_number': block_num,
'from': tx['from'],
'to': tx['to'],
'value_eth': float(value_eth),
'gas_used': tx['gas'],
'gas_price_gwei': self.w3.from_wei(tx['gasPrice'], 'gwei'),
'gas_cost_eth': self.w3.from_wei(gas_cost, 'ether'),
'timestamp': datetime.fromtimestamp(block['timestamp'])
}
transactions.append(tx_data)
if tx['to'] == address:
eth_received += float(value_eth)
if tx['from'] == address:
eth_sent += float(value_eth)
gas_used += self.w3.from_wei(gas_cost, 'ether')
except Exception as e:
logger.warning(f"Error processing block {block_num}: {e}")
continue
# Analysis results
analysis = {
'address': address,
'blocks_analyzed': blocks_to_analyze,
'total_transactions': len(transactions),
'eth_received': eth_received,
'eth_sent': eth_sent,
'net_eth_flow': eth_received - eth_sent,
'total_gas_cost': gas_used,
'current_balance': self.eth_client.get_balance(address),
'transactions': transactions
}
return analysis
except Exception as e:
logger.error(f"Error analyzing address: {e}")
return {}
def create_transaction_graph(self, transactions: List[Dict]) -> None:
"""Create transaction flow visualization"""
if not transactions:
logger.warning("No transactions to visualize")
return
# Create DataFrame
df = pd.DataFrame(transactions)
# Time series analysis
df['timestamp'] = pd.to_datetime(df['timestamp'])
df.set_index('timestamp', inplace=True)
# Create subplots
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
# Transaction volume over time
daily_volume = df.resample('D')['value_eth'].sum()
axes[0, 0].plot(daily_volume.index, daily_volume.values)
axes[0, 0].set_title('Daily Transaction Volume (ETH)')
axes[0, 0].set_ylabel('ETH')
axes[0, 0].tick_params(axis='x', rotation=45)
# Transaction count over time
daily_count = df.resample('D').size()
axes[0, 1].plot(daily_count.index, daily_count.values)
axes[0, 1].set_title('Daily Transaction Count')
axes[0, 1].set_ylabel('Transactions')
axes[0, 1].tick_params(axis='x', rotation=45)
# Gas price distribution
axes[1, 0].hist(df['gas_price_gwei'], bins=30, alpha=0.7)
axes[1, 0].set_title('Gas Price Distribution')
axes[1, 0].set_xlabel('Gas Price (Gwei)')
axes[1, 0].set_ylabel('Frequency')
# Value distribution
axes[1, 1].hist(df[df['value_eth'] > 0]['value_eth'], bins=30, alpha=0.7)
axes[1, 1].set_title('Transaction Value Distribution')
axes[1, 1].set_xlabel('Value (ETH)')
axes[1, 1].set_ylabel('Frequency')
plt.tight_layout()
plt.show()
def analyze_gas_trends(self, blocks_to_analyze: int = 1000) -> Dict:
"""Analyze gas price trends"""
try:
current_block = self.w3.eth.block_number
start_block = max(0, current_block - blocks_to_analyze)
gas_data = []
for block_num in range(start_block, current_block + 1, 10): # Sample every 10 blocks
try:
block = self.w3.eth.get_block(block_num, full_transactions=True)
if block['transactions']:
gas_prices = [self.w3.from_wei(tx['gasPrice'], 'gwei')
for tx in block['transactions']]
gas_data.append({
'block_number': block_num,
'timestamp': datetime.fromtimestamp(block['timestamp']),
'avg_gas_price': np.mean(gas_prices),
'median_gas_price': np.median(gas_prices),
'max_gas_price': np.max(gas_prices),
'min_gas_price': np.min(gas_prices),
'tx_count': len(block['transactions']),
'gas_used': block['gasUsed'],
'gas_limit': block['gasLimit'],
'gas_utilization': block['gasUsed'] / block['gasLimit']
})
except Exception as e:
logger.warning(f"Error processing block {block_num}: {e}")
continue
return {
'gas_data': gas_data,
'blocks_analyzed': len(gas_data),
'avg_gas_price': np.mean([d['avg_gas_price'] for d in gas_data]),
'avg_gas_utilization': np.mean([d['gas_utilization'] for d in gas_data])
}
except Exception as e:
logger.error(f"Error analyzing gas trends: {e}")
return {}
def token_holder_analysis(self, token_address: str, top_n: int = 100) -> Dict:
"""Analyze token distribution among holders"""
try:
token = ERC20Token(self.w3, token_address)
# Get transfer events to find all holders
transfer_events = token.get_transfer_events()
# Track balances
balances = defaultdict(float)
for event in transfer_events:
from_addr = event['from']
to_addr = event['to']
value = event['value']
# Handle minting (from zero address)
if from_addr != '0x0000000000000000000000000000000000000000':
balances[from_addr] -= value
balances[to_addr] += value
# Remove zero balances and get current balances
active_holders = {}
for address, balance in balances.items():
if balance > 0:
# Verify current balance on-chain
current_balance = token.get_balance(address)
if current_balance > 0:
active_holders[address] = current_balance
# Sort by balance
sorted_holders = sorted(active_holders.items(), key=lambda x: x[1], reverse=True)
top_holders = sorted_holders[:top_n]
total_supply = token.total_supply / (10 ** token.decimals)
total_held = sum(active_holders.values())
# Calculate distribution metrics
gini_coefficient = self._calculate_gini_coefficient([balance for _, balance in sorted_holders])
return {
'token_name': token.name,
'token_symbol': token.symbol,
'total_supply': total_supply,
'total_holders': len(active_holders),
'top_holders': top_holders,
'concentration_ratio': {
'top_10': sum([balance for _, balance in sorted_holders[:10]]) / total_supply * 100,
'top_50': sum([balance for _, balance in sorted_holders[:50]]) / total_supply * 100,
'top_100': sum([balance for _, balance in sorted_holders[:100]]) / total_supply * 100
},
'gini_coefficient': gini_coefficient
}
except Exception as e:
logger.error(f"Error analyzing token holders: {e}")
return {}
@staticmethod
def _calculate_gini_coefficient(values: List[float]) -> float:
"""Calculate Gini coefficient for wealth distribution"""
if not values:
return 0
values = sorted(values)
n = len(values)
cumsum = np.cumsum(values)
return (n + 1 - 2 * sum((n + 1 - i) * y for i, y in enumerate(values, 1))) / (n * sum(values))
class BlockchainDatabase:
"""SQLite database for storing blockchain data"""
def __init__(self, db_path: str = "blockchain_data.db"):
self.db_path = db_path
self.conn = sqlite3.connect(db_path)
self.create_tables()
def create_tables(self):
"""Create database tables"""
cursor = self.conn.cursor()
# Transactions table
cursor.execute('''
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hash TEXT UNIQUE NOT NULL,
block_number INTEGER,
from_address TEXT,
to_address TEXT,
value_eth REAL,
gas_used INTEGER,
gas_price_gwei REAL,
timestamp DATETIME,
status INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
# Blocks table
cursor.execute('''
CREATE TABLE IF NOT EXISTS blocks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
number INTEGER UNIQUE NOT NULL,
hash TEXT UNIQUE NOT NULL,
parent_hash TEXT,
timestamp DATETIME,
gas_limit INTEGER,
gas_used INTEGER,
miner TEXT,
transaction_count INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
# Token transfers table
cursor.execute('''
CREATE TABLE IF NOT EXISTS token_transfers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_address TEXT,
from_address TEXT,
to_address TEXT,
value REAL,
transaction_hash TEXT,
block_number INTEGER,
log_index INTEGER,
timestamp DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
# Create indexes
cursor.execute('CREATE INDEX IF NOT EXISTS idx_tx_hash ON transactions(hash)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_tx_block ON transactions(block_number)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_tx_from ON transactions(from_address)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_tx_to ON transactions(to_address)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_block_number ON blocks(number)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_token_address ON token_transfers(token_address)')
self.conn.commit()
def insert_transaction(self, tx_data: Dict):
"""Insert transaction data"""
cursor = self.conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO transactions
(hash, block_number, from_address, to_address, value_eth, gas_used, gas_price_gwei, timestamp, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
tx_data['hash'],
tx_data['block_number'],
tx_data['from'],
tx_data['to'],
tx_data['value'],
tx_data['gas_used'],
tx_data['gas_price_gwei'],
tx_data['timestamp'],
tx_data['status']
))
self.conn.commit()
def insert_block(self, block_data: Dict):
"""Insert block data"""
cursor = self.conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO blocks
(number, hash, parent_hash, timestamp, gas_limit, gas_used, miner, transaction_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
block_data['number'],
block_data['hash'],
block_data['parent_hash'],
block_data['timestamp'],
block_data['gas_limit'],
block_data['gas_used'],
block_data['miner'],
block_data['transactions_count']
))
self.conn.commit()
def get_address_transactions(self, address: str, limit: int = 100) -> List[Dict]:
"""Get transactions for an address"""
cursor = self.conn.cursor()
cursor.execute('''
SELECT * FROM transactions
WHERE from_address = ? OR to_address = ?
ORDER BY block_number DESC
LIMIT ?
''', (address, address, limit))
columns = [description[0] for description in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()]
def get_gas_statistics(self, hours: int = 24) -> Dict:
"""Get gas statistics for the last N hours"""
cursor = self.conn.cursor()
cursor.execute('''
SELECT
AVG(gas_price_gwei) as avg_gas_price,
MIN(gas_price_gwei) as min_gas_price,
MAX(gas_price_gwei) as max_gas_price,
COUNT(*) as transaction_count
FROM transactions
WHERE timestamp > datetime('now', '-{} hours')
'''.format(hours))
row = cursor.fetchone()
return {
'avg_gas_price': row[0] or 0,
'min_gas_price': row[1] or 0,
'max_gas_price': row[2] or 0,
'transaction_count': row[3] or 0
}
# ═══════════════════════════════════════════════════════════════════════════════
# 5. CRYPTOCURRENCY TRADING AND APIS
# ═══════════════════════════════════════════════════════════════════════════════
import ccxt
import pandas as pd
from typing import Tuple
import ta # Technical analysis library
class CryptocurrencyTrader:
"""Cryptocurrency trading utilities and API integration"""
def __init__(self, exchange_name: str = 'binance', api_key: str = None,
api_secret: str = None, sandbox: bool = True):
"""
Initialize cryptocurrency trader
Args:
exchange_name: Exchange name (binance, coinbase, kraken, etc.)
api_key: API key for authenticated endpoints
api_secret: API secret for authenticated endpoints
sandbox: Use sandbox/testnet environment
"""
self.exchange_name = exchange_name
# Initialize exchange
exchange_class = getattr(ccxt, exchange_name)
self.exchange = exchange_class({
'apiKey': api_key,