mmgen-pywallet 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C) 2013 by philemon <mmgen-py@yandex.com>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. mmgen-pywallet: Dump contents of a bitcoind wallet to file
  20. """
  21. # Changes by Philemon:
  22. # password entry at prompt
  23. # dump keys, addresses or keys for specified addresses (output in flat list)
  24. # PyWallet 1.2.1 (Public Domain)
  25. # http://github.com/joric/pywallet
  26. # Most of the actual PyWallet code placed in the public domain.
  27. # PyWallet includes portions of free software, listed below.
  28. # BitcoinTools (wallet.dat handling code, MIT License)
  29. # https://github.com/gavinandresen/bitcointools
  30. # Copyright (c) 2010 Gavin Andresen
  31. # python-ecdsa (EC_KEY implementation, MIT License)
  32. # http://github.com/warner/python-ecdsa
  33. # "python-ecdsa" Copyright (c) 2010 Brian Warner
  34. # Portions written in 2005 by Peter Pearson and placed in the public domain.
  35. # SlowAES (aes.py code, Apache 2 License)
  36. # http://code.google.com/p/slowaes/
  37. # Copyright (c) 2008, Josh Davis (http://www.josh-davis.org),
  38. # Alex Martelli (http://www.aleax.it)
  39. # Ported from C code written by Laurent Haan (http://www.progressive-coding.com)
  40. from bsddb.db import *
  41. import sys, time
  42. import json
  43. import logging
  44. import struct
  45. import StringIO
  46. import traceback
  47. import socket
  48. import types
  49. import string
  50. import exceptions
  51. import hashlib
  52. import random
  53. import math
  54. import mmgen.config as g
  55. from mmgen.Opts import *
  56. from mmgen.util import msg
  57. max_version = 60000
  58. addrtype = 0
  59. json_db = {}
  60. private_keys = []
  61. password = None
  62. help_data = {
  63. 'prog_name': g.prog_name,
  64. 'desc': "Dump contents of a bitcoind wallet to file",
  65. 'usage': "[opts] <bitcoind wallet file>",
  66. 'options': """
  67. -h, --help Print this help message
  68. -d, --outdir= d Specify an alternate directory 'd' for output
  69. -e, --echo-passphrase Display passphrase on screen upon entry
  70. -j, --json Dump wallet in json format
  71. -k, --keys Dump all private keys (flat list)
  72. -a, --addrs Dump all addresses (flat list)
  73. -K, --keysforaddrs= f Dump private keys for addresses listed in file 'f'
  74. -P, --passwd-file= f Get passphrase from file 'f'
  75. -S, --stdout Dump to stdout rather than file
  76. """
  77. }
  78. opts,cmd_args = parse_opts(sys.argv,help_data)
  79. if len(cmd_args) == 1:
  80. from mmgen.util import check_infile
  81. check_infile(cmd_args[0])
  82. else:
  83. usage(help_data)
  84. if ('json' not in opts and 'keys' not in opts
  85. and 'addrs' not in opts and 'keysforaddrs' not in opts):
  86. usage(help_data)
  87. # from the SlowAES project, http://code.google.com/p/slowaes (aes.py)
  88. def append_PKCS7_padding(s):
  89. """return s padded to a multiple of 16-bytes by PKCS7 padding"""
  90. numpads = 16 - (len(s)%16)
  91. return s + numpads*chr(numpads)
  92. def strip_PKCS7_padding(s):
  93. """return s stripped of PKCS7 padding"""
  94. if len(s)%16 or not s:
  95. raise ValueError("String of len %d can't be PCKS7-padded" % len(s))
  96. numpads = ord(s[-1])
  97. if numpads > 16:
  98. raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1])
  99. return s[:-numpads]
  100. class AES(object):
  101. # valid key sizes
  102. keySize = dict(SIZE_128=16, SIZE_192=24, SIZE_256=32)
  103. # Rijndael S-box
  104. sbox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
  105. 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
  106. 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
  107. 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
  108. 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
  109. 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
  110. 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,
  111. 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
  112. 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
  113. 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
  114. 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
  115. 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  116. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
  117. 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
  118. 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
  119. 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
  120. 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
  121. 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
  122. 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
  123. 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
  124. 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
  125. 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
  126. 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
  127. 0x54, 0xbb, 0x16]
  128. # Rijndael Inverted S-box
  129. rsbox = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
  130. 0x9e, 0x81, 0xf3, 0xd7, 0xfb , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
  131. 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb , 0x54,
  132. 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
  133. 0x42, 0xfa, 0xc3, 0x4e , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
  134. 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 , 0x72, 0xf8,
  135. 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
  136. 0x65, 0xb6, 0x92 , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
  137. 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 , 0x90, 0xd8, 0xab,
  138. 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
  139. 0x45, 0x06 , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
  140. 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b , 0x3a, 0x91, 0x11, 0x41,
  141. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
  142. 0x73 , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
  143. 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e , 0x47, 0xf1, 0x1a, 0x71, 0x1d,
  144. 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b ,
  145. 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
  146. 0xfe, 0x78, 0xcd, 0x5a, 0xf4 , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
  147. 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f , 0x60,
  148. 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
  149. 0x93, 0xc9, 0x9c, 0xef , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
  150. 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 , 0x17, 0x2b,
  151. 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
  152. 0x21, 0x0c, 0x7d]
  153. def getSBoxValue(self,num):
  154. """Retrieves a given S-Box Value"""
  155. return self.sbox[num]
  156. def getSBoxInvert(self,num):
  157. """Retrieves a given Inverted S-Box Value"""
  158. return self.rsbox[num]
  159. def rotate(self, word):
  160. """ Rijndael's key schedule rotate operation.
  161. Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
  162. Word is an char list of size 4 (32 bits overall).
  163. """
  164. return word[1:] + word[:1]
  165. # Rijndael Rcon
  166. Rcon = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
  167. 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97,
  168. 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  169. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66,
  170. 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
  171. 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  172. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
  173. 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61,
  174. 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  175. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
  176. 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc,
  177. 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  178. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
  179. 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
  180. 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  181. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
  182. 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4,
  183. 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  184. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08,
  185. 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
  186. 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  187. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2,
  188. 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74,
  189. 0xe8, 0xcb ]
  190. def getRconValue(self, num):
  191. """Retrieves a given Rcon Value"""
  192. return self.Rcon[num]
  193. def core(self, word, iteration):
  194. """Key schedule core."""
  195. # rotate the 32-bit word 8 bits to the left
  196. word = self.rotate(word)
  197. # apply S-Box substitution on all 4 parts of the 32-bit word
  198. for i in range(4):
  199. word[i] = self.getSBoxValue(word[i])
  200. # XOR the output of the rcon operation with i to the first part
  201. # (leftmost) only
  202. word[0] = word[0] ^ self.getRconValue(iteration)
  203. return word
  204. def expandKey(self, key, size, expandedKeySize):
  205. """Rijndael's key expansion.
  206. Expands an 128,192,256 key into an 176,208,240 bytes key
  207. expandedKey is a char list of large enough size,
  208. key is the non-expanded key.
  209. """
  210. # current expanded keySize, in bytes
  211. currentSize = 0
  212. rconIteration = 1
  213. expandedKey = [0] * expandedKeySize
  214. # set the 16, 24, 32 bytes of the expanded key to the input key
  215. for j in range(size):
  216. expandedKey[j] = key[j]
  217. currentSize += size
  218. while currentSize < expandedKeySize:
  219. # assign the previous 4 bytes to the temporary value t
  220. t = expandedKey[currentSize-4:currentSize]
  221. # every 16,24,32 bytes we apply the core schedule to t
  222. # and increment rconIteration afterwards
  223. if currentSize % size == 0:
  224. t = self.core(t, rconIteration)
  225. rconIteration += 1
  226. # For 256-bit keys, we add an extra sbox to the calculation
  227. if size == self.keySize["SIZE_256"] and ((currentSize % size) == 16):
  228. for l in range(4): t[l] = self.getSBoxValue(t[l])
  229. # We XOR t with the four-byte block 16,24,32 bytes before the new
  230. # expanded key. This becomes the next four bytes in the expanded
  231. # key.
  232. for m in range(4):
  233. expandedKey[currentSize] = expandedKey[currentSize - size] ^ \
  234. t[m]
  235. currentSize += 1
  236. return expandedKey
  237. def addRoundKey(self, state, roundKey):
  238. """Adds (XORs) the round key to the state."""
  239. for i in range(16):
  240. state[i] ^= roundKey[i]
  241. return state
  242. def createRoundKey(self, expandedKey, roundKeyPointer):
  243. """Create a round key.
  244. Creates a round key from the given expanded key and the
  245. position within the expanded key.
  246. """
  247. roundKey = [0] * 16
  248. for i in range(4):
  249. for j in range(4):
  250. roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]
  251. return roundKey
  252. def galois_multiplication(self, a, b):
  253. """Galois multiplication of 8 bit characters a and b."""
  254. p = 0
  255. for counter in range(8):
  256. if b & 1: p ^= a
  257. hi_bit_set = a & 0x80
  258. a <<= 1
  259. # keep a 8 bit
  260. a &= 0xFF
  261. if hi_bit_set:
  262. a ^= 0x1b
  263. b >>= 1
  264. return p
  265. #
  266. # substitute all the values from the state with the value in the SBox
  267. # using the state value as index for the SBox
  268. #
  269. def subBytes(self, state, isInv):
  270. if isInv: getter = self.getSBoxInvert
  271. else: getter = self.getSBoxValue
  272. for i in range(16): state[i] = getter(state[i])
  273. return state
  274. # iterate over the 4 rows and call shiftRow() with that row
  275. def shiftRows(self, state, isInv):
  276. for i in range(4):
  277. state = self.shiftRow(state, i*4, i, isInv)
  278. return state
  279. # each iteration shifts the row to the left by 1
  280. def shiftRow(self, state, statePointer, nbr, isInv):
  281. for i in range(nbr):
  282. if isInv:
  283. state[statePointer:statePointer+4] = \
  284. state[statePointer+3:statePointer+4] + \
  285. state[statePointer:statePointer+3]
  286. else:
  287. state[statePointer:statePointer+4] = \
  288. state[statePointer+1:statePointer+4] + \
  289. state[statePointer:statePointer+1]
  290. return state
  291. # galois multiplication of the 4x4 matrix
  292. def mixColumns(self, state, isInv):
  293. # iterate over the 4 columns
  294. for i in range(4):
  295. # construct one column by slicing over the 4 rows
  296. column = state[i:i+16:4]
  297. # apply the mixColumn on one column
  298. column = self.mixColumn(column, isInv)
  299. # put the values back into the state
  300. state[i:i+16:4] = column
  301. return state
  302. # galois multiplication of 1 column of the 4x4 matrix
  303. def mixColumn(self, column, isInv):
  304. if isInv: mult = [14, 9, 13, 11]
  305. else: mult = [2, 1, 1, 3]
  306. cpy = list(column)
  307. g = self.galois_multiplication
  308. column[0] = g(cpy[0], mult[0]) ^ g(cpy[3], mult[1]) ^ \
  309. g(cpy[2], mult[2]) ^ g(cpy[1], mult[3])
  310. column[1] = g(cpy[1], mult[0]) ^ g(cpy[0], mult[1]) ^ \
  311. g(cpy[3], mult[2]) ^ g(cpy[2], mult[3])
  312. column[2] = g(cpy[2], mult[0]) ^ g(cpy[1], mult[1]) ^ \
  313. g(cpy[0], mult[2]) ^ g(cpy[3], mult[3])
  314. column[3] = g(cpy[3], mult[0]) ^ g(cpy[2], mult[1]) ^ \
  315. g(cpy[1], mult[2]) ^ g(cpy[0], mult[3])
  316. return column
  317. # applies the 4 operations of the forward round in sequence
  318. def aes_round(self, state, roundKey):
  319. state = self.subBytes(state, False)
  320. state = self.shiftRows(state, False)
  321. state = self.mixColumns(state, False)
  322. state = self.addRoundKey(state, roundKey)
  323. return state
  324. # applies the 4 operations of the inverse round in sequence
  325. def aes_invRound(self, state, roundKey):
  326. state = self.shiftRows(state, True)
  327. state = self.subBytes(state, True)
  328. state = self.addRoundKey(state, roundKey)
  329. state = self.mixColumns(state, True)
  330. return state
  331. # Perform the initial operations, the standard round, and the final
  332. # operations of the forward aes, creating a round key for each round
  333. def aes_main(self, state, expandedKey, nbrRounds):
  334. state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
  335. i = 1
  336. while i < nbrRounds:
  337. state = self.aes_round(state, self.createRoundKey(expandedKey, 16*i))
  338. i += 1
  339. state = self.subBytes(state, False)
  340. state = self.shiftRows(state, False)
  341. state = self.addRoundKey(state, self.createRoundKey(expandedKey, 16*nbrRounds))
  342. return state
  343. # Perform the initial operations, the standard round, and the final
  344. # operations of the inverse aes, creating a round key for each round
  345. def aes_invMain(self, state, expandedKey, nbrRounds):
  346. state = self.addRoundKey(state, self.createRoundKey(expandedKey, 16*nbrRounds))
  347. i = nbrRounds - 1
  348. while i > 0:
  349. state = self.aes_invRound(state, self.createRoundKey(expandedKey, 16*i))
  350. i -= 1
  351. state = self.shiftRows(state, True)
  352. state = self.subBytes(state, True)
  353. state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
  354. return state
  355. # encrypts a 128 bit input block against the given key of size specified
  356. def encrypt(self, iput, key, size):
  357. output = [0] * 16
  358. # the number of rounds
  359. nbrRounds = 0
  360. # the 128 bit block to encode
  361. block = [0] * 16
  362. # set the number of rounds
  363. if size == self.keySize["SIZE_128"]: nbrRounds = 10
  364. elif size == self.keySize["SIZE_192"]: nbrRounds = 12
  365. elif size == self.keySize["SIZE_256"]: nbrRounds = 14
  366. else: return None
  367. # the expanded keySize
  368. expandedKeySize = 16*(nbrRounds+1)
  369. # Set the block values, for the block:
  370. # a0,0 a0,1 a0,2 a0,3
  371. # a1,0 a1,1 a1,2 a1,3
  372. # a2,0 a2,1 a2,2 a2,3
  373. # a3,0 a3,1 a3,2 a3,3
  374. # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
  375. #
  376. # iterate over the columns
  377. for i in range(4):
  378. # iterate over the rows
  379. for j in range(4):
  380. block[(i+(j*4))] = iput[(i*4)+j]
  381. # expand the key into an 176, 208, 240 bytes key
  382. # the expanded key
  383. expandedKey = self.expandKey(key, size, expandedKeySize)
  384. # encrypt the block using the expandedKey
  385. block = self.aes_main(block, expandedKey, nbrRounds)
  386. # unmap the block again into the output
  387. for k in range(4):
  388. # iterate over the rows
  389. for l in range(4):
  390. output[(k*4)+l] = block[(k+(l*4))]
  391. return output
  392. # decrypts a 128 bit input block against the given key of size specified
  393. def decrypt(self, iput, key, size):
  394. output = [0] * 16
  395. # the number of rounds
  396. nbrRounds = 0
  397. # the 128 bit block to decode
  398. block = [0] * 16
  399. # set the number of rounds
  400. if size == self.keySize["SIZE_128"]: nbrRounds = 10
  401. elif size == self.keySize["SIZE_192"]: nbrRounds = 12
  402. elif size == self.keySize["SIZE_256"]: nbrRounds = 14
  403. else: return None
  404. # the expanded keySize
  405. expandedKeySize = 16*(nbrRounds+1)
  406. # Set the block values, for the block:
  407. # a0,0 a0,1 a0,2 a0,3
  408. # a1,0 a1,1 a1,2 a1,3
  409. # a2,0 a2,1 a2,2 a2,3
  410. # a3,0 a3,1 a3,2 a3,3
  411. # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
  412. # iterate over the columns
  413. for i in range(4):
  414. # iterate over the rows
  415. for j in range(4):
  416. block[(i+(j*4))] = iput[(i*4)+j]
  417. # expand the key into an 176, 208, 240 bytes key
  418. expandedKey = self.expandKey(key, size, expandedKeySize)
  419. # decrypt the block using the expandedKey
  420. block = self.aes_invMain(block, expandedKey, nbrRounds)
  421. # unmap the block again into the output
  422. for k in range(4):
  423. # iterate over the rows
  424. for l in range(4):
  425. output[(k*4)+l] = block[(k+(l*4))]
  426. return output
  427. class AESModeOfOperation(object):
  428. aes = AES()
  429. # structure of supported modes of operation
  430. modeOfOperation = dict(OFB=0, CFB=1, CBC=2)
  431. # converts a 16 character string into a number array
  432. def convertString(self, string, start, end, mode):
  433. if end - start > 16: end = start + 16
  434. if mode == self.modeOfOperation["CBC"]: ar = [0] * 16
  435. else: ar = []
  436. i = start
  437. j = 0
  438. while len(ar) < end - start:
  439. ar.append(0)
  440. while i < end:
  441. ar[j] = ord(string[i])
  442. j += 1
  443. i += 1
  444. return ar
  445. # Mode of Operation Encryption
  446. # stringIn - Input String
  447. # mode - mode of type modeOfOperation
  448. # hexKey - a hex key of the bit length size
  449. # size - the bit length of the key
  450. # hexIV - the 128 bit hex Initilization Vector
  451. def encrypt(self, stringIn, mode, key, size, IV):
  452. if len(key) % size:
  453. return None
  454. if len(IV) % 16:
  455. return None
  456. # the AES input/output
  457. plaintext = []
  458. iput = [0] * 16
  459. output = []
  460. ciphertext = [0] * 16
  461. # the output cipher string
  462. cipherOut = []
  463. # char firstRound
  464. firstRound = True
  465. if stringIn != None:
  466. for j in range(int(math.ceil(float(len(stringIn))/16))):
  467. start = j*16
  468. end = j*16+16
  469. if end > len(stringIn):
  470. end = len(stringIn)
  471. plaintext = self.convertString(stringIn, start, end, mode)
  472. # print 'PT@%s:%s' % (j, plaintext)
  473. if mode == self.modeOfOperation["CFB"]:
  474. if firstRound:
  475. output = self.aes.encrypt(IV, key, size)
  476. firstRound = False
  477. else:
  478. output = self.aes.encrypt(iput, key, size)
  479. for i in range(16):
  480. if len(plaintext)-1 < i:
  481. ciphertext[i] = 0 ^ output[i]
  482. elif len(output)-1 < i:
  483. ciphertext[i] = plaintext[i] ^ 0
  484. elif len(plaintext)-1 < i and len(output) < i:
  485. ciphertext[i] = 0 ^ 0
  486. else:
  487. ciphertext[i] = plaintext[i] ^ output[i]
  488. for k in range(end-start):
  489. cipherOut.append(ciphertext[k])
  490. iput = ciphertext
  491. elif mode == self.modeOfOperation["OFB"]:
  492. if firstRound:
  493. output = self.aes.encrypt(IV, key, size)
  494. firstRound = False
  495. else:
  496. output = self.aes.encrypt(iput, key, size)
  497. for i in range(16):
  498. if len(plaintext)-1 < i:
  499. ciphertext[i] = 0 ^ output[i]
  500. elif len(output)-1 < i:
  501. ciphertext[i] = plaintext[i] ^ 0
  502. elif len(plaintext)-1 < i and len(output) < i:
  503. ciphertext[i] = 0 ^ 0
  504. else:
  505. ciphertext[i] = plaintext[i] ^ output[i]
  506. for k in range(end-start):
  507. cipherOut.append(ciphertext[k])
  508. iput = output
  509. elif mode == self.modeOfOperation["CBC"]:
  510. for i in range(16):
  511. if firstRound:
  512. iput[i] = plaintext[i] ^ IV[i]
  513. else:
  514. iput[i] = plaintext[i] ^ ciphertext[i]
  515. # print 'IP@%s:%s' % (j, iput)
  516. firstRound = False
  517. ciphertext = self.aes.encrypt(iput, key, size)
  518. # always 16 bytes because of the padding for CBC
  519. for k in range(16):
  520. cipherOut.append(ciphertext[k])
  521. return mode, len(stringIn), cipherOut
  522. # Mode of Operation Decryption
  523. # cipherIn - Encrypted String
  524. # originalsize - The unencrypted string length - required for CBC
  525. # mode - mode of type modeOfOperation
  526. # key - a number array of the bit length size
  527. # size - the bit length of the key
  528. # IV - the 128 bit number array Initilization Vector
  529. def decrypt(self, cipherIn, originalsize, mode, key, size, IV):
  530. # cipherIn = unescCtrlChars(cipherIn)
  531. if len(key) % size:
  532. return None
  533. if len(IV) % 16:
  534. return None
  535. # the AES input/output
  536. ciphertext = []
  537. iput = []
  538. output = []
  539. plaintext = [0] * 16
  540. # the output plain text string
  541. stringOut = ''
  542. # char firstRound
  543. firstRound = True
  544. if cipherIn != None:
  545. for j in range(int(math.ceil(float(len(cipherIn))/16))):
  546. start = j*16
  547. end = j*16+16
  548. if j*16+16 > len(cipherIn):
  549. end = len(cipherIn)
  550. ciphertext = cipherIn[start:end]
  551. if mode == self.modeOfOperation["CFB"]:
  552. if firstRound:
  553. output = self.aes.encrypt(IV, key, size)
  554. firstRound = False
  555. else:
  556. output = self.aes.encrypt(iput, key, size)
  557. for i in range(16):
  558. if len(output)-1 < i:
  559. plaintext[i] = 0 ^ ciphertext[i]
  560. elif len(ciphertext)-1 < i:
  561. plaintext[i] = output[i] ^ 0
  562. elif len(output)-1 < i and len(ciphertext) < i:
  563. plaintext[i] = 0 ^ 0
  564. else:
  565. plaintext[i] = output[i] ^ ciphertext[i]
  566. for k in range(end-start):
  567. stringOut += chr(plaintext[k])
  568. iput = ciphertext
  569. elif mode == self.modeOfOperation["OFB"]:
  570. if firstRound:
  571. output = self.aes.encrypt(IV, key, size)
  572. firstRound = False
  573. else:
  574. output = self.aes.encrypt(iput, key, size)
  575. for i in range(16):
  576. if len(output)-1 < i:
  577. plaintext[i] = 0 ^ ciphertext[i]
  578. elif len(ciphertext)-1 < i:
  579. plaintext[i] = output[i] ^ 0
  580. elif len(output)-1 < i and len(ciphertext) < i:
  581. plaintext[i] = 0 ^ 0
  582. else:
  583. plaintext[i] = output[i] ^ ciphertext[i]
  584. for k in range(end-start):
  585. stringOut += chr(plaintext[k])
  586. iput = output
  587. elif mode == self.modeOfOperation["CBC"]:
  588. output = self.aes.decrypt(ciphertext, key, size)
  589. for i in range(16):
  590. if firstRound:
  591. plaintext[i] = IV[i] ^ output[i]
  592. else:
  593. plaintext[i] = iput[i] ^ output[i]
  594. firstRound = False
  595. if originalsize is not None and originalsize < end:
  596. for k in range(originalsize-start):
  597. stringOut += chr(plaintext[k])
  598. else:
  599. for k in range(end-start):
  600. stringOut += chr(plaintext[k])
  601. iput = ciphertext
  602. return stringOut
  603. # end of aes.py code
  604. # pywallet crypter implementation
  605. crypter = None
  606. try:
  607. from Crypto.Cipher import AES
  608. crypter = 'pycrypto'
  609. except:
  610. pass
  611. class Crypter_pycrypto( object ):
  612. def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
  613. if nDerivationMethod != 0:
  614. return 0
  615. data = vKeyData + vSalt
  616. for i in xrange(nDerivIterations):
  617. data = hashlib.sha512(data).digest()
  618. self.SetKey(data[0:32])
  619. self.SetIV(data[32:32+16])
  620. return len(data)
  621. def SetKey(self, key):
  622. self.chKey = key
  623. def SetIV(self, iv):
  624. self.chIV = iv[0:16]
  625. def Encrypt(self, data):
  626. return AES.new(self.chKey,AES.MODE_CBC,self.chIV).encrypt(data)[0:32]
  627. def Decrypt(self, data):
  628. return AES.new(self.chKey,AES.MODE_CBC,self.chIV).decrypt(data)[0:32]
  629. try:
  630. if not crypter:
  631. import ctypes
  632. import ctypes.util
  633. ssl = ctypes.cdll.LoadLibrary (ctypes.util.find_library ('ssl') or 'libeay32')
  634. crypter = 'ssl'
  635. except:
  636. pass
  637. class Crypter_ssl(object):
  638. def __init__(self):
  639. self.chKey = ctypes.create_string_buffer (32)
  640. self.chIV = ctypes.create_string_buffer (16)
  641. def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
  642. if nDerivationMethod != 0:
  643. return 0
  644. strKeyData = ctypes.create_string_buffer (vKeyData)
  645. chSalt = ctypes.create_string_buffer (vSalt)
  646. return ssl.EVP_BytesToKey(ssl.EVP_aes_256_cbc(), ssl.EVP_sha512(), chSalt, strKeyData,
  647. len(vKeyData), nDerivIterations, ctypes.byref(self.chKey), ctypes.byref(self.chIV))
  648. def SetKey(self, key):
  649. self.chKey = ctypes.create_string_buffer(key)
  650. def SetIV(self, iv):
  651. self.chIV = ctypes.create_string_buffer(iv)
  652. def Encrypt(self, data):
  653. buf = ctypes.create_string_buffer(len(data) + 16)
  654. written = ctypes.c_int(0)
  655. final = ctypes.c_int(0)
  656. ctx = ssl.EVP_CIPHER_CTX_new()
  657. ssl.EVP_CIPHER_CTX_init(ctx)
  658. ssl.EVP_EncryptInit_ex(ctx, ssl.EVP_aes_256_cbc(), None, self.chKey, self.chIV)
  659. ssl.EVP_EncryptUpdate(ctx, buf, ctypes.byref(written), data, len(data))
  660. output = buf.raw[:written.value]
  661. ssl.EVP_EncryptFinal_ex(ctx, buf, ctypes.byref(final))
  662. output += buf.raw[:final.value]
  663. return output
  664. def Decrypt(self, data):
  665. buf = ctypes.create_string_buffer(len(data) + 16)
  666. written = ctypes.c_int(0)
  667. final = ctypes.c_int(0)
  668. ctx = ssl.EVP_CIPHER_CTX_new()
  669. ssl.EVP_CIPHER_CTX_init(ctx)
  670. ssl.EVP_DecryptInit_ex(ctx, ssl.EVP_aes_256_cbc(), None, self.chKey, self.chIV)
  671. ssl.EVP_DecryptUpdate(ctx, buf, ctypes.byref(written), data, len(data))
  672. output = buf.raw[:written.value]
  673. ssl.EVP_DecryptFinal_ex(ctx, buf, ctypes.byref(final))
  674. output += buf.raw[:final.value]
  675. return output
  676. class Crypter_pure(object):
  677. def __init__(self):
  678. self.m = AESModeOfOperation()
  679. self.cbc = self.m.modeOfOperation["CBC"]
  680. self.sz = self.m.aes.keySize["SIZE_256"]
  681. def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
  682. if nDerivationMethod != 0:
  683. return 0
  684. data = vKeyData + vSalt
  685. for i in xrange(nDerivIterations):
  686. data = hashlib.sha512(data).digest()
  687. self.SetKey(data[0:32])
  688. self.SetIV(data[32:32+16])
  689. return len(data)
  690. def SetKey(self, key):
  691. self.chKey = [ord(i) for i in key]
  692. def SetIV(self, iv):
  693. self.chIV = [ord(i) for i in iv]
  694. def Encrypt(self, data):
  695. mode, size, cypher = self.m.encrypt(data, self.cbc, self.chKey, self.sz, self.chIV)
  696. return ''.join(map(chr, cypher))
  697. def Decrypt(self, data):
  698. chData = [ord(i) for i in data]
  699. return self.m.decrypt(chData, self.sz, self.cbc, self.chKey, self.sz, self.chIV)
  700. # secp256k1
  701. _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
  702. _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
  703. _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
  704. _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
  705. _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
  706. _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
  707. # python-ecdsa code (EC_KEY implementation)
  708. class CurveFp( object ):
  709. def __init__( self, p, a, b ):
  710. self.__p = p
  711. self.__a = a
  712. self.__b = b
  713. def p( self ):
  714. return self.__p
  715. def a( self ):
  716. return self.__a
  717. def b( self ):
  718. return self.__b
  719. def contains_point( self, x, y ):
  720. return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0
  721. class Point( object ):
  722. def __init__( self, curve, x, y, order = None ):
  723. self.__curve = curve
  724. self.__x = x
  725. self.__y = y
  726. self.__order = order
  727. if self.__curve: assert self.__curve.contains_point( x, y )
  728. if order: assert self * order == INFINITY
  729. def __add__( self, other ):
  730. if other == INFINITY: return self
  731. if self == INFINITY: return other
  732. assert self.__curve == other.__curve
  733. if self.__x == other.__x:
  734. if ( self.__y + other.__y ) % self.__curve.p() == 0:
  735. return INFINITY
  736. else:
  737. return self.double()
  738. p = self.__curve.p()
  739. l = ( ( other.__y - self.__y ) * \
  740. inverse_mod( other.__x - self.__x, p ) ) % p
  741. x3 = ( l * l - self.__x - other.__x ) % p
  742. y3 = ( l * ( self.__x - x3 ) - self.__y ) % p
  743. return Point( self.__curve, x3, y3 )
  744. def __mul__( self, other ):
  745. def leftmost_bit( x ):
  746. assert x > 0
  747. result = 1L
  748. while result <= x: result = 2 * result
  749. return result / 2
  750. e = other
  751. if self.__order: e = e % self.__order
  752. if e == 0: return INFINITY
  753. if self == INFINITY: return INFINITY
  754. assert e > 0
  755. e3 = 3 * e
  756. negative_self = Point( self.__curve, self.__x, -self.__y, self.__order )
  757. i = leftmost_bit( e3 ) / 2
  758. result = self
  759. while i > 1:
  760. result = result.double()
  761. if ( e3 & i ) != 0 and ( e & i ) == 0: result = result + self
  762. if ( e3 & i ) == 0 and ( e & i ) != 0: result = result + negative_self
  763. i = i / 2
  764. return result
  765. def __rmul__( self, other ):
  766. return self * other
  767. def __str__( self ):
  768. if self == INFINITY: return "infinity"
  769. return "(%d,%d)" % ( self.__x, self.__y )
  770. def double( self ):
  771. if self == INFINITY:
  772. return INFINITY
  773. p = self.__curve.p()
  774. a = self.__curve.a()
  775. l = ( ( 3 * self.__x * self.__x + a ) * \
  776. inverse_mod( 2 * self.__y, p ) ) % p
  777. x3 = ( l * l - 2 * self.__x ) % p
  778. y3 = ( l * ( self.__x - x3 ) - self.__y ) % p
  779. return Point( self.__curve, x3, y3 )
  780. def x( self ):
  781. return self.__x
  782. def y( self ):
  783. return self.__y
  784. def curve( self ):
  785. return self.__curve
  786. def order( self ):
  787. return self.__order
  788. INFINITY = Point( None, None, None )
  789. def inverse_mod( a, m ):
  790. if a < 0 or m <= a: a = a % m
  791. c, d = a, m
  792. uc, vc, ud, vd = 1, 0, 0, 1
  793. while c != 0:
  794. q, c, d = divmod( d, c ) + ( c, )
  795. uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
  796. assert d == 1
  797. if ud > 0: return ud
  798. else: return ud + m
  799. class Signature( object ):
  800. def __init__( self, r, s ):
  801. self.r = r
  802. self.s = s
  803. class Public_key( object ):
  804. def __init__( self, generator, point ):
  805. self.curve = generator.curve()
  806. self.generator = generator
  807. self.point = point
  808. n = generator.order()
  809. if not n:
  810. raise RuntimeError, "Generator point must have order."
  811. if not n * point == INFINITY:
  812. raise RuntimeError, "Generator point order is bad."
  813. if point.x() < 0 or n <= point.x() or point.y() < 0 or n <= point.y():
  814. raise RuntimeError, "Generator point has x or y out of range."
  815. def verifies( self, hash, signature ):
  816. G = self.generator
  817. n = G.order()
  818. r = signature.r
  819. s = signature.s
  820. if r < 1 or r > n-1: return False
  821. if s < 1 or s > n-1: return False
  822. c = inverse_mod( s, n )
  823. u1 = ( hash * c ) % n
  824. u2 = ( r * c ) % n
  825. xy = u1 * G + u2 * self.point
  826. v = xy.x() % n
  827. return v == r
  828. class Private_key( object ):
  829. def __init__( self, public_key, secret_multiplier ):
  830. self.public_key = public_key
  831. self.secret_multiplier = secret_multiplier
  832. def der( self ):
  833. hex_der_key = '06052b8104000a30740201010420' + \
  834. '%064x' % self.secret_multiplier + \
  835. 'a00706052b8104000aa14403420004' + \
  836. '%064x' % self.public_key.point.x() + \
  837. '%064x' % self.public_key.point.y()
  838. return hex_der_key.decode('hex')
  839. def sign( self, hash, random_k ):
  840. G = self.public_key.generator
  841. n = G.order()
  842. k = random_k % n
  843. p1 = k * G
  844. r = p1.x()
  845. if r == 0: raise RuntimeError, "amazingly unlucky random number r"
  846. s = ( inverse_mod( k, n ) * \
  847. ( hash + ( self.secret_multiplier * r ) % n ) ) % n
  848. if s == 0: raise RuntimeError, "amazingly unlucky random number s"
  849. return Signature( r, s )
  850. class EC_KEY(object):
  851. def __init__( self, secret ):
  852. curve = CurveFp( _p, _a, _b )
  853. generator = Point( curve, _Gx, _Gy, _r )
  854. self.pubkey = Public_key( generator, generator * secret )
  855. self.privkey = Private_key( self.pubkey, secret )
  856. self.secret = secret
  857. # end of python-ecdsa code
  858. # pywallet openssl private key implementation
  859. def i2d_ECPrivateKey(pkey, compressed=False):
  860. if compressed:
  861. key = '3081d30201010420' + \
  862. '%064x' % pkey.secret + \
  863. 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
  864. '%064x' % _p + \
  865. '3006040100040107042102' + \
  866. '%064x' % _Gx + \
  867. '022100' + \
  868. '%064x' % _r + \
  869. '020101a124032200'
  870. else:
  871. key = '308201130201010420' + \
  872. '%064x' % pkey.secret + \
  873. 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
  874. '%064x' % _p + \
  875. '3006040100040107044104' + \
  876. '%064x' % _Gx + \
  877. '%064x' % _Gy + \
  878. '022100' + \
  879. '%064x' % _r + \
  880. '020101a144034200'
  881. return key.decode('hex') + i2o_ECPublicKey(pkey, compressed)
  882. def i2o_ECPublicKey(pkey, compressed=False):
  883. # public keys are 65 bytes long (520 bits)
  884. # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
  885. # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
  886. # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
  887. if compressed:
  888. if pkey.pubkey.point.y() & 1:
  889. key = '03' + '%064x' % pkey.pubkey.point.x()
  890. else:
  891. key = '02' + '%064x' % pkey.pubkey.point.x()
  892. else:
  893. key = '04' + \
  894. '%064x' % pkey.pubkey.point.x() + \
  895. '%064x' % pkey.pubkey.point.y()
  896. return key.decode('hex')
  897. # bitcointools hashes and base58 implementation
  898. def hash_160(public_key):
  899. md = hashlib.new('ripemd160')
  900. md.update(hashlib.sha256(public_key).digest())
  901. return md.digest()
  902. def public_key_to_bc_address(public_key):
  903. h160 = hash_160(public_key)
  904. return hash_160_to_bc_address(h160)
  905. def hash_160_to_bc_address(h160):
  906. vh160 = chr(addrtype) + h160
  907. h = Hash(vh160)
  908. addr = vh160 + h[0:4]
  909. return b58encode(addr)
  910. def bc_address_to_hash_160(addr):
  911. bytes = b58decode(addr, 25)
  912. return bytes[1:21]
  913. __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  914. __b58base = len(__b58chars)
  915. def b58encode(v):
  916. """ encode v, which is a string of bytes, to base58.
  917. """
  918. long_value = 0L
  919. for (i, c) in enumerate(v[::-1]):
  920. long_value += (256**i) * ord(c)
  921. result = ''
  922. while long_value >= __b58base:
  923. div, mod = divmod(long_value, __b58base)
  924. result = __b58chars[mod] + result
  925. long_value = div
  926. result = __b58chars[long_value] + result
  927. # Bitcoin does a little leading-zero-compression:
  928. # leading 0-bytes in the input become leading-1s
  929. nPad = 0
  930. for c in v:
  931. if c == '\0': nPad += 1
  932. else: break
  933. return (__b58chars[0]*nPad) + result
  934. def b58decode(v, length):
  935. """ decode v into a string of len bytes
  936. """
  937. long_value = 0L
  938. for (i, c) in enumerate(v[::-1]):
  939. long_value += __b58chars.find(c) * (__b58base**i)
  940. result = ''
  941. while long_value >= 256:
  942. div, mod = divmod(long_value, 256)
  943. result = chr(mod) + result
  944. long_value = div
  945. result = chr(long_value) + result
  946. nPad = 0
  947. for c in v:
  948. if c == __b58chars[0]: nPad += 1
  949. else: break
  950. result = chr(0)*nPad + result
  951. if length is not None and len(result) != length:
  952. return None
  953. return result
  954. # end of bitcointools base58 implementation
  955. # address handling code
  956. def Hash(data):
  957. return hashlib.sha256(hashlib.sha256(data).digest()).digest()
  958. def EncodeBase58Check(secret):
  959. hash = Hash(secret)
  960. return b58encode(secret + hash[0:4])
  961. def DecodeBase58Check(sec):
  962. vchRet = b58decode(sec, None)
  963. secret = vchRet[0:-4]
  964. csum = vchRet[-4:]
  965. hash = Hash(secret)
  966. cs32 = hash[0:4]
  967. if cs32 != csum:
  968. return None
  969. else:
  970. return secret
  971. def PrivKeyToSecret(privkey):
  972. if len(privkey) == 279:
  973. return privkey[9:9+32]
  974. else:
  975. return privkey[8:8+32]
  976. def SecretToASecret(secret, compressed=False):
  977. vchIn = chr((addrtype+128)&255) + secret
  978. if compressed: vchIn += '\01'
  979. return EncodeBase58Check(vchIn)
  980. def ASecretToSecret(sec):
  981. vch = DecodeBase58Check(sec)
  982. if vch and vch[0] == chr((addrtype+128)&255):
  983. return vch[1:]
  984. else:
  985. return False
  986. def regenerate_key(sec):
  987. b = ASecretToSecret(sec)
  988. if not b:
  989. return False
  990. b = b[0:32]
  991. secret = int('0x' + b.encode('hex'), 16)
  992. return EC_KEY(secret)
  993. def GetPubKey(pkey, compressed=False):
  994. return i2o_ECPublicKey(pkey, compressed)
  995. def GetPrivKey(pkey, compressed=False):
  996. return i2d_ECPrivateKey(pkey, compressed)
  997. def GetSecret(pkey):
  998. return ('%064x' % pkey.secret).decode('hex')
  999. def is_compressed(sec):
  1000. b = ASecretToSecret(sec)
  1001. return len(b) == 33
  1002. # bitcointools wallet.dat handling code
  1003. def create_env(db_dir):
  1004. db_env = DBEnv(0)
  1005. r = db_env.open(db_dir, (DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN|DB_THREAD|DB_RECOVER))
  1006. return db_env
  1007. def parse_CAddress(vds):
  1008. d = {'ip':'0.0.0.0','port':0,'nTime': 0}
  1009. try:
  1010. d['nVersion'] = vds.read_int32()
  1011. d['nTime'] = vds.read_uint32()
  1012. d['nServices'] = vds.read_uint64()
  1013. d['pchReserved'] = vds.read_bytes(12)
  1014. d['ip'] = socket.inet_ntoa(vds.read_bytes(4))
  1015. d['port'] = vds.read_uint16()
  1016. except:
  1017. pass
  1018. return d
  1019. def deserialize_CAddress(d):
  1020. return d['ip']+":"+str(d['port'])
  1021. def parse_BlockLocator(vds):
  1022. d = { 'hashes' : [] }
  1023. nHashes = vds.read_compact_size()
  1024. for i in xrange(nHashes):
  1025. d['hashes'].append(vds.read_bytes(32))
  1026. return d
  1027. def deserialize_BlockLocator(d):
  1028. result = "Block Locator top: "+d['hashes'][0][::-1].encode('hex_codec')
  1029. return result
  1030. def parse_setting(setting, vds):
  1031. if setting[0] == "f": # flag (boolean) settings
  1032. return str(vds.read_boolean())
  1033. elif setting[0:4] == "addr": # CAddress
  1034. d = parse_CAddress(vds)
  1035. return deserialize_CAddress(d)
  1036. elif setting == "nTransactionFee":
  1037. return vds.read_int64()
  1038. elif setting == "nLimitProcessors":
  1039. return vds.read_int32()
  1040. return 'unknown setting'
  1041. class SerializationError(Exception):
  1042. """ Thrown when there's a problem deserializing or serializing """
  1043. class BCDataStream(object):
  1044. def __init__(self):
  1045. self.input = None
  1046. self.read_cursor = 0
  1047. def clear(self):
  1048. self.input = None
  1049. self.read_cursor = 0
  1050. def write(self, bytes): # Initialize with string of bytes
  1051. if self.input is None:
  1052. self.input = bytes
  1053. else:
  1054. self.input += bytes
  1055. def map_file(self, file, start): # Initialize with bytes from file
  1056. self.input = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
  1057. self.read_cursor = start
  1058. def seek_file(self, position):
  1059. self.read_cursor = position
  1060. def close_file(self):
  1061. self.input.close()
  1062. def read_string(self):
  1063. # Strings are encoded depending on length:
  1064. # 0 to 252 : 1-byte-length followed by bytes (if any)
  1065. # 253 to 65,535 : byte'253' 2-byte-length followed by bytes
  1066. # 65,536 to 4,294,967,295 : byte '254' 4-byte-length followed by bytes
  1067. # ... and the Bitcoin client is coded to understand:
  1068. # greater than 4,294,967,295 : byte '255' 8-byte-length followed by bytes of string
  1069. # ... but I don't think it actually handles any strings that big.
  1070. if self.input is None:
  1071. raise SerializationError("call write(bytes) before trying to deserialize")
  1072. try:
  1073. length = self.read_compact_size()
  1074. except IndexError:
  1075. raise SerializationError("attempt to read past end of buffer")
  1076. return self.read_bytes(length)
  1077. def write_string(self, string):
  1078. # Length-encoded as with read-string
  1079. self.write_compact_size(len(string))
  1080. self.write(string)
  1081. def read_bytes(self, length):
  1082. try:
  1083. result = self.input[self.read_cursor:self.read_cursor+length]
  1084. self.read_cursor += length
  1085. return result
  1086. except IndexError:
  1087. raise SerializationError("attempt to read past end of buffer")
  1088. return ''
  1089. def read_boolean(self): return self.read_bytes(1)[0] != chr(0)
  1090. def read_int16(self): return self._read_num('<h')
  1091. def read_uint16(self): return self._read_num('<H')
  1092. def read_int32(self): return self._read_num('<i')
  1093. def read_uint32(self): return self._read_num('<I')
  1094. def read_int64(self): return self._read_num('<q')
  1095. def read_uint64(self): return self._read_num('<Q')
  1096. def write_boolean(self, val): return self.write(chr(1) if val else chr(0))
  1097. def write_int16(self, val): return self._write_num('<h', val)
  1098. def write_uint16(self, val): return self._write_num('<H', val)
  1099. def write_int32(self, val): return self._write_num('<i', val)
  1100. def write_uint32(self, val): return self._write_num('<I', val)
  1101. def write_int64(self, val): return self._write_num('<q', val)
  1102. def write_uint64(self, val): return self._write_num('<Q', val)
  1103. def read_compact_size(self):
  1104. size = ord(self.input[self.read_cursor])
  1105. self.read_cursor += 1
  1106. if size == 253:
  1107. size = self._read_num('<H')
  1108. elif size == 254:
  1109. size = self._read_num('<I')
  1110. elif size == 255:
  1111. size = self._read_num('<Q')
  1112. return size
  1113. def write_compact_size(self, size):
  1114. if size < 0:
  1115. raise SerializationError("attempt to write size < 0")
  1116. elif size < 253:
  1117. self.write(chr(size))
  1118. elif size < 2**16:
  1119. self.write('\xfd')
  1120. self._write_num('<H', size)
  1121. elif size < 2**32:
  1122. self.write('\xfe')
  1123. self._write_num('<I', size)
  1124. elif size < 2**64:
  1125. self.write('\xff')
  1126. self._write_num('<Q', size)
  1127. def _read_num(self, format):
  1128. (i,) = struct.unpack_from(format, self.input, self.read_cursor)
  1129. self.read_cursor += struct.calcsize(format)
  1130. return i
  1131. def _write_num(self, format, num):
  1132. s = struct.pack(format, num)
  1133. self.write(s)
  1134. def open_wallet(db_env, db_file="wallet.dat", writable=False):
  1135. db = DB(db_env)
  1136. flags = DB_THREAD | (DB_CREATE if writable else DB_RDONLY)
  1137. try:
  1138. r = db.open(db_file, "main", DB_BTREE, flags)
  1139. except DBError:
  1140. r = True
  1141. if r is not None:
  1142. logging.error("Couldn't open " + db_file + "/main. Try quitting Bitcoin and running this again.")
  1143. sys.exit(1)
  1144. return db
  1145. def parse_wallet(db, item_callback):
  1146. kds = BCDataStream()
  1147. vds = BCDataStream()
  1148. for (key, value) in db.items():
  1149. d = { }
  1150. kds.clear(); kds.write(key)
  1151. vds.clear(); vds.write(value)
  1152. type = kds.read_string()
  1153. d["__key__"] = key
  1154. d["__value__"] = value
  1155. d["__type__"] = type
  1156. try:
  1157. if type == "tx":
  1158. d["tx_id"] = kds.read_bytes(32)
  1159. elif type == "name":
  1160. d['hash'] = kds.read_string()
  1161. d['name'] = vds.read_string()
  1162. elif type == "version":
  1163. d['version'] = vds.read_uint32()
  1164. elif type == "minversion":
  1165. d['minversion'] = vds.read_uint32()
  1166. elif type == "setting":
  1167. d['setting'] = kds.read_string()
  1168. d['value'] = parse_setting(d['setting'], vds)
  1169. elif type == "key":
  1170. d['public_key'] = kds.read_bytes(kds.read_compact_size())
  1171. d['private_key'] = vds.read_bytes(vds.read_compact_size())
  1172. elif type == "wkey":
  1173. d['public_key'] = kds.read_bytes(kds.read_compact_size())
  1174. d['private_key'] = vds.read_bytes(vds.read_compact_size())
  1175. d['created'] = vds.read_int64()
  1176. d['expires'] = vds.read_int64()
  1177. d['comment'] = vds.read_string()
  1178. elif type == "ckey":
  1179. d['public_key'] = kds.read_bytes(kds.read_compact_size())
  1180. d['crypted_key'] = vds.read_bytes(vds.read_compact_size())
  1181. elif type == "mkey":
  1182. d['nID'] = kds.read_int32()
  1183. d['crypted_key'] = vds.read_bytes(vds.read_compact_size())
  1184. d['salt'] = vds.read_bytes(vds.read_compact_size())
  1185. d['nDerivationMethod'] = vds.read_int32()
  1186. d['nDeriveIterations'] = vds.read_int32()
  1187. d['vchOtherDerivationParameters'] = vds.read_bytes(vds.read_compact_size())
  1188. elif type == "defaultkey":
  1189. d['key'] = vds.read_bytes(vds.read_compact_size())
  1190. elif type == "pool":
  1191. d['n'] = kds.read_int64()
  1192. d['nVersion'] = vds.read_int32()
  1193. d['nTime'] = vds.read_int64()
  1194. d['public_key'] = vds.read_bytes(vds.read_compact_size())
  1195. elif type == "acc":
  1196. d['account'] = kds.read_string()
  1197. d['nVersion'] = vds.read_int32()
  1198. d['public_key'] = vds.read_bytes(vds.read_compact_size())
  1199. elif type == "acentry":
  1200. d['account'] = kds.read_string()
  1201. d['n'] = kds.read_uint64()
  1202. d['nVersion'] = vds.read_int32()
  1203. d['nCreditDebit'] = vds.read_int64()
  1204. d['nTime'] = vds.read_int64()
  1205. d['otherAccount'] = vds.read_string()
  1206. d['comment'] = vds.read_string()
  1207. elif type == "bestblock":
  1208. d['nVersion'] = vds.read_int32()
  1209. d.update(parse_BlockLocator(vds))
  1210. item_callback(type, d)
  1211. except Exception, e:
  1212. traceback.print_exc()
  1213. print("ERROR parsing wallet.dat, type %s" % type)
  1214. print("key data in hex: %s"%key.encode('hex_codec'))
  1215. print("value data in hex: %s"%value.encode('hex_codec'))
  1216. sys.exit(1)
  1217. def update_wallet(db, type, data):
  1218. """Write a single item to the wallet.
  1219. db must be open with writable=True.
  1220. type and data are the type code and data dictionary as parse_wallet would
  1221. give to item_callback.
  1222. data's __key__, __value__ and __type__ are ignored; only the primary data
  1223. fields are used.
  1224. """
  1225. d = data
  1226. kds = BCDataStream()
  1227. vds = BCDataStream()
  1228. # Write the type code to the key
  1229. kds.write_string(type)
  1230. vds.write("") # Ensure there is something
  1231. try:
  1232. if type == "tx":
  1233. raise NotImplementedError("Writing items of type 'tx'")
  1234. kds.write(d['tx_id'])
  1235. elif type == "name":
  1236. kds.write_string(d['hash'])
  1237. vds.write_string(d['name'])
  1238. elif type == "version":
  1239. vds.write_uint32(d['version'])
  1240. elif type == "minversion":
  1241. vds.write_uint32(d['minversion'])
  1242. elif type == "setting":
  1243. raise NotImplementedError("Writing items of type 'setting'")
  1244. kds.write_string(d['setting'])
  1245. #d['value'] = parse_setting(d['setting'], vds)
  1246. elif type == "key":
  1247. kds.write_string(d['public_key'])
  1248. vds.write_string(d['private_key'])
  1249. elif type == "wkey":
  1250. kds.write_string(d['public_key'])
  1251. vds.write_string(d['private_key'])
  1252. vds.write_int64(d['created'])
  1253. vds.write_int64(d['expires'])
  1254. vds.write_string(d['comment'])
  1255. elif type == "ckey":
  1256. kds.write_string(d['public_key'])
  1257. vds.write_string(d['crypted_key'])
  1258. elif type == "defaultkey":
  1259. vds.write_string(d['key'])
  1260. elif type == "pool":
  1261. kds.write_int64(d['n'])
  1262. vds.write_int32(d['nVersion'])
  1263. vds.write_int64(d['nTime'])
  1264. vds.write_string(d['public_key'])
  1265. elif type == "acc":
  1266. kds.write_string(d['account'])
  1267. vds.write_int32(d['nVersion'])
  1268. vds.write_string(d['public_key'])
  1269. elif type == "acentry":
  1270. kds.write_string(d['account'])
  1271. kds.write_uint64(d['n'])
  1272. vds.write_int32(d['nVersion'])
  1273. vds.write_int64(d['nCreditDebit'])
  1274. vds.write_int64(d['nTime'])
  1275. vds.write_string(d['otherAccount'])
  1276. vds.write_string(d['comment'])
  1277. elif type == "bestblock":
  1278. vds.write_int32(d['nVersion'])
  1279. vds.write_compact_size(len(d['hashes']))
  1280. for h in d['hashes']:
  1281. vds.write(h)
  1282. else:
  1283. print "Unknown key type: "+type
  1284. # Write the key/value pair to the database
  1285. db.put(kds.input, vds.input)
  1286. except Exception, e:
  1287. print("ERROR writing to wallet.dat, type %s"%type)
  1288. print("data dictionary: %r"%data)
  1289. traceback.print_exc()
  1290. def read_wallet(json_db, db_env, db_file, print_wallet, print_wallet_transactions, transaction_filter):
  1291. db = open_wallet(db_env, db_file)
  1292. json_db['keys'] = []
  1293. json_db['pool'] = []
  1294. json_db['names'] = {}
  1295. def item_callback(type, d):
  1296. global password
  1297. if type == "name":
  1298. json_db['names'][d['hash']] = d['name']
  1299. elif type == "version":
  1300. json_db['version'] = d['version']
  1301. elif type == "minversion":
  1302. json_db['minversion'] = d['minversion']
  1303. elif type == "setting":
  1304. if not json_db.has_key('settings'): json_db['settings'] = {}
  1305. json_db["settings"][d['setting']] = d['value']
  1306. elif type == "defaultkey":
  1307. json_db['defaultkey'] = public_key_to_bc_address(d['key'])
  1308. elif type == "key":
  1309. addr = public_key_to_bc_address(d['public_key'])
  1310. compressed = d['public_key'][0] != '\04'
  1311. sec = SecretToASecret(PrivKeyToSecret(d['private_key']), compressed)
  1312. private_keys.append(sec)
  1313. json_db['keys'].append({'addr' : addr, 'sec' : sec})
  1314. # json_db['keys'].append({'addr' : addr, 'sec' : sec,
  1315. # 'secret':PrivKeyToSecret(d['private_key']).encode('hex'),
  1316. # 'pubkey':d['public_key'].encode('hex'),
  1317. # 'privkey':d['private_key'].encode('hex')})
  1318. elif type == "wkey":
  1319. if not json_db.has_key('wkey'): json_db['wkey'] = []
  1320. json_db['wkey']['created'] = d['created']
  1321. elif type == "ckey":
  1322. addr = public_key_to_bc_address(d['public_key'])
  1323. ckey = d['crypted_key']
  1324. pubkey = d['public_key']
  1325. json_db['keys'].append( {'addr' : addr, 'ckey': ckey.encode('hex'), 'pubkey': pubkey.encode('hex') })
  1326. elif type == "mkey":
  1327. mkey = {}
  1328. mkey['nID'] = d['nID']
  1329. mkey['crypted_key'] = d['crypted_key'].encode('hex')
  1330. mkey['salt'] = d['salt'].encode('hex')
  1331. mkey['nDeriveIterations'] = d['nDeriveIterations']
  1332. mkey['nDerivationMethod'] = d['nDerivationMethod']
  1333. mkey['vchOtherDerivationParameters'] = d['vchOtherDerivationParameters'].encode('hex')
  1334. json_db['mkey'] = mkey
  1335. if password == None and \
  1336. ('json' in opts or 'keysforaddrs' in opts or 'keys' in opts):
  1337. from mmgen.util import get_bitcoind_passphrase
  1338. password = get_bitcoind_passphrase("Enter password: ",opts)
  1339. if password != None:
  1340. global crypter
  1341. if crypter == 'pycrypto':
  1342. crypter = Crypter_pycrypto()
  1343. elif crypter == 'ssl':
  1344. crypter = Crypter_ssl()
  1345. else:
  1346. crypter = Crypter_pure()
  1347. logging.warning("pycrypto or libssl not found, decryption may be slow")
  1348. res = crypter.SetKeyFromPassphrase(password, d['salt'], d['nDeriveIterations'], d['nDerivationMethod'])
  1349. if res == 0:
  1350. logging.error("Unsupported derivation method")
  1351. sys.exit(1)
  1352. masterkey = crypter.Decrypt(d['crypted_key'])
  1353. crypter.SetKey(masterkey)
  1354. elif type == "pool":
  1355. json_db['pool'].append( {'n': d['n'], 'addr': public_key_to_bc_address(d['public_key']), 'nTime' : d['nTime'] } )
  1356. elif type == "acc":
  1357. json_db['acc'] = d['account']
  1358. # msg("Account %s (current key: %s)"%(d['account'], public_key_to_bc_address(d['public_key'])))
  1359. elif type == "acentry":
  1360. json_db['acentry'] = (d['account'], d['nCreditDebit'], d['otherAccount'], time.ctime(d['nTime']), d['n'], d['comment'])
  1361. elif type == "bestblock":
  1362. json_db['bestblock'] = d['hashes'][0][::-1].encode('hex_codec')
  1363. else:
  1364. json_db[type] = 'unsupported'
  1365. parse_wallet(db, item_callback)
  1366. db.close()
  1367. for k in json_db['keys']:
  1368. addr = k['addr']
  1369. if addr in json_db['names'].keys():
  1370. k["label"] = json_db['names'][addr]
  1371. else:
  1372. k["reserve"] = 1
  1373. if 'mkey' in json_db.keys() and password != None:
  1374. check = True
  1375. for k in json_db['keys']:
  1376. ckey = k['ckey'].decode('hex')
  1377. public_key = k['pubkey'].decode('hex')
  1378. crypter.SetIV(Hash(public_key))
  1379. secret = crypter.Decrypt(ckey)
  1380. compressed = public_key[0] != '\04'
  1381. if check:
  1382. check = False
  1383. pkey = EC_KEY(int('0x' + secret.encode('hex'), 16))
  1384. if public_key != GetPubKey(pkey, compressed):
  1385. logging.error("wrong password")
  1386. sys.exit(1)
  1387. sec = SecretToASecret(secret, compressed)
  1388. k['sec'] = sec
  1389. k['secret'] = secret.encode('hex')
  1390. del(k['ckey'])
  1391. del(k['secret'])
  1392. del(k['pubkey'])
  1393. private_keys.append(sec)
  1394. del(json_db['pool'])
  1395. del(json_db['names'])
  1396. # Non-portable. For Windows, works only if supplied filename is in current dir
  1397. # main()
  1398. import os.path
  1399. infile = os.path.abspath(cmd_args[0])
  1400. db_dir,db_file = os.path.dirname(infile),os.path.basename(infile)
  1401. # print "[%s] [%s]" % (db_dir,db_file)
  1402. db_env = create_env(db_dir)
  1403. read_wallet(json_db, db_env, db_file, True, True, "")
  1404. if json_db.get('minversion') > max_version:
  1405. print "Version mismatch (must be <= %d)" % max_version
  1406. exit(1)
  1407. wallet_addrs = [i['addr'] for i in json_db['keys']]
  1408. if 'json' in opts:
  1409. data = [json.dumps(json_db, sort_keys=True, indent=4)]
  1410. ext,what = "json","json dump"
  1411. elif 'keys' in opts:
  1412. data = sorted([i['sec'] for i in json_db['keys']])
  1413. ext,what = "keys","private keys"
  1414. elif 'addrs' in opts:
  1415. data = sorted([i['addr'] for i in json_db['keys']])
  1416. ext,what = "addrs","addresses"
  1417. elif 'keysforaddrs' in opts:
  1418. from mmgen.util import get_lines_from_file
  1419. usr_addrs = set(get_lines_from_file(opts['keysforaddrs'],"addresses",remove_comments=True))
  1420. data = [i['sec'] for i in json_db['keys'] if i['addr'] in usr_addrs]
  1421. ext,what = "keys","private keys"
  1422. if len(data) < len(usr_addrs):
  1423. msg("Warning: not all requested keys found")
  1424. len_arg = "%s" % len(wallet_addrs) \
  1425. if len(data) == len(wallet_addrs) or ext == "json" \
  1426. else "%s:%s" % (len(data),len(wallet_addrs))
  1427. from mmgen.util import make_chksum_8,write_walletdat_dump_to_file,write_to_stdout
  1428. wallet_id = make_chksum_8(str(sorted(wallet_addrs)))
  1429. data = "\n".join(data) + "\n"
  1430. # Output data
  1431. if 'stdout' in opts:
  1432. confirm = False if 'addrs' in opts else True
  1433. write_to_stdout(data,"secret keys",confirm)
  1434. elif not sys.stdout.isatty():
  1435. write_to_stdout(data,"secret keys",confirm=False)
  1436. else:
  1437. write_walletdat_dump_to_file(wallet_id, data, len_arg, ext, what, opts)