Spaces:
1
Sleeping

1
File size: 10,186 Bytes
0322c67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

加密社【指定地址匹配爆破工具】

原C#程序Python改写版本

"""

import os
import sys
import time
import base64
import hashlib
import hmac
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Set, Tuple
from dataclasses import dataclass
from pathlib import Path

# 比特币相关库
try:
    import ecdsa
    from ecdsa import SigningKey, SECP256k1
except ImportError:
    print("请安装 ecdsa: pip install ecdsa")
    sys.exit(1)

# 以太坊相关库
try:
    from eth_account import Account
    import mnemonic
    from eth_utils import to_checksum_address
except ImportError:
    print("请安装 web3 和 mnemonic: pip install web3 mnemonic")
    sys.exit(1)


@dataclass
class Config:
    """程序配置"""
    success_file: str = "success.txt"
    address_file: str = "addresses.txt"
    max_workers: int = os.cpu_count() * 2 if os.cpu_count() else 4
    batch_size: int = 100
    sleep_interval: float = 0.05




class BitcoinAddressGenerator:
    """比特币地址生成器"""
    
    @staticmethod
    def generate_address() -> Tuple[str, str]:
        """

        生成真实的比特币地址和私钥

        返回: (address, private_key_wif)

        """
        # 生成32字节随机私钥
        private_key_bytes = os.urandom(32)
        
        # 使用secp256k1曲线生成密钥对
        sk = SigningKey.from_string(private_key_bytes, curve=SECP256k1)
        vk = sk.verifying_key
        
        # 获取压缩公钥
        public_key_bytes = vk.to_string("compressed")
        
        # 计算地址 (P2PKH - Legacy地址格式)
        # SHA256
        sha256_hash = hashlib.sha256(public_key_bytes).digest()
        # RIPEMD160
        ripemd160 = hashlib.new('ripemd160')
        ripemd160.update(sha256_hash)
        hash160 = ripemd160.digest()
        
        # 添加版本字节 (0x00 for mainnet)
        version_hash160 = b'\x00' + hash160
        
        # 计算校验和 (双SHA256)
        checksum = hashlib.sha256(hashlib.sha256(version_hash160).digest()).digest()[:4]
        
        # 拼接并Base58编码
        address_bytes = version_hash160 + checksum
        address = BitcoinAddressGenerator.base58_encode(address_bytes)
        
        # 生成WIF格式私钥
        # 添加版本字节 (0x80 for mainnet) 和压缩标志 (0x01)
        extended_key = b'\x80' + private_key_bytes + b'\x01'
        wif_checksum = hashlib.sha256(hashlib.sha256(extended_key).digest()).digest()[:4]
        wif_bytes = extended_key + wif_checksum
        wif_private_key = BitcoinAddressGenerator.base58_encode(wif_bytes)
        
        return address, wif_private_key
    
    @staticmethod
    def base58_encode(data: bytes) -> str:
        """Base58编码"""
        ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
        
        # 计算前导零
        num = int.from_bytes(data, 'big')
        leading_zeros = len(data) - len(data.lstrip(b'\x00'))
        
        result = ''
        while num > 0:
            num, remainder = divmod(num, 58)
            result = ALPHABET[remainder] + result
        
        # 添加前导1 (对应前导零)
        return '1' * leading_zeros + result


class EthereumAddressGenerator:
    """以太坊地址生成器"""
    
    @staticmethod
    def generate_address() -> Tuple[str, str]:
        """

        生成以太坊地址和私钥

        返回: (address, private_key)

        """
        # 生成12个助记词 (与C#的WordCount.Twelve一致)
        m = mnemonic.Mnemonic("english")
        seed_phrase = m.generate(strength=128)  # 128 bits = 12 words
        
        # 从助记词生成钱包
        seed = m.to_seed(seed_phrase)
        
        # 使用BIP32派生第一个账户
        # 这里简化为直接生成随机账户(功能等效)
        account = Account.create()
        
        # 获取校验和地址
        address = to_checksum_address(account.address)
        private_key = account.key.hex()
        
        return address, private_key


class BruteForceTool:
    """暴力破解主程序"""
    
    def __init__(self):
        self.config = Config()
        self.target_addresses: Set[str] = set()
        self.failed_count = 0
        self.success_file_lock = threading.Lock()
        self.count_lock = threading.Lock()
        self.is_running = True
        #self.valid_license = LicenseManager.get_license_key()
        
        # 设置文件路径
        self.root_dir = Path.cwd()
        self.success_file_path = self.root_dir / self.config.success_file
        self.address_file_path = self.root_dir / self.config.address_file
    
    def load_target_addresses(self) -> bool:
        """加载目标地址"""
        if not self.address_file_path.exists():
            print(f"地址文件不存在:{self.address_file_path}")
            print("请确保在程序根目录下有 addresses.txt 文件。")
            input("按任意键退出...")
            return False
        
        try:
            with open(self.address_file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    address = line.strip()
                    if address:
                        # 不区分大小写存储
                        self.target_addresses.add(address.lower())
            
            print(f"已加载目标地址数量: {len(self.target_addresses)}")
            return True
            
        except Exception as e:
            print(f"⚠️ 读取文件时发生错误:{e}")
            input("按任意键退出...")
            return False
    
    def update_counter(self):
        """后台更新计数器"""
        while self.is_running:
            with self.count_lock:
                current = self.failed_count
            
            # 覆盖同一行显示
            print(f"\r已尝试次数: {current} ", end='', flush=True)
            time.sleep(0.3)
    
    def write_success(self, content: str):
        """写入成功匹配到文件"""
        try:
            with self.success_file_lock:
                with open(self.success_file_path, 'a', encoding='utf-8') as f:
                    f.write(content + '\n')
        except Exception as e:
            print(f"\n⚠️ 写入文件失败: {e}")
    
    def check_bitcoin(self):
        """生成并检查比特币地址"""
        try:
            address, private_key = BitcoinAddressGenerator.generate_address()
            
            if address.lower() in self.target_addresses:
                message = f"[BTC] 匹配成功: 地址={address}, 私钥={private_key}"
                print(f"\n\033[92m{message}\033[0m")  # 绿色
                self.write_success(message)
            else:
                with self.count_lock:
                    self.failed_count += 1
                    
        except Exception as e:
            # 生成失败,计入失败次数
            with self.count_lock:
                self.failed_count += 1
    
    def check_ethereum(self):
        """生成并检查以太坊地址"""
        try:
            address, private_key = EthereumAddressGenerator.generate_address()
            
            if address.lower() in self.target_addresses:
                message = f"[ETH] 匹配成功: 地址={address}, 私钥={private_key}"
                print(f"\n\033[92m{message}\033[0m")  # 绿色
                self.write_success(message)
            else:
                with self.count_lock:
                    self.failed_count += 1
                    
        except Exception as e:
            with self.count_lock:
                self.failed_count += 1
    
    def worker_batch(self, _):
        """工作线程:处理一批任务"""
        # 每个worker生成一个BTC和一个ETH地址
        self.check_bitcoin()
        self.check_ethereum()
    
    def signal_handler(self, signum, frame):
        """处理Ctrl+C信号"""
        print("\n\n🛑 收到停止信号,正在关闭...")
        self.is_running = False
    
    def run(self):
        """主运行循环"""
        import signal

        # 加载目标地址
        if not self.load_target_addresses():
            return
        
        # 设置信号处理
        signal.signal(signal.SIGINT, self.signal_handler)
        
        # 启动计数器线程
        counter_thread = threading.Thread(target=self.update_counter, daemon=True)
        counter_thread.start()
        
        print("\n🚀 开始多线程生成地址...")
        print("按 Ctrl+C 停止程序\n")
        
        try:
            with ThreadPoolExecutor(max_workers=self.config.max_workers) as executor:
                while self.is_running:
                    # 提交一批任务
                    futures = [
                        executor.submit(self.worker_batch, i) 
                        for i in range(self.config.batch_size)
                    ]
                    
                    # 等待完成(非阻塞检查is_running)
                    for future in futures:
                        if not self.is_running:
                            break
                        try:
                            future.result(timeout=1)
                        except:
                            pass
                    
                    # 短暂休息防止CPU过载
                    time.sleep(self.config.sleep_interval)
        
        except Exception as e:
            print(f"\n⚠️ 运行时错误: {e}")
        
        finally:
            self.is_running = False
            print("\n🛑 程序已停止。")
            print(f"最终尝试次数: {self.failed_count}")


def main():
    """入口函数"""
    tool = BruteForceTool()
    tool.run()


if __name__ == "__main__":
    main()