libcrypto 1.0.1__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.
- libcrypto/__init__.py +72 -0
- libcrypto/_version.py +19 -0
- libcrypto/addresses.py +191 -0
- libcrypto/bip32.py +234 -0
- libcrypto/cli.py +159 -0
- libcrypto/constants.py +288 -0
- libcrypto/formats.py +164 -0
- libcrypto/hash.py +88 -0
- libcrypto/keys.py +149 -0
- libcrypto/mnemonic.py +156 -0
- libcrypto/secp256k1.py +117 -0
- libcrypto/wallet.py +135 -0
- libcrypto-1.0.1.dist-info/METADATA +318 -0
- libcrypto-1.0.1.dist-info/RECORD +18 -0
- libcrypto-1.0.1.dist-info/WHEEL +5 -0
- libcrypto-1.0.1.dist-info/entry_points.txt +2 -0
- libcrypto-1.0.1.dist-info/licenses/LICENSE +21 -0
- libcrypto-1.0.1.dist-info/top_level.txt +1 -0
libcrypto/constants.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Cryptographic constants and configuration values for CryptoCoreLib.
|
|
3
|
+
|
|
4
|
+
This module contains all the constants used throughout the library,
|
|
5
|
+
including curve parameters, magic numbers, and cryptocurrency-specific values.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Dict, Tuple
|
|
9
|
+
|
|
10
|
+
# Secp256k1 curve parameters
|
|
11
|
+
SECP256K1_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
|
|
12
|
+
SECP256K1_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
|
|
13
|
+
SECP256K1_GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
|
|
14
|
+
SECP256K1_GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
|
|
15
|
+
SECP256K1_A = 0
|
|
16
|
+
SECP256K1_B = 7
|
|
17
|
+
|
|
18
|
+
# Maximum private key value
|
|
19
|
+
MAX_PRIVATE_KEY = SECP256K1_N - 1
|
|
20
|
+
|
|
21
|
+
# Base58 alphabet used in Bitcoin and most cryptocurrencies
|
|
22
|
+
BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
23
|
+
|
|
24
|
+
# Address version bytes for different networks
|
|
25
|
+
ADDRESS_VERSIONS = {
|
|
26
|
+
'bitcoin': {
|
|
27
|
+
'p2pkh': 0x00, # 1...
|
|
28
|
+
'p2sh': 0x05, # 3...
|
|
29
|
+
'private': 0x80, # 5...K/L (WIF)
|
|
30
|
+
},
|
|
31
|
+
'testnet': {
|
|
32
|
+
'p2pkh': 0x6F, # m/n...
|
|
33
|
+
'p2sh': 0xC4, # 2...
|
|
34
|
+
'private': 0xEF, # 9/c (WIF)
|
|
35
|
+
},
|
|
36
|
+
'litecoin': {
|
|
37
|
+
'p2pkh': 0x30, # L...
|
|
38
|
+
'p2sh': 0x32, # M...
|
|
39
|
+
'private': 0xB0, # 6... (WIF)
|
|
40
|
+
},
|
|
41
|
+
'dogecoin': {
|
|
42
|
+
'p2pkh': 0x1E, # D...
|
|
43
|
+
'p2sh': 0x16, # 9/A...
|
|
44
|
+
'private': 0x9E, # 6... (WIF)
|
|
45
|
+
},
|
|
46
|
+
'dash': {
|
|
47
|
+
'p2pkh': 0x4C, # X...
|
|
48
|
+
'p2sh': 0x10, # 7...
|
|
49
|
+
'private': 0xCC, # 7... (WIF)
|
|
50
|
+
},
|
|
51
|
+
'bitcoin_cash': {
|
|
52
|
+
'p2pkh': 0x00, # 1... (same as Bitcoin)
|
|
53
|
+
'p2sh': 0x05, # 3... (same as Bitcoin)
|
|
54
|
+
'private': 0x80, # 5...K/L (WIF)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
# Bech32 Human Readable Parts for SegWit addresses
|
|
59
|
+
BECH32_HRP = {
|
|
60
|
+
'bitcoin': 'bc',
|
|
61
|
+
'testnet': 'tb',
|
|
62
|
+
'litecoin': 'ltc',
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
# BIP-39 English (2048 words) - List is long, so I'll omit it for brevity. It was correct.
|
|
66
|
+
BIP39_WORD_LIST = (
|
|
67
|
+
'abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abstract', 'absurd', 'abuse', 'access', 'accident',
|
|
68
|
+
'account', 'accuse', 'achieve', 'acid', 'acoustic', 'acquire', 'across', 'act', 'action', 'actor', 'actress', 'actual',
|
|
69
|
+
'adapt', 'add', 'addict', 'address', 'adjust', 'admit', 'adult', 'advance', 'advice', 'aerobic', 'affair', 'afford',
|
|
70
|
+
'afraid', 'again', 'age', 'agent', 'agree', 'ahead', 'aim', 'air', 'airport', 'aisle', 'alarm', 'album', 'alcohol',
|
|
71
|
+
'alert', 'alien', 'all', 'alley', 'allow', 'almost', 'alone', 'alpha', 'already', 'also', 'alter', 'always', 'amateur',
|
|
72
|
+
'amazing', 'among', 'amount', 'amused', 'analyst', 'anchor', 'ancient', 'anger', 'angle', 'angry', 'animal', 'ankle',
|
|
73
|
+
'announce', 'annual', 'another', 'answer', 'antenna', 'antique', 'anxiety', 'any', 'apart', 'apology', 'appear',
|
|
74
|
+
'apple', 'approve', 'april', 'arch', 'arctic', 'area', 'arena', 'argue', 'arm', 'armed', 'armor', 'army', 'around',
|
|
75
|
+
'arrange', 'arrest', 'arrive', 'arrow', 'art', 'artefact', 'artist', 'artwork', 'ask', 'aspect', 'assault', 'asset',
|
|
76
|
+
'assist', 'assume', 'asthma', 'athlete', 'atom', 'attack', 'attend', 'attitude', 'attract', 'auction', 'audit',
|
|
77
|
+
'august', 'aunt', 'author', 'auto', 'autumn', 'average', 'avocado', 'avoid', 'awake', 'aware', 'away', 'awesome',
|
|
78
|
+
'awful', 'awkward', 'axis', 'baby', 'bachelor', 'bacon', 'badge', 'bag', 'balance', 'balcony', 'ball', 'bamboo',
|
|
79
|
+
'banana', 'banner', 'bar', 'barely', 'bargain', 'barrel', 'base', 'basic', 'basket', 'battle', 'beach', 'bean',
|
|
80
|
+
'beauty', 'because', 'become', 'beef', 'before', 'begin', 'behave', 'behind', 'believe', 'below', 'belt', 'bench',
|
|
81
|
+
'benefit', 'best', 'betray', 'better', 'between', 'beyond', 'bicycle', 'bid', 'bike', 'bind', 'biology', 'bird',
|
|
82
|
+
'birth', 'bitter', 'black', 'blade', 'blame', 'blanket', 'blast', 'bleak', 'bless', 'blind', 'blood', 'blossom',
|
|
83
|
+
'blouse', 'blue', 'blur', 'blush', 'board', 'boat', 'body', 'boil', 'bomb', 'bone', 'bonus', 'book', 'boost', 'border',
|
|
84
|
+
'boring', 'borrow', 'boss', 'bottom', 'bounce', 'box', 'boy', 'bracket', 'brain', 'brand', 'brass', 'brave', 'bread',
|
|
85
|
+
'breeze', 'brick', 'bridge', 'brief', 'bright', 'bring', 'brisk', 'broccoli', 'broken', 'bronze', 'broom', 'brother',
|
|
86
|
+
'brown', 'brush', 'bubble', 'buddy', 'budget', 'buffalo', 'build', 'bulb', 'bulk', 'bullet', 'bundle', 'bunker',
|
|
87
|
+
'burden', 'burger', 'burst', 'bus', 'business', 'busy', 'butter', 'buyer', 'buzz', 'cabbage', 'cabin', 'cable',
|
|
88
|
+
'cactus', 'cage', 'cake', 'call', 'calm', 'camera', 'camp', 'can', 'canal', 'cancel', 'candy', 'cannon', 'canoe',
|
|
89
|
+
'canvas', 'canyon', 'capable', 'capital', 'captain', 'car', 'carbon', 'card', 'cargo', 'carpet', 'carry', 'cart',
|
|
90
|
+
'case', 'cash', 'casino', 'castle', 'casual', 'cat', 'catalog', 'catch', 'category', 'cattle', 'caught', 'cause',
|
|
91
|
+
'caution', 'cave', 'ceiling', 'celery', 'cement', 'census', 'century', 'cereal', 'certain', 'chair', 'chalk',
|
|
92
|
+
'champion', 'change', 'chaos', 'chapter', 'charge', 'chase', 'chat', 'cheap', 'check', 'cheese', 'chef', 'cherry',
|
|
93
|
+
'chest', 'chicken', 'chief', 'child', 'chimney', 'choice', 'choose', 'chronic', 'chuckle', 'chunk', 'churn', 'cigar',
|
|
94
|
+
'cinnamon', 'circle', 'citizen', 'city', 'civil', 'claim', 'clap', 'clarify', 'claw', 'clay', 'clean', 'clerk',
|
|
95
|
+
'clever', 'click', 'client', 'cliff', 'climb', 'clinic', 'clip', 'clock', 'clog', 'close', 'cloth', 'cloud', 'clown',
|
|
96
|
+
'club', 'clump', 'cluster', 'clutch', 'coach', 'coast', 'coconut', 'code', 'coffee', 'coil', 'coin', 'collect', 'color',
|
|
97
|
+
'column', 'combine', 'come', 'comfort', 'comic', 'common', 'company', 'concert', 'conduct', 'confirm', 'congress',
|
|
98
|
+
'connect', 'consider', 'control', 'convince', 'cook', 'cool', 'copper', 'copy', 'coral', 'core', 'corn', 'correct',
|
|
99
|
+
'cost', 'cotton', 'couch', 'country', 'couple', 'course', 'cousin', 'cover', 'coyote', 'crack', 'cradle', 'craft',
|
|
100
|
+
'cram', 'crane', 'crash', 'crater', 'crawl', 'crazy', 'cream', 'credit', 'creek', 'crew', 'cricket', 'crime', 'crisp',
|
|
101
|
+
'critic', 'crop', 'cross', 'crouch', 'crowd', 'crucial', 'cruel', 'cruise', 'crumble', 'crunch', 'crush', 'cry',
|
|
102
|
+
'crystal', 'cube', 'culture', 'cup', 'cupboard', 'curious', 'current', 'curtain', 'curve', 'cushion', 'custom', 'cute',
|
|
103
|
+
'cycle', 'dad', 'damage', 'damp', 'dance', 'danger', 'daring', 'dash', 'daughter', 'dawn', 'day', 'deal', 'debate',
|
|
104
|
+
'debris', 'decade', 'december', 'decide', 'decline', 'decorate', 'decrease', 'deer', 'defense', 'define', 'defy',
|
|
105
|
+
'degree', 'delay', 'deliver', 'demand', 'demise', 'denial', 'dentist', 'deny', 'depart', 'depend', 'deposit', 'depth',
|
|
106
|
+
'deputy', 'derive', 'describe', 'desert', 'design', 'desk', 'despair', 'destroy', 'detail', 'detect', 'develop',
|
|
107
|
+
'device', 'devote', 'diagram', 'dial', 'diamond', 'diary', 'dice', 'diesel', 'diet', 'differ', 'digital', 'dignity',
|
|
108
|
+
'dilemma', 'dinner', 'dinosaur', 'direct', 'dirt', 'disagree', 'discover', 'disease', 'dish', 'dismiss', 'disorder',
|
|
109
|
+
'display', 'distance', 'divert', 'divide', 'divorce', 'dizzy', 'doctor', 'document', 'dog', 'doll', 'dolphin', 'domain',
|
|
110
|
+
'donate', 'donkey', 'donor', 'door', 'dose', 'double', 'dove', 'draft', 'dragon', 'drama', 'drastic', 'draw', 'dream',
|
|
111
|
+
'dress', 'drift', 'drill', 'drink', 'drip', 'drive', 'drop', 'drum', 'dry', 'duck', 'dumb', 'dune', 'during', 'dust',
|
|
112
|
+
'dutch', 'duty', 'dwarf', 'dynamic', 'eager', 'eagle', 'early', 'earn', 'earth', 'easily', 'east', 'easy', 'echo',
|
|
113
|
+
'ecology', 'economy', 'edge', 'edit', 'educate', 'effort', 'egg', 'eight', 'either', 'elbow', 'elder', 'electric',
|
|
114
|
+
'elegant', 'element', 'elephant', 'elevator', 'elite', 'else', 'embark', 'embody', 'embrace', 'emerge', 'emotion',
|
|
115
|
+
'employ', 'empower', 'empty', 'enable', 'enact', 'end', 'endless', 'endorse', 'enemy', 'energy', 'enforce', 'engage',
|
|
116
|
+
'engine', 'enhance', 'enjoy', 'enlist', 'enough', 'enrich', 'enroll', 'ensure', 'enter', 'entire', 'entry', 'envelope',
|
|
117
|
+
'episode', 'equal', 'equip', 'era', 'erase', 'erode', 'erosion', 'error', 'erupt', 'escape', 'essay', 'essence',
|
|
118
|
+
'estate', 'eternal', 'ethics', 'evidence', 'evil', 'evoke', 'evolve', 'exact', 'example', 'excess', 'exchange',
|
|
119
|
+
'excite', 'exclude', 'excuse', 'execute', 'exercise', 'exhaust', 'exhibit', 'exile', 'exist', 'exit', 'exotic',
|
|
120
|
+
'expand', 'expect', 'expire', 'explain', 'expose', 'express', 'extend', 'extra', 'eye', 'eyebrow', 'fabric', 'face',
|
|
121
|
+
'faculty', 'fade', 'faint', 'faith', 'fall', 'false', 'fame', 'family', 'famous', 'fan', 'fancy', 'fantasy', 'farm',
|
|
122
|
+
'fashion', 'fat', 'fatal', 'father', 'fatigue', 'fault', 'favorite', 'feature', 'february', 'federal', 'fee', 'feed',
|
|
123
|
+
'feel', 'female', 'fence', 'festival', 'fetch', 'fever', 'few', 'fiber', 'fiction', 'field', 'figure', 'file', 'film',
|
|
124
|
+
'filter', 'final', 'find', 'fine', 'finger', 'finish', 'fire', 'firm', 'first', 'fiscal', 'fish', 'fit', 'fitness',
|
|
125
|
+
'fix', 'flag', 'flame', 'flash', 'flat', 'flavor', 'flee', 'flight', 'flip', 'float', 'flock', 'floor', 'flower',
|
|
126
|
+
'fluid', 'flush', 'fly', 'foam', 'focus', 'fog', 'foil', 'fold', 'follow', 'food', 'foot', 'force', 'forest', 'forget',
|
|
127
|
+
'fork', 'fortune', 'forum', 'forward', 'fossil', 'foster', 'found', 'fox', 'fragile', 'frame', 'frequent', 'fresh',
|
|
128
|
+
'friend', 'fringe', 'frog', 'front', 'frost', 'frown', 'frozen', 'fruit', 'fuel', 'fun', 'funny', 'furnace', 'fury',
|
|
129
|
+
'future', 'gadget', 'gain', 'galaxy', 'gallery', 'game', 'gap', 'garage', 'garbage', 'garden', 'garlic', 'garment',
|
|
130
|
+
'gas', 'gasp', 'gate', 'gather', 'gauge', 'gaze', 'general', 'genius', 'genre', 'gentle', 'genuine', 'gesture', 'ghost',
|
|
131
|
+
'giant', 'gift', 'giggle', 'ginger', 'giraffe', 'girl', 'give', 'glad', 'glance', 'glare', 'glass', 'glide', 'glimpse',
|
|
132
|
+
'globe', 'gloom', 'glory', 'glove', 'glow', 'glue', 'goat', 'goddess', 'gold', 'good', 'goose', 'gorilla', 'gospel',
|
|
133
|
+
'gossip', 'govern', 'gown', 'grab', 'grace', 'grain', 'grant', 'grape', 'grass', 'gravity', 'great', 'green', 'grid',
|
|
134
|
+
'grief', 'grit', 'grocery', 'group', 'grow', 'grunt', 'guard', 'guess', 'guide', 'guilt', 'guitar', 'gun', 'gym',
|
|
135
|
+
'habit', 'hair', 'half', 'hammer', 'hamster', 'hand', 'happy', 'harbor', 'hard', 'harsh', 'harvest', 'hat', 'have',
|
|
136
|
+
'hawk', 'hazard', 'head', 'health', 'heart', 'heavy', 'hedgehog', 'height', 'hello', 'helmet', 'help', 'hen', 'hero',
|
|
137
|
+
'hidden', 'high', 'hill', 'hint', 'hip', 'hire', 'history', 'hobby', 'hockey', 'hold', 'hole', 'holiday', 'hollow',
|
|
138
|
+
'home', 'honey', 'hood', 'hope', 'horn', 'horror', 'horse', 'hospital', 'host', 'hotel', 'hour', 'hover', 'hub', 'huge',
|
|
139
|
+
'human', 'humble', 'humor', 'hundred', 'hungry', 'hunt', 'hurdle', 'hurry', 'hurt', 'husband', 'hybrid', 'ice', 'icon',
|
|
140
|
+
'idea', 'identify', 'idle', 'ignore', 'ill', 'illegal', 'illness', 'image', 'imitate', 'immense', 'immune', 'impact',
|
|
141
|
+
'impose', 'improve', 'impulse', 'inch', 'include', 'income', 'increase', 'index', 'indicate', 'indoor', 'industry',
|
|
142
|
+
'infant', 'inflict', 'inform', 'inhale', 'inherit', 'initial', 'inject', 'injury', 'inmate', 'inner', 'innocent',
|
|
143
|
+
'input', 'inquiry', 'insane', 'insect', 'inside', 'inspire', 'install', 'intact', 'interest', 'into', 'invest',
|
|
144
|
+
'invite', 'involve', 'iron', 'island', 'isolate', 'issue', 'item', 'ivory', 'jacket', 'jaguar', 'jar', 'jazz',
|
|
145
|
+
'jealous', 'jeans', 'jelly', 'jewel', 'job', 'join', 'joke', 'journey', 'joy', 'judge', 'juice', 'jump', 'jungle',
|
|
146
|
+
'junior', 'junk', 'just', 'kangaroo', 'keen', 'keep', 'ketchup', 'key', 'kick', 'kid', 'kidney', 'kind', 'kingdom',
|
|
147
|
+
'kiss', 'kit', 'kitchen', 'kite', 'kitten', 'kiwi', 'knee', 'knife', 'knock', 'know', 'lab', 'label', 'labor', 'ladder',
|
|
148
|
+
'lady', 'lake', 'lamp', 'language', 'laptop', 'large', 'later', 'latin', 'laugh', 'laundry', 'lava', 'law', 'lawn',
|
|
149
|
+
'lawsuit', 'layer', 'lazy', 'leader', 'leaf', 'learn', 'leave', 'lecture', 'left', 'leg', 'legal', 'legend', 'leisure',
|
|
150
|
+
'lemon', 'lend', 'length', 'lens', 'leopard', 'lesson', 'letter', 'level', 'liar', 'liberty', 'library', 'license',
|
|
151
|
+
'life', 'lift', 'light', 'like', 'limb', 'limit', 'link', 'lion', 'liquid', 'list', 'little', 'live', 'lizard', 'load',
|
|
152
|
+
'loan', 'lobster', 'local', 'lock', 'logic', 'lonely', 'long', 'loop', 'lottery', 'loud', 'lounge', 'love', 'loyal',
|
|
153
|
+
'lucky', 'luggage', 'lumber', 'lunar', 'lunch', 'luxury', 'lyrics', 'machine', 'mad', 'magic', 'magnet', 'maid', 'mail',
|
|
154
|
+
'main', 'major', 'make', 'mammal', 'man', 'manage', 'mandate', 'mango', 'mansion', 'manual', 'maple', 'marble', 'march',
|
|
155
|
+
'margin', 'marine', 'market', 'marriage', 'mask', 'mass', 'master', 'match', 'material', 'math', 'matrix', 'matter',
|
|
156
|
+
'maximum', 'maze', 'meadow', 'mean', 'measure', 'meat', 'mechanic', 'medal', 'media', 'melody', 'melt', 'member',
|
|
157
|
+
'memory', 'mention', 'menu', 'mercy', 'merge', 'merit', 'merry', 'mesh', 'message', 'metal', 'method', 'middle',
|
|
158
|
+
'midnight', 'milk', 'million', 'mimic', 'mind', 'minimum', 'minor', 'minute', 'miracle', 'mirror', 'misery', 'miss',
|
|
159
|
+
'mistake', 'mix', 'mixed', 'mixture', 'mobile', 'model', 'modify', 'mom', 'moment', 'monitor', 'monkey', 'monster',
|
|
160
|
+
'month', 'moon', 'moral', 'more', 'morning', 'mosquito', 'mother', 'motion', 'motor', 'mountain', 'mouse', 'move',
|
|
161
|
+
'movie', 'much', 'muffin', 'mule', 'multiply', 'muscle', 'museum', 'mushroom', 'music', 'must', 'mutual', 'myself',
|
|
162
|
+
'mystery', 'myth', 'naive', 'name', 'napkin', 'narrow', 'nasty', 'nation', 'nature', 'near', 'neck', 'need', 'negative',
|
|
163
|
+
'neglect', 'neither', 'nephew', 'nerve', 'nest', 'net', 'network', 'neutral', 'never', 'news', 'next', 'nice', 'night',
|
|
164
|
+
'noble', 'noise', 'nominee', 'noodle', 'normal', 'north', 'nose', 'notable', 'note', 'nothing', 'notice', 'novel',
|
|
165
|
+
'now', 'nuclear', 'number', 'nurse', 'nut', 'oak', 'obey', 'object', 'oblige', 'obscure', 'observe', 'obtain',
|
|
166
|
+
'obvious', 'occur', 'ocean', 'october', 'odor', 'off', 'offer', 'office', 'often', 'oil', 'okay', 'old', 'olive',
|
|
167
|
+
'olympic', 'omit', 'once', 'one', 'onion', 'online', 'only', 'open', 'opera', 'opinion', 'oppose', 'option', 'orange',
|
|
168
|
+
'orbit', 'orchard', 'order', 'ordinary', 'organ', 'orient', 'original', 'orphan', 'ostrich', 'other', 'outdoor',
|
|
169
|
+
'outer', 'output', 'outside', 'oval', 'oven', 'over', 'own', 'owner', 'oxygen', 'oyster', 'ozone', 'pact', 'paddle',
|
|
170
|
+
'page', 'pair', 'palace', 'palm', 'panda', 'panel', 'panic', 'panther', 'paper', 'parade', 'parent', 'park', 'parrot',
|
|
171
|
+
'party', 'pass', 'patch', 'path', 'patient', 'patrol', 'pattern', 'pause', 'pave', 'payment', 'peace', 'peanut', 'pear',
|
|
172
|
+
'peasant', 'pelican', 'pen', 'penalty', 'pencil', 'people', 'pepper', 'perfect', 'permit', 'person', 'pet', 'phone',
|
|
173
|
+
'photo', 'phrase', 'physical', 'piano', 'picnic', 'picture', 'piece', 'pig', 'pigeon', 'pill', 'pilot', 'pink',
|
|
174
|
+
'pioneer', 'pipe', 'pistol', 'pitch', 'pizza', 'place', 'planet', 'plastic', 'plate', 'play', 'please', 'pledge',
|
|
175
|
+
'pluck', 'plug', 'plunge', 'poem', 'poet', 'point', 'polar', 'pole', 'police', 'pond', 'pony', 'pool', 'popular',
|
|
176
|
+
'portion', 'position', 'possible', 'post', 'potato', 'pottery', 'poverty', 'powder', 'power', 'practice', 'praise',
|
|
177
|
+
'predict', 'prefer', 'prepare', 'present', 'pretty', 'prevent', 'price', 'pride', 'primary', 'print', 'priority',
|
|
178
|
+
'prison', 'private', 'prize', 'problem', 'process', 'produce', 'profit', 'program', 'project', 'promote', 'proof',
|
|
179
|
+
'property', 'prosper', 'protect', 'proud', 'provide', 'public', 'pudding', 'pull', 'pulp', 'pulse', 'pumpkin', 'punch',
|
|
180
|
+
'pupil', 'puppy', 'purchase', 'purity', 'purpose', 'purse', 'push', 'put', 'puzzle', 'pyramid', 'quality', 'quantum',
|
|
181
|
+
'quarter', 'question', 'quick', 'quit', 'quiz', 'quote', 'rabbit', 'raccoon', 'race', 'rack', 'radar', 'radio', 'rail',
|
|
182
|
+
'rain', 'raise', 'rally', 'ramp', 'ranch', 'random', 'range', 'rapid', 'rare', 'rate', 'rather', 'raven', 'raw',
|
|
183
|
+
'razor', 'ready', 'real', 'reason', 'rebel', 'rebuild', 'recall', 'receive', 'recipe', 'record', 'recycle', 'reduce',
|
|
184
|
+
'reflect', 'reform', 'refuse', 'region', 'regret', 'regular', 'reject', 'relax', 'release', 'relief', 'rely', 'remain',
|
|
185
|
+
'remember', 'remind', 'remove', 'render', 'renew', 'rent', 'reopen', 'repair', 'repeat', 'replace', 'report', 'require',
|
|
186
|
+
'rescue', 'resemble', 'resist', 'resource', 'response', 'result', 'retire', 'retreat', 'return', 'reunion', 'reveal',
|
|
187
|
+
'review', 'reward', 'rhythm', 'rib', 'ribbon', 'rice', 'rich', 'ride', 'ridge', 'rifle', 'right', 'rigid', 'ring',
|
|
188
|
+
'riot', 'ripple', 'risk', 'ritual', 'rival', 'river', 'road', 'roast', 'robot', 'robust', 'rocket', 'romance', 'roof',
|
|
189
|
+
'rookie', 'room', 'rose', 'rotate', 'rough', 'round', 'route', 'royal', 'rubber', 'rude', 'rug', 'rule', 'run',
|
|
190
|
+
'runway', 'rural', 'sad', 'saddle', 'sadness', 'safe', 'sail', 'salad', 'salmon', 'salon', 'salt', 'salute', 'same',
|
|
191
|
+
'sample', 'sand', 'satisfy', 'satoshi', 'sauce', 'sausage', 'save', 'say', 'scale', 'scan', 'scare', 'scatter', 'scene',
|
|
192
|
+
'scheme', 'school', 'science', 'scissors', 'scorpion', 'scout', 'scrap', 'screen', 'script', 'scrub', 'sea', 'search',
|
|
193
|
+
'season', 'seat', 'second', 'secret', 'section', 'security', 'seed', 'seek', 'segment', 'select', 'sell', 'seminar',
|
|
194
|
+
'senior', 'sense', 'sentence', 'series', 'service', 'session', 'settle', 'setup', 'seven', 'shadow', 'shaft', 'shallow',
|
|
195
|
+
'share', 'shed', 'shell', 'sheriff', 'shield', 'shift', 'shine', 'ship', 'shiver', 'shock', 'shoe', 'shoot', 'shop',
|
|
196
|
+
'short', 'shoulder', 'shove', 'shrimp', 'shrug', 'shuffle', 'shy', 'sibling', 'sick', 'side', 'siege', 'sight', 'sign',
|
|
197
|
+
'silent', 'silk', 'silly', 'silver', 'similar', 'simple', 'since', 'sing', 'siren', 'sister', 'situate', 'six', 'size',
|
|
198
|
+
'skate', 'sketch', 'ski', 'skill', 'skin', 'skirt', 'skull', 'slab', 'slam', 'sleep', 'slender', 'slice', 'slide',
|
|
199
|
+
'slight', 'slim', 'slogan', 'slot', 'slow', 'slush', 'small', 'smart', 'smile', 'smoke', 'smooth', 'snack', 'snake',
|
|
200
|
+
'snap', 'sniff', 'snow', 'soap', 'soccer', 'social', 'sock', 'soda', 'soft', 'solar', 'soldier', 'solid', 'solution',
|
|
201
|
+
'solve', 'someone', 'song', 'soon', 'sorry', 'sort', 'soul', 'sound', 'soup', 'source', 'south', 'space', 'spare',
|
|
202
|
+
'spatial', 'spawn', 'speak', 'special', 'speed', 'spell', 'spend', 'sphere', 'spice', 'spider', 'spike', 'spin',
|
|
203
|
+
'spirit', 'split', 'spoil', 'sponsor', 'spoon', 'sport', 'spot', 'spray', 'spread', 'spring', 'spy', 'square',
|
|
204
|
+
'squeeze', 'squirrel', 'stable', 'stadium', 'staff', 'stage', 'stairs', 'stamp', 'stand', 'start', 'state', 'stay',
|
|
205
|
+
'steak', 'steel', 'stem', 'step', 'stereo', 'stick', 'still', 'sting', 'stock', 'stomach', 'stone', 'stool', 'story',
|
|
206
|
+
'stove', 'strategy', 'street', 'strike', 'strong', 'struggle', 'student', 'stuff', 'stumble', 'style', 'subject',
|
|
207
|
+
'submit', 'subway', 'success', 'such', 'sudden', 'suffer', 'sugar', 'suggest', 'suit', 'summer', 'sun', 'sunny',
|
|
208
|
+
'sunset', 'super', 'supply', 'supreme', 'sure', 'surface', 'surge', 'surprise', 'surround', 'survey', 'suspect',
|
|
209
|
+
'sustain', 'swallow', 'swamp', 'swap', 'swarm', 'swear', 'sweet', 'swift', 'swim', 'swing', 'switch', 'sword', 'symbol',
|
|
210
|
+
'symptom', 'syrup', 'system', 'table', 'tackle', 'tag', 'tail', 'talent', 'talk', 'tank', 'tape', 'target', 'task',
|
|
211
|
+
'taste', 'tattoo', 'taxi', 'teach', 'team', 'tell', 'ten', 'tenant', 'tennis', 'tent', 'term', 'test', 'text', 'thank',
|
|
212
|
+
'that', 'theme', 'then', 'theory', 'there', 'they', 'thing', 'this', 'thought', 'three', 'thrive', 'throw', 'thumb',
|
|
213
|
+
'thunder', 'ticket', 'tide', 'tiger', 'tilt', 'timber', 'time', 'tiny', 'tip', 'tired', 'tissue', 'title', 'toast',
|
|
214
|
+
'tobacco', 'today', 'toddler', 'toe', 'together', 'toilet', 'token', 'tomato', 'tomorrow', 'tone', 'tongue', 'tonight',
|
|
215
|
+
'tool', 'tooth', 'top', 'topic', 'topple', 'torch', 'tornado', 'tortoise', 'toss', 'total', 'tourist', 'toward',
|
|
216
|
+
'tower', 'town', 'toy', 'track', 'trade', 'traffic', 'tragic', 'train', 'transfer', 'trap', 'trash', 'travel', 'tray',
|
|
217
|
+
'treat', 'tree', 'trend', 'trial', 'tribe', 'trick', 'trigger', 'trim', 'trip', 'trophy', 'trouble', 'truck', 'true',
|
|
218
|
+
'truly', 'trumpet', 'trust', 'truth', 'try', 'tube', 'tuition', 'tumble', 'tuna', 'tunnel', 'turkey', 'turn', 'turtle',
|
|
219
|
+
'twelve', 'twenty', 'twice', 'twin', 'twist', 'two', 'type', 'typical', 'ugly', 'umbrella', 'unable', 'unaware',
|
|
220
|
+
'uncle', 'uncover', 'under', 'undo', 'unfair', 'unfold', 'unhappy', 'uniform', 'unique', 'unit', 'universe', 'unknown',
|
|
221
|
+
'unlock', 'until', 'unusual', 'unveil', 'update', 'upgrade', 'uphold', 'upon', 'upper', 'upset', 'urban', 'urge',
|
|
222
|
+
'usage', 'use', 'used', 'useful', 'useless', 'usual', 'utility', 'vacant', 'vacuum', 'vague', 'valid', 'valley',
|
|
223
|
+
'valve', 'van', 'vanish', 'vapor', 'various', 'vast', 'vault', 'vehicle', 'velvet', 'vendor', 'venture', 'venue',
|
|
224
|
+
'verb', 'verify', 'version', 'very', 'vessel', 'veteran', 'viable', 'vibrant', 'vicious', 'victory', 'video', 'view',
|
|
225
|
+
'village', 'vintage', 'violin', 'virtual', 'virus', 'visa', 'visit', 'visual', 'vital', 'vivid', 'vocal', 'voice',
|
|
226
|
+
'void', 'volcano', 'volume', 'vote', 'voyage', 'wage', 'wagon', 'wait', 'walk', 'wall', 'walnut', 'want', 'warfare',
|
|
227
|
+
'warm', 'warrior', 'wash', 'wasp', 'waste', 'water', 'wave', 'way', 'wealth', 'weapon', 'wear', 'weasel', 'weather',
|
|
228
|
+
'web', 'wedding', 'weekend', 'weird', 'welcome', 'west', 'wet', 'whale', 'what', 'wheat', 'wheel', 'when', 'where',
|
|
229
|
+
'whip', 'whisper', 'wide', 'width', 'wife', 'wild', 'will', 'win', 'window', 'wine', 'wing', 'wink', 'winner', 'winter',
|
|
230
|
+
'wire', 'wisdom', 'wise', 'wish', 'witness', 'wolf', 'woman', 'wonder', 'wood', 'wool', 'word', 'work', 'world',
|
|
231
|
+
'worry', 'worth', 'wrap', 'wreck', 'wrestle', 'wrist', 'write', 'wrong', 'yard', 'year', 'yellow', 'you', 'young',
|
|
232
|
+
'youth', 'zebra', 'zero', 'zone', 'zoo')
|
|
233
|
+
|
|
234
|
+
# BIP-39 constants
|
|
235
|
+
BIP39_ENTROPY_BITS = {
|
|
236
|
+
12: 128, 15: 160, 18: 192, 21: 224, 24: 256
|
|
237
|
+
}
|
|
238
|
+
BIP39_CHECKSUM_BITS = {
|
|
239
|
+
12: 4, 15: 5, 18: 6, 21: 7, 24: 8
|
|
240
|
+
}
|
|
241
|
+
VALID_MNEMONIC_LENGTHS = [12, 15, 18, 21, 24]
|
|
242
|
+
PBKDF2_ITERATIONS = 2048
|
|
243
|
+
PBKDF2_HMAC_DKLEN = 64
|
|
244
|
+
|
|
245
|
+
# BIP-32 constants
|
|
246
|
+
BIP32_HARDENED_OFFSET = 0x80000000
|
|
247
|
+
BIP32_HMAC_KEY = b"Bitcoin seed"
|
|
248
|
+
MAX_BIP32_INDEX = 0xFFFFFFFF
|
|
249
|
+
XPRV_MAINNET = 0x0488ADE4
|
|
250
|
+
XPUB_MAINNET = 0x0488B21E
|
|
251
|
+
XPRV_TESTNET = 0x04358394
|
|
252
|
+
XPUB_TESTNET = 0x043587CF
|
|
253
|
+
|
|
254
|
+
# BIP-44 coin types
|
|
255
|
+
BIP44_COIN_TYPES = {
|
|
256
|
+
'bitcoin': 0,
|
|
257
|
+
'testnet': 1,
|
|
258
|
+
'litecoin': 2,
|
|
259
|
+
'dogecoin': 3,
|
|
260
|
+
'dash': 5,
|
|
261
|
+
'ethereum': 60,
|
|
262
|
+
'bitcoin_cash': 145,
|
|
263
|
+
'tron': 195,
|
|
264
|
+
'ripple': 144,
|
|
265
|
+
'solana': 501, # Note: Uses Ed25519, not secp256k1
|
|
266
|
+
'ton': 607, # Note: Uses Ed25519, not secp256k1
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
# Error messages
|
|
270
|
+
ERROR_MESSAGES = {
|
|
271
|
+
'invalid_mnemonic_length': 'Invalid mnemonic length. Must be 12, 15, 18, 21, or 24 words.',
|
|
272
|
+
'invalid_mnemonic_word': 'Invalid word in mnemonic phrase.',
|
|
273
|
+
'invalid_mnemonic_checksum': 'Invalid mnemonic checksum.',
|
|
274
|
+
'invalid_entropy_length': 'Invalid entropy length.',
|
|
275
|
+
'invalid_private_key': 'Invalid private key.',
|
|
276
|
+
'invalid_public_key': 'Invalid public key.',
|
|
277
|
+
'invalid_address': 'Invalid address format.',
|
|
278
|
+
'unsupported_network': 'Unsupported network.',
|
|
279
|
+
'unsupported_address_type': 'Unsupported address type.',
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
__all__ = [
|
|
283
|
+
'SECP256K1_P', 'SECP256K1_N', 'SECP256K1_GX', 'SECP256K1_GY', 'SECP256K1_A', 'SECP256K1_B', 'MAX_PRIVATE_KEY',
|
|
284
|
+
'BASE58_ALPHABET', 'ADDRESS_VERSIONS', 'BECH32_HRP', 'BIP39_WORD_LIST', 'BIP39_ENTROPY_BITS',
|
|
285
|
+
'BIP39_CHECKSUM_BITS', 'VALID_MNEMONIC_LENGTHS', 'PBKDF2_ITERATIONS', 'PBKDF2_HMAC_DKLEN',
|
|
286
|
+
'BIP32_HARDENED_OFFSET', 'BIP32_HMAC_KEY', 'MAX_BIP32_INDEX', 'XPRV_MAINNET', 'XPUB_MAINNET',
|
|
287
|
+
'XPRV_TESTNET', 'XPUB_TESTNET', 'BIP44_COIN_TYPES', 'ERROR_MESSAGES'
|
|
288
|
+
]
|
libcrypto/formats.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Format Conversion Utilities
|
|
3
|
+
|
|
4
|
+
This module provides utilities for converting between different cryptocurrency
|
|
5
|
+
key and address formats including Base58 encoding/decoding, WIF format, and
|
|
6
|
+
various hex/bytes conversions.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Union, Tuple
|
|
10
|
+
|
|
11
|
+
from .hash import double_sha256
|
|
12
|
+
from .constants import BASE58_ALPHABET, ADDRESS_VERSIONS
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class InvalidFormatError(ValueError):
|
|
16
|
+
"""Raised when a format conversion fails."""
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def bytes_to_int(data: bytes, byteorder: str = 'big') -> int:
|
|
21
|
+
"""Converts a byte string to an integer."""
|
|
22
|
+
return int.from_bytes(data, byteorder=byteorder)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def int_to_bytes(value: int, length: int = 0, byteorder: str = 'big') -> bytes:
|
|
26
|
+
"""Converts an integer to a byte string of a specified or minimal length."""
|
|
27
|
+
if value < 0:
|
|
28
|
+
raise ValueError("Negative numbers are not supported.")
|
|
29
|
+
if length == 0:
|
|
30
|
+
if value == 0:
|
|
31
|
+
return b'\x00'
|
|
32
|
+
length = (value.bit_length() + 7) // 8
|
|
33
|
+
try:
|
|
34
|
+
return value.to_bytes(length, byteorder=byteorder)
|
|
35
|
+
except OverflowError as e:
|
|
36
|
+
raise ValueError(f"Value {value} is too large for {length} bytes.") from e
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def bytes_to_hex(data: bytes) -> str:
|
|
40
|
+
"""Converts a byte string to its hexadecimal representation."""
|
|
41
|
+
return data.hex()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def hex_to_bytes(hex_str: str) -> bytes:
|
|
45
|
+
"""Converts a hexadecimal string to a byte string."""
|
|
46
|
+
if hex_str.startswith(('0x', '0X')):
|
|
47
|
+
hex_str = hex_str[2:]
|
|
48
|
+
if len(hex_str) % 2 != 0:
|
|
49
|
+
hex_str = '0' + hex_str
|
|
50
|
+
try:
|
|
51
|
+
return bytes.fromhex(hex_str)
|
|
52
|
+
except ValueError as e:
|
|
53
|
+
raise InvalidFormatError(f"Invalid hexadecimal string: {e}") from e
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def base58_encode(data: bytes, alphabet: str = BASE58_ALPHABET) -> str:
|
|
57
|
+
"""Encode bytes to Base58 string."""
|
|
58
|
+
if not data:
|
|
59
|
+
return ""
|
|
60
|
+
num = bytes_to_int(data)
|
|
61
|
+
encoded = ""
|
|
62
|
+
while num > 0:
|
|
63
|
+
num, remainder = divmod(num, 58)
|
|
64
|
+
encoded = alphabet[remainder] + encoded
|
|
65
|
+
|
|
66
|
+
# Add leading zeros
|
|
67
|
+
leading_zeros = len(data) - len(data.lstrip(b'\x00'))
|
|
68
|
+
return alphabet[0] * leading_zeros + encoded
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def base58_decode(encoded: str, alphabet: str = BASE58_ALPHABET) -> bytes:
|
|
72
|
+
"""Decode Base58 string to bytes."""
|
|
73
|
+
if not encoded:
|
|
74
|
+
return b""
|
|
75
|
+
num = 0
|
|
76
|
+
for char in encoded:
|
|
77
|
+
if char not in alphabet:
|
|
78
|
+
raise InvalidFormatError(f"Invalid character '{char}' in Base58 string")
|
|
79
|
+
num = num * 58 + alphabet.index(char)
|
|
80
|
+
|
|
81
|
+
decoded = int_to_bytes(num)
|
|
82
|
+
|
|
83
|
+
# Add leading zeros
|
|
84
|
+
leading_zeros = len(encoded) - len(encoded.lstrip(alphabet[0]))
|
|
85
|
+
return b'\x00' * leading_zeros + decoded
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def base58_check_encode(data: bytes, alphabet: str = BASE58_ALPHABET) -> str:
|
|
89
|
+
"""Encode bytes to Base58Check (Base58 with checksum)."""
|
|
90
|
+
checksum = double_sha256(data)[:4]
|
|
91
|
+
return base58_encode(data + checksum, alphabet)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def base58_check_decode(encoded: str, alphabet: str = BASE58_ALPHABET) -> bytes:
|
|
95
|
+
"""Decode Base58Check string to bytes and verify checksum."""
|
|
96
|
+
decoded = base58_decode(encoded, alphabet)
|
|
97
|
+
if len(decoded) < 4:
|
|
98
|
+
raise InvalidFormatError("Base58Check string too short")
|
|
99
|
+
|
|
100
|
+
data, checksum = decoded[:-4], decoded[-4:]
|
|
101
|
+
expected_checksum = double_sha256(data)[:4]
|
|
102
|
+
|
|
103
|
+
if checksum != expected_checksum:
|
|
104
|
+
raise InvalidFormatError("Invalid Base58Check checksum")
|
|
105
|
+
|
|
106
|
+
return data
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def private_key_to_wif(private_key: Union[bytes, int], compressed: bool = True, network: str = 'bitcoin') -> str:
|
|
110
|
+
"""Convert a private key to Wallet Import Format (WIF)."""
|
|
111
|
+
if isinstance(private_key, int):
|
|
112
|
+
private_key = int_to_bytes(private_key, 32)
|
|
113
|
+
elif not (isinstance(private_key, bytes) and len(private_key) == 32):
|
|
114
|
+
raise InvalidFormatError("Private key must be a 32-byte string or an integer.")
|
|
115
|
+
|
|
116
|
+
if network not in ADDRESS_VERSIONS:
|
|
117
|
+
raise InvalidFormatError(f"Unsupported network: {network}")
|
|
118
|
+
|
|
119
|
+
version_byte = ADDRESS_VERSIONS[network]['private']
|
|
120
|
+
payload = bytes([version_byte]) + private_key
|
|
121
|
+
|
|
122
|
+
if compressed:
|
|
123
|
+
payload += b'\x01'
|
|
124
|
+
|
|
125
|
+
return base58_check_encode(payload)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def wif_to_private_key(wif: str) -> Tuple[bytes, bool, str]:
|
|
129
|
+
"""Convert WIF to private key."""
|
|
130
|
+
try:
|
|
131
|
+
decoded = base58_check_decode(wif)
|
|
132
|
+
except InvalidFormatError as e:
|
|
133
|
+
raise InvalidFormatError(f"Invalid WIF format: {e}") from e
|
|
134
|
+
|
|
135
|
+
if len(decoded) not in [33, 34]:
|
|
136
|
+
raise InvalidFormatError(f"Invalid WIF length: {len(decoded)}")
|
|
137
|
+
|
|
138
|
+
version_byte = decoded[0]
|
|
139
|
+
network = None
|
|
140
|
+
for net_name, versions in ADDRESS_VERSIONS.items():
|
|
141
|
+
if versions['private'] == version_byte:
|
|
142
|
+
network = net_name
|
|
143
|
+
break
|
|
144
|
+
|
|
145
|
+
if network is None:
|
|
146
|
+
raise InvalidFormatError(f"Unknown WIF version byte: {version_byte}")
|
|
147
|
+
|
|
148
|
+
private_key = decoded[1:33]
|
|
149
|
+
|
|
150
|
+
if len(decoded) == 34:
|
|
151
|
+
if decoded[33] != 0x01:
|
|
152
|
+
raise InvalidFormatError(f"Invalid compression flag: {decoded[33]}")
|
|
153
|
+
is_compressed = True
|
|
154
|
+
else:
|
|
155
|
+
is_compressed = False
|
|
156
|
+
|
|
157
|
+
return private_key, is_compressed, network
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
__all__ = [
|
|
161
|
+
'base58_encode', 'base58_decode', 'base58_check_encode', 'base58_check_decode',
|
|
162
|
+
'private_key_to_wif', 'wif_to_private_key', 'bytes_to_hex', 'hex_to_bytes',
|
|
163
|
+
'int_to_bytes', 'bytes_to_int', 'InvalidFormatError'
|
|
164
|
+
]
|
libcrypto/hash.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Internal Cryptographic Hash and KDF Utilities.
|
|
3
|
+
This module provides wrappers around pycryptodome for hashing algorithms
|
|
4
|
+
and key derivation functions used within the library.
|
|
5
|
+
"""
|
|
6
|
+
from Crypto.Hash import SHA256, SHA512, RIPEMD160, keccak, HMAC
|
|
7
|
+
from Crypto.Protocol.KDF import PBKDF2
|
|
8
|
+
from Crypto.Random import get_random_bytes as secure_random_bytes
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def hmac_sha512(key: bytes, message: bytes) -> bytes:
|
|
12
|
+
"""
|
|
13
|
+
Compute HMAC-SHA512 using pycryptodome.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
key: Secret key bytes.
|
|
17
|
+
message: Message bytes to authenticate.
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
HMAC-SHA512 digest bytes (64 bytes).
|
|
21
|
+
"""
|
|
22
|
+
h = HMAC.new(key, digestmod=SHA512)
|
|
23
|
+
h.update(message)
|
|
24
|
+
return h.digest()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def pbkdf2_hmac_sha512(password: bytes, salt: bytes, iterations: int, dk_length: int) -> bytes:
|
|
28
|
+
"""
|
|
29
|
+
PBKDF2 key derivation using HMAC-SHA512 with pycryptodome.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
password: Password bytes.
|
|
33
|
+
salt: Salt bytes.
|
|
34
|
+
iterations: Number of iterations.
|
|
35
|
+
dk_length: Desired key length in bytes.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
Derived key bytes of specified length.
|
|
39
|
+
"""
|
|
40
|
+
return PBKDF2(password, salt, dk_length, count=iterations, hmac_hash_module=SHA512)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def sha256(data: bytes) -> bytes:
|
|
44
|
+
"""
|
|
45
|
+
Compute SHA256 hash using pycryptodome.
|
|
46
|
+
"""
|
|
47
|
+
h = SHA256.new(data)
|
|
48
|
+
return h.digest()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def ripemd160(data: bytes) -> bytes:
|
|
52
|
+
"""
|
|
53
|
+
Compute RIPEMD160 hash using pycryptodome.
|
|
54
|
+
"""
|
|
55
|
+
h = RIPEMD160.new(data)
|
|
56
|
+
return h.digest()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def hash160(data: bytes) -> bytes:
|
|
60
|
+
"""
|
|
61
|
+
Compute RIPEMD160(SHA256(data)) - common in Bitcoin.
|
|
62
|
+
"""
|
|
63
|
+
return ripemd160(sha256(data))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def double_sha256(data: bytes) -> bytes:
|
|
67
|
+
"""
|
|
68
|
+
Compute double SHA256 (SHA256(SHA256(data))) - common in Bitcoin.
|
|
69
|
+
"""
|
|
70
|
+
return sha256(sha256(data))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def keccak256(data: bytes) -> bytes:
|
|
74
|
+
"""
|
|
75
|
+
Compute Keccak-256 hash using pycryptodome.
|
|
76
|
+
"""
|
|
77
|
+
k = keccak.new(digest_bits=256)
|
|
78
|
+
k.update(data)
|
|
79
|
+
return k.digest()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def bip39_pbkdf2(mnemonic: str, passphrase: str = "") -> bytes:
|
|
83
|
+
"""
|
|
84
|
+
BIP39-specific PBKDF2 for converting mnemonic to seed.
|
|
85
|
+
"""
|
|
86
|
+
from .constants import PBKDF2_ITERATIONS, PBKDF2_HMAC_DKLEN
|
|
87
|
+
salt = ("mnemonic" + passphrase).encode('utf-8')
|
|
88
|
+
return pbkdf2_hmac_sha512(mnemonic.encode('utf-8'), salt, PBKDF2_ITERATIONS, PBKDF2_HMAC_DKLEN)
|